Django: app level variables
<p>I've created a Django-rest-framework app. It exposes some API which does some get/set operations in the MySQL DB. </p>

<p>I have a requirement of making an HTTP request to another server and piggyback this response along with the usual response. I'm trying to use a self-made HTTP connection pool to make HTTP requests instead of making new connections on each request.</p>

<p>What is the most appropriate place to keep this app level HTTP connection pool object?</p>

<p>I've looked around for it &amp; there are multiple solutions each with some cons. Here are some:</p>

<ol>
<li><p>To make a singleton class of the pool in a diff file, but this is not a good pythonic way to do things. There are various discussions over why not to use singleton design pattern.</p>

<p>Also, I don't know how intelligent it would be to pool a pooler? (:P)</p></li>
<li>To keep it in <strong>init</strong>.py of the app dir. The issue with that are as follows:

<ul>
<li>It should only contain imports &amp; things related to that.</li>
<li>It will be difficult to unit test the code because the import would happen before mocking and it would actually try to hit the API.</li>
</ul></li>
<li><p>To use sessions, but I guess that makes more sense if it was something user session specific, like a user specific number, etc</p>

<p>Also, the object needs to be serializable. I don't know how HTTP Connection pool can be serialized.</p></li>
<li>To keep it global in views.py but that also is discouraged.</li>
</ol>

<p>What is the best place to store such app/global level variables?</p>

<p>A possible solution is to implement a custom Django middleware, as described in <a href="https://docs.djangoproject.com/ja/1.9/topics/http/middleware/" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/http/middleware/</a>.</p>

<p>You could initialize the HTTP connection pool in the middleware's <strong>__init__</strong> method, which is only called <em>once</em> at the first request. Then, start the HTTP request during <strong>process_request</strong> and on <strong>process_response</strong> check it has finished (or wait for it) and append that response to the internal one.</p>

python django django-rest-framework global-variables