我想在我的项目中创建自定义中间件。但我收到这样的错误:
[ django.core.exceptions.ImproperlyConfigured: WSGI application 'custommiddle.wsgi.application' could not be loaded; Error importing module. ]
我认为问题可能出在我的python版本上,我正在使用版本 3.7 。
这是我的文件夹结构:
custommiddle/ # project name
__init__.py
settings.py
urls.py
wsgi.py
cmiddle/ # app name
middle/ # directory
__init__.py
middleware.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
middleware.py
from django.conf import settings
class StackOverflowMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_exception(self, request, exception):
if settings.DEBUG:
print (exception.__class__.__name__)
print (exception.message)
return None
settings.py
INSTALLED_APPS = [ 'soet' ]
MIDDLEWARE_CLASSES = [ 'soet.middleware.StackOverFlowMiddleware' ]
答案 0 :(得分:0)
我认为您已经正确编辑了 settings.py 。因为中间件部分似乎正确。您可以确认是否正确编辑了settings.py,如下所示
settings.py
import os
BASE_DIR = ...
SECRET_KEY = ...
DEBUG = ...
ALLOWED_HOSTS = ...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'soet', # your apps
]
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',
'soet.middleware.StackOverFlowMiddleware' # your_middleware
]
.
.
.
答案 1 :(得分:0)
soet 使用的是python2语法。在Python 3中, print 语句已替换为 print()函数。
查看位于https://github.com/vitorfs/soet/blob/master/soet/middleware.py的代码库 并且您可以将其更改为python3语法(基本上只查看print语句)。
在以下位置访问django文档以创建中间件:https://docs.djangoproject.com/en/2.2/topics/http/middleware/