Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: app level variables

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?

like image 639
Pankaj Singhal Avatar asked Sep 14 '16 12:09

Pankaj Singhal


1 Answers

This thread is a bit old but still could be googled. generally, if you want a component to be accessible among several apps in your Django project you can put it in a general or core app as a Util or whatever.

in terms of reusability and app-specific you can use a Factory with a cache mechanism something like:

class ConnectionPool:
    pass


@dataclass
class ConnectionPoolFactory:
    connection_pool_cache: dict[str: ConnectionPool] = field(default_factory=dict)

    def get_connection(self, app_name: str) -> ConnectionPool:
        if self.connection_pool_cache.get(app_name, None) is None:
            self.connection_pool_cache[app_name] = ConnectionPool()
        return self.connection_pool_cache[app_name]
like image 69
omid Avatar answered Oct 19 '22 17:10

omid