首页 > 解决方案 > 自定义错误处理程序在 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

标签: pythonflask

解决方案


我已经复制了您的案例,但在我的案例中,自定义错误处理程序有效。我从云外壳编辑器创建了这个示例。我与您分享我的代码,希望对您有所帮助:

应用程序.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


推荐阅读