python - 自定义错误处理程序在 Google Cloud Run 上不起作用
问题描述
我正在将我的 Python 应用程序部署到网络上,并为此使用 Google 的 Cloud Run。到目前为止一切正常,但errorhandler
没有。
我flask limiter
用来限制路由的请求。通过以下代码,我呈现了一个名为的模板,该模板429.html
应显示在429-error
. 在我的本地机器上它确实如此,在云运行上我得到了flask limiter
返回的基本页面。
错误页面
我的代码errorhandler
如下:
@app.errorhandler(429)
def page_not_found(e):
# note that we set the 404 status explicitly
db = onpage_functions.get_stats()
return render_template('static/429.html', db=db), 429
解决方案
我已经复制了您的案例,但在我的案例中,自定义错误处理程序有效。我从云外壳编辑器创建了这个示例。我与您分享我的代码,希望对您有所帮助:
应用程序.py:
"""
A sample Hello World server.
"""
import os
import requests
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask import Flask, render_template
# pylint: disable=C0103
app = Flask(__name__)
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["2 per minute", "1 per second"],
)
@app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
message = "It's running!"
"""Get Cloud Run environment variables."""
service = os.environ.get('K_SERVICE', 'Unknown service')
revision = os.environ.get('K_REVISION', 'Unknown revision')
return render_template('index.html',
message=message,
Service=service,
Revision=revision)
@app.errorhandler(429)
def page_not_foundes(e):
# note that we set the 429 status explicitly
return render_template('429.html')
if __name__ == '__main__':
server_port = os.environ.get('PORT', '8080')
app.run(debug=False, port=server_port, host='0.0.0.0')
要求.txt:
Flask==1.1.2
requests==2.25.1
ptvsd==4.3.2 # Required for debugging.
Flask-Limiter==1.4
自定义 html 是在目录模板 429.html 上创建的
<h1>MY CUSTOM 429</h1>
在我发送两个请求后,我成功地看到了我的自定义错误。我希望我的代码可以帮助你:D
推荐阅读
- ios - iOS 崩溃 - 在当前参数寄存器中找到选择器名称:保留
- c# - C# - System.Timer Tick 事件处理的问题
- linux-kernel - FPGA 上的 DMA 无法访问使用 GFP_KERNEL 标志分配的内核内存
- c# - 使用 StreamWriter 不可写
- delphi - 无效的指针操作——不知道为什么
- asp.net - 如何让输入标签文本与顶部对齐?
- testflight - 被提示使用带有 Testflight 公共共享链接的兑换代码
- android - 为什么我无法在 android studio 中播放声音
- c# - .Net Core 2.1 CORS 和 Firebase JWT 授权
- java - 对输入流和从文件读取感到困惑