Middleware acts as a hook into Django's request/response processing
at a low level and it is light. The hooks are available for request,
response, view, template_response, and exception processing. The hook
might need to modify the request before the view handles it, it might
need to log information about the request for debugging purposes, check a
cookie to set the local, and so on.
Context processors just modify the context. Context is a key value mapping with variables passed to a template. A context processor takes a request object as its argument, and returns a dictionary of items that get merged into the context. The context gets rendered to your template as per your view and it attaches whatever else your context processors merge in. You can think of it as a global context variable(s), available to you at all your templates.
Both are fairly simple to write and have their purpose. Here is a diagram that shows where middleware and context fit in in a typical django flow:
Django Flowchart
Context processors just modify the context. Context is a key value mapping with variables passed to a template. A context processor takes a request object as its argument, and returns a dictionary of items that get merged into the context. The context gets rendered to your template as per your view and it attaches whatever else your context processors merge in. You can think of it as a global context variable(s), available to you at all your templates.
Both are fairly simple to write and have their purpose. Here is a diagram that shows where middleware and context fit in in a typical django flow:
Django Flowchart
- User requests a page
- Request reaches Request Middlewares, which could manipulate or answer the request
- The URLConffinds the related View using urls.py
- View Middlewares are called, which could manipulate or answer the request
- The view function is invoked
- The view could optionally access data through models
- All model-to-DB interactions are done via a manager
- Views could use a special context if needed
- The context is passed to the Template for rendering
No comments:
Post a Comment