Django: app level variables

2019-01-12 07:06发布

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

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.

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

I've looked around for it & there are multiple solutions each with some cons. Here are some:

  1. 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.

    Also, I don't know how intelligent it would be to pool a pooler? (:P)

  2. To keep it in init.py of the app dir. The issue with that are as follows:
    • It should only contain imports & things related to that.
    • 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.
  3. To use sessions, but I guess that makes more sense if it was something user session specific, like a user specific number, etc

    Also, the object needs to be serializable. I don't know how HTTP Connection pool can be serialized.

  4. To keep it global in views.py but that also is discouraged.

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

1条回答
时光不老,我们不散
2楼-- · 2019-01-12 07:47

A possible solution is to implement a custom Django middleware, as described in https://docs.djangoproject.com/ja/1.9/topics/http/middleware/.

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

查看更多
登录 后发表回答