{"id":299,"date":"2016-12-29T01:17:50","date_gmt":"2016-12-28T17:17:50","guid":{"rendered":"http:\/\/vinta.ws\/code\/?p=299"},"modified":"2026-03-17T01:16:03","modified_gmt":"2026-03-16T17:16:03","slug":"lazy-evaluation-in-django-middlewares","status":"publish","type":"post","link":"https:\/\/vinta.ws\/code\/lazy-evaluation-in-django-middlewares.html","title":{"rendered":"Lazy evaluation in Django middlewares"},"content":{"rendered":"<p>Attach a lazily evaluated function as a property of <code>request<\/code> in a middleware.<\/p>\n<pre class=\"line-numbers\"><code class=\"language-py\">from django.contrib.gis.geoip import GeoIP\nfrom django.utils.functional import SimpleLazyObject\n\ndef get_country_code(request):\n    g = GeoIP()\n    location = g.country(request.META['REMOTE_ADDR'])\n    country_code = location.get('country_code', 'TW')\n\n    return country_code\n\nclass CountryAndSiteMiddleware(object):\n\n    def process_request(self, request):\n        request.COUNTRY_CODE = SimpleLazyObject(lambda: get_country_code(request))<\/code><\/pre>\n<p>Then you could use <code>request.COUNTRY_CODE<\/code> whenever you want.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Attach a lazy evaluated function as a property of request in a middleware.<\/p>\n","protected":false},"author":1,"featured_media":301,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4,116],"tags":[13,2],"class_list":["post-299","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-about-python","category-about-web-development","tag-django","tag-python"],"_links":{"self":[{"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/posts\/299","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/comments?post=299"}],"version-history":[{"count":0,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/posts\/299\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/media\/301"}],"wp:attachment":[{"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/media?parent=299"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/categories?post=299"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/vinta.ws\/code\/wp-json\/wp\/v2\/tags?post=299"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}