我有一个问题,即在项目中的每个python应用程序上运行任何函数的最佳方法是什么? 例如,我有一个项目--bbCms包含2个应用程序 - 文章和董事会。 我想在这些应用程序的每个页面上运行doSomething函数。 在PHP上我可以创建文件,例如functions.php,类型代码和每个app里面的require运行这个函数。
如何在Python(django)中解决这个问题?
答案 0 :(得分:0)
注意:请以租约
views.py
更新您的代码,以了解您的项目是如何运作的。
首先,django使用views.py
处理您的请求。
如果您使用Function based View
,则只需执行此操作:
def doSomething():
# do Something
return something
def index(request):
doSomething() # add this for all views functions
return render(request, 'index.html')
或者您可以制作自己的middleware.py
:
def simple_middleware(get_response):
# One-time configuration and initialization.
def middleware(request):
# Change here!! this code will be executed for all requests
# Code to be executed for each request before
# the view (and later middleware) are called.
response = get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
return middleware
并添加到settings.py
:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myproject.middleware.simple_middware', # add this!
]
参考:https://docs.djangoproject.com/en/1.10/topics/http/middleware/