如何在 Django 视图之外加载数据?
How to load data outside Django view?
如果我有一些 Django 视图,如 'first'、'second' 等,我想在这些视图之外加载一些数据,但在视图内部使用它。
这里有一个例子来理解我的想法。
#function execution time is long, that is why i want to laod it only once when run programm.
fetched_data_from_postgres = some function which load data from postgres and return list with postgres data
def first(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("first VIEW")
def second(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("secondVIEW")
def third(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("third VIEW")
当我 运行 我的 django 项目像这样 python manage.py runserver
但是当我 运行 使用 gunicorn 或 wsgi 时,当我可以指定工人数时,这种方法工作得很好,然后当工人改变时,这变量丢失,需要刷新页面才能让之前的工作人员获取该数据。太可笑了。
或者也许还有其他方法可以完成这项工作?
当您使用 python manage.py runserver
在本地启动项目时,此方法不起作用,它只能在项目启动时工作一次,然后每次都需要重新加载项目。这是因为 any_views.py
中的所有内容仅在项目启动时加载一次,但您的函数除外。所以你必须重新启动你的项目,以刷新你的 fetched_data_from_postgres
变量
更好的方法,创建一个脚本 fetch_script.py
,将函数 some function which load data from postgres and return list with postgres data
移到其中,然后在 views.py
内部调用它,而不是在
外部
避免多次加载数据并防止此函数 fetched_data_from_postgres
到 运行 两次的最佳解决方案是 与 Django 一起使用缓存框架 .查看文档以获取更多详细信息:
https://docs.djangoproject.com/en/stable/topics/cache/
设置相对容易,应该可以完美解决您的问题。如果您觉得这有点矫枉过正,那么问题是您真的需要速度吗?您确定您没有尝试过早优化吗?
如果我有一些 Django 视图,如 'first'、'second' 等,我想在这些视图之外加载一些数据,但在视图内部使用它。
这里有一个例子来理解我的想法。
#function execution time is long, that is why i want to laod it only once when run programm.
fetched_data_from_postgres = some function which load data from postgres and return list with postgres data
def first(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("first VIEW")
def second(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("secondVIEW")
def third(request):
#and the i want to use that previous value in all my views
fetched_data_from_postgres = do something
return HttpResponse("third VIEW")
当我 运行 我的 django 项目像这样 python manage.py runserver
但是当我 运行 使用 gunicorn 或 wsgi 时,当我可以指定工人数时,这种方法工作得很好,然后当工人改变时,这变量丢失,需要刷新页面才能让之前的工作人员获取该数据。太可笑了。
或者也许还有其他方法可以完成这项工作?
当您使用 python manage.py runserver
在本地启动项目时,此方法不起作用,它只能在项目启动时工作一次,然后每次都需要重新加载项目。这是因为 any_views.py
中的所有内容仅在项目启动时加载一次,但您的函数除外。所以你必须重新启动你的项目,以刷新你的 fetched_data_from_postgres
变量
更好的方法,创建一个脚本 fetch_script.py
,将函数 some function which load data from postgres and return list with postgres data
移到其中,然后在 views.py
内部调用它,而不是在
避免多次加载数据并防止此函数 fetched_data_from_postgres
到 运行 两次的最佳解决方案是 与 Django 一起使用缓存框架 .查看文档以获取更多详细信息:
https://docs.djangoproject.com/en/stable/topics/cache/
设置相对容易,应该可以完美解决您的问题。如果您觉得这有点矫枉过正,那么问题是您真的需要速度吗?您确定您没有尝试过早优化吗?