{"id":75887,"date":"2020-01-20T12:28:59","date_gmt":"2020-01-20T06:58:59","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75887"},"modified":"2024-04-12T14:17:41","modified_gmt":"2024-04-12T08:47:41","slug":"middleware-methods","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/","title":{"rendered":"Middleware Methods"},"content":{"rendered":"<p>During the request phase, before calling the view, Django applies middleware in the order it\u2019s defined in MIDDLEWARE_CLASSES, top-down. Two hooks are available:<\/p>\n<ul>\n<li>process_request()<\/li>\n<li>process_view()<\/li>\n<\/ul>\n<p>During the response phase, after calling the view, middleware are applied in reverse order, from the bottom up. Three hooks are available:<\/p>\n<ul>\n<li>process_exception()<\/li>\n<li>process_template_response()<\/li>\n<li>process_response()<\/li>\n<\/ul>\n<p>If you prefer, you can also think of it like an onion: each middleware class is a layer that wraps the view. The behavior of each hook is described below.<\/p>\n<h3>Writing Your Own Middleware<\/h3>\n<p>Writing your own middleware is easy. Each middleware component is a single Python class that defines one or more of the following methods:<br>\nprocess_request<br>\nMethod: process_request(request)<\/p>\n<ul>\n<li>request is an HttpRequest object.<\/li>\n<li>process_request() is called on each request, before Django decides which view to execute.<\/li>\n<\/ul>\n<p>It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_request() middleware, then, process_view() middleware, and finally, the appropriate view.<\/p>\n<p>If it returns an HttpResponse object, Django won\u2019t bother calling any other request, view or exception middleware, or the appropriate view; it\u2019ll apply response middleware to that HttpResponse, and return the result.<\/p>\n<h3>process_view<\/h3>\n<p>Method: process_view(request, view_func, view_args, view_kwargs)<\/p>\n<ul>\n<li>request is an HttpRequest object.<\/li>\n<li>view_func is the Python function that Django is about to use. (It\u2019s the actual function object, not the name of the function as a string.)<\/li>\n<li>view_args is a list of positional arguments that will be passed to the view.<\/li>\n<li>view_kwargs is a dictionary of keyword arguments that will be passed to the view.<\/li>\n<li>Neither view_args nor view_kwargs include the first view argument (request). process_view() is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view.<\/li>\n<\/ul>\n<p>If it returns an HttpResponse object, Django won\u2019t bother calling any other view or exception middleware, or the appropriate view; it\u2019ll apply response middleware to that HttpResponse, and return the result.<br>\nAccessing request.POST inside middleware from process_request or process_view will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided.<\/p>\n<p>The CsrfViewMiddleware class can be considered an exception, as it provides the csrf_exempt() and csrf_protect() decorators which allow views to explicitly control at what point the CSRF validation should occur.<\/p>\n<h3>process_template_response<\/h3>\n<p>Method: process_template_response(request, response)<\/p>\n<ul>\n<li>request is an HttpRequest object.<\/li>\n<li>response is the TemplateResponse object (or equivalent) returned by a Django view or by a middleware.<br>\nprocess_template_response() is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent.<\/li>\n<\/ul>\n<p>It must return a response object that implements a render method. It could alter the given response by changing response.template_name and response.context_data, or it could create and return a brand-new TemplateResponse or equivalent.<\/p>\n<p>You don\u2019t need to explicitly render responses \u2013 responses will be automatically rendered once all template response middleware has been called.<\/p>\n<p>Middleware are run in reverse order during the response phase, which includes process_template_response().<\/p>\n<h3>process_response<\/h3>\n<p>Method: process_response(request, response)<\/p>\n<ul>\n<li>request is an HttpRequest object.<\/li>\n<li>response is the HttpResponse or StreamingHttpResponse object returned by a Django view or by a middleware. process_response() is called on all responses before they\u2019re returned to the browser. It must return an HttpResponse or StreamingHttpResponse object. It could alter the given response, or it could create and return a brand-new HttpResponse or StreamingHttpResponse.<\/li>\n<\/ul>\n<p>Unlike the process_request() and process_view() methods, the process_response() method is always called, even if the process_request() and process_view() methods of the same middleware class were skipped (because an earlier middleware method returned an HttpResponse). In particular, this means that your process_response() method cannot rely on setup done in process_request().<\/p>\n<p>Finally, remember that during the response phase, middleware are applied in reverse order, from the bottom up. This means classes defined at the end of MIDDLEWARE_CLASSES will be run first.<\/p>\n<p><strong>Dealing with streaming responses<\/strong> &#8211; Unlike HttpResponse, StreamingHttpResponse does not have a content attribute. As a result, middleware can no longer assume that all responses will have a content attribute. If they need access to the content, they must test for streaming responses and adjust their behavior accordingly:<\/p>\n<p>if response.streaming:<br>\nresponse.streaming_content = wrap_streaming_content(response.streaming_content)<br>\nelse:<br>\nresponse.content = alter_content(response.content)<\/p>\n<p>streaming_content should be assumed to be too large to hold in memory. Response middleware may wrap it in a new generator, but must not consume it. Wrapping is typically implemented as follows:<\/p>\n<p>def wrap_streaming_content(content):<br>\nfor chunk in content:<br>\nyield alter_content(chunk)<\/p>\n<h3>process_exception<\/h3>\n<p>Method: process_exception(request, exception)<\/p>\n<ul>\n<li>request is an HttpRequest object.<\/li>\n<li>exception is an Exception object raised by the view function.<\/li>\n<li>Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.<\/li>\n<\/ul>\n<p>Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.<\/p>\n<h3>__init__<\/h3>\n<p>Most middleware classes won\u2019t need an initializer since middleware classes are essentially placeholders for the process_* methods. If you do need some global state, you may use __init__ to set up. However, keep in mind a couple of caveats:<\/p>\n<ul>\n<li>Django initializes your middleware without any arguments, so you can\u2019t define __init__ as requiring any arguments.<\/li>\n<li>Unlike the process_* methods which get called once per request, __init__ gets called only once, when the Web server responds to the first request.<\/li>\n<\/ul>\n<h3>Marking middleware as unused<\/h3>\n<p>It\u2019s sometimes useful to determine at run-time whether a piece of middleware should be used. In these cases, your middleware\u2019s __init__ method may raise django.core.exceptions.MiddlewareNotUsed. Django will then remove that piece of middleware from the middleware process and a debug message will be logged to the django.request logger when DEBUG is set to True.<\/p>\n<h3>Additional Guidelines<\/h3>\n<ul>\n<li>Middleware classes don\u2019t have to subclass anything.<\/li>\n<li>The middleware class can live anywhere on your Python path. All Django cares about is that the MIDDLEWARE_CLASSES setting includes the path to it.<\/li>\n<li>Feel free to look at Django\u2019s available middleware for examples.<\/li>\n<li>If you write a middleware component that you think would be useful to other people, contribute to the community! Let us know and we\u2019ll consider adding it to Django.<\/li>\n<\/ul>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>During the request phase, before calling the view, Django applies middleware in the order it\u2019s defined in MIDDLEWARE_CLASSES, top-down. Two hooks are available: process_request() process_view() During the response phase, after calling the view, middleware are applied in reverse order, from the bottom up. Three hooks are available: process_exception() process_template_response() process_response() If you prefer, you can&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8852],"class_list":["post-75887","page","type-page","status-publish","hentry","category-django-web-development","tag-middleware-methods"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Middleware Methods - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Middleware Methods - Tutorial\" \/>\n<meta property=\"og:description\" content=\"During the request phase, before calling the view, Django applies middleware in the order it\u2019s defined in MIDDLEWARE_CLASSES, top-down. Two hooks are available: process_request() process_view() During the response phase, after calling the view, middleware are applied in reverse order, from the bottom up. Three hooks are available: process_exception() process_template_response() process_response() If you prefer, you can...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:41+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/\",\"name\":\"Middleware Methods - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:58:59+00:00\",\"dateModified\":\"2024-04-12T08:47:41+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Middleware Methods\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Middleware Methods - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/","og_locale":"en_US","og_type":"article","og_title":"Middleware Methods - Tutorial","og_description":"During the request phase, before calling the view, Django applies middleware in the order it\u2019s defined in MIDDLEWARE_CLASSES, top-down. Two hooks are available: process_request() process_view() During the response phase, after calling the view, middleware are applied in reverse order, from the bottom up. Three hooks are available: process_exception() process_template_response() process_response() If you prefer, you can...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:41+00:00","twitter_misc":{"Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/","name":"Middleware Methods - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:58:59+00:00","dateModified":"2024-04-12T08:47:41+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/middleware-methods\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Middleware Methods"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75887","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75887"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75887\/revisions"}],"predecessor-version":[{"id":83412,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75887\/revisions\/83412"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75887"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75887"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75887"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}