Django 正确保存全局 API 客户端实例变量的方法
Django proper way to save global API client instance variable
如何存储一些 API 客户端实例并使其在整个项目中可用。
API client instance
- 是一些 AppApi()
,我需要在整个 django 项目的不同视图(甚至应用程序)中调用它的方法。
对于我来说,有两种方式:
- 在一些核心 Django 应用
core/apps.py
模块中创建一个全局变量;
- 创建单例包装器;
在这种情况下最好和正确的方法是什么?
查看 django.db.connections
、django.db.router
、django.contrib.staticfiles.storage.staticfiles_storage
,还有更多。基本上,您创建一个模块变量,其中包含您的单例 class 实例,然后导入该变量:
from django.db import connections
vendor = connections['default'].vendor # always the same during app lifetime.
如何存储一些 API 客户端实例并使其在整个项目中可用。
API client instance
- 是一些 AppApi()
,我需要在整个 django 项目的不同视图(甚至应用程序)中调用它的方法。
对于我来说,有两种方式:
- 在一些核心 Django 应用
core/apps.py
模块中创建一个全局变量; - 创建单例包装器;
在这种情况下最好和正确的方法是什么?
查看 django.db.connections
、django.db.router
、django.contrib.staticfiles.storage.staticfiles_storage
,还有更多。基本上,您创建一个模块变量,其中包含您的单例 class 实例,然后导入该变量:
from django.db import connections
vendor = connections['default'].vendor # always the same during app lifetime.