python - 在 django 中,Middleware 两次触发错误
问题描述
我已经为一个应用程序创建了一些中间件,该应用程序根据登录用户检查一些标准。
如果其中任何一个失败,它就会启动错误,让用户知道。
问题是错误在页面顶部出现了两次。
中间件如下所示:
class RegistrationMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
print("In init of middleware")
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
print("Pre-view middle")
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
print("Post-view middle")
...logic stuff....
if invalid_entries:
for problem_reg in invalid_entries:
messages.error(
request, format_html(
"""
Please either
remove or change this registration.
"""
)
)
print('end of view reutrning response')
return response
该错误在页面上显示了两次。
我的控制台显示如下:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In init of middleware
Pre-view middle
this is a test of the get_user method
Post-view middle
end of view reutrning response
[25/Feb/2019 09:48:46] "GET /registrations/ HTTP/1.1" 200 21860
[25/Feb/2019 09:48:46] "GET /static/styles.css HTTP/1.1" 200 7082
[25/Feb/2019 09:48:46] "GET /static/registrations/style.css HTTP/1.1" 200 2282
[25/Feb/2019 09:48:46] "GET /static/registrations/index.js HTTP/1.1" 200 1885
[25/Feb/2019 09:48:46] "GET /static/all.min.js HTTP/1.1" 200 3738182
Pre-view middle
Post-view middle
this is a test of the get_user method
end of view reutrning response
Not Found: /favicon.ico
[25/Feb/2019 09:48:47] "GET /favicon.ico HTTP/1.1" 404 2586
我不确定中间件是否 100% 是检查此类错误的最佳解决方案,但我需要在应用程序中的每个视图上检查相同的代码位,因此这似乎是处理此问题的正确方法。
我只是想让它只触发一次——在视图渲染之前或之后都可以,但我只需要它来显示一个错误。
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible mt-4" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
{% endfor %}
解决方案
有逻辑之后:response = self.get_response(request)
导致问题和不一致的行为 - 因为在视图之后处理警报,进而导致在下次刷新和冲洗和重复时加载错误,并且大多数时候错误被重复。
将其移至视图处理之前解决了问题并有助于使其保持一致。
推荐阅读
- java - 使用 JpaPagingItemReader 时无法获取基于不同 pageSize 和 ChunkSize 的所有记录
- javascript - html 文件输入接受 .zip 文件
- rust - 没有为 Rocket 的 UUID 找到 Serde 的序列化实现
- sql - 字段作为子字符串
- sql - 使用 MyBatis 的 SQL 异常
- excel - 如何将网站数据抓取到 excel 中,但将结果附加到日志中
- ios - 在这种情况下,“ContentMode”对于类型查找不明确
- amazon-web-services - Invoke-WmiMethod:向 EC2 实例发送消息时访问被拒绝
- ios - UITableView 使用 willDisplay 拉取刷新和分页
- angular - 带字符串标记的角度动态 DI