【问题标题】:Custom Errorhandler doesn't work on Google Cloud Run [closed]自定义错误处理程序在 Google Cloud Run 上不起作用 [关闭]
【发布时间】:2021-05-20 18:46:03
【问题描述】:

我正在将我的 Python 应用程序部署到网络上,并为此使用 Google 的 Cloud Run。 到目前为止一切正常,但 errorhandler 没有。

我使用flask limiter 来限制路由的请求。通过以下代码,我渲染了一个名为429.html 的模板,它应该显示在429-error 中。在我的本地机器上确实如此,在 Cloud run 上,我得到了基本的 flask limiter 页面返回。 error page

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

【问题讨论】:

  • 我关闭了这个,因为目前无法从问题中包含的信息中明确得出您提供的答案(即这里只有足够的信息来猜测,而不是回答)。至少,根据您的回答,您需要在问题中包含足够多的代码,以表明app.run() 实际上早于@app.errorhandler(429)。这应该是一个比较简单的改变。一旦您edit 添加额外的代码/上下文,您的问题将自动放入重新打开审核队列中,以便重新审核。

标签: python flask


【解决方案1】:

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

app.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')

requeriments.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

【讨论】:

    【解决方案2】:

    几天后我发现我的代码确实有效。

    错误是我放置的

    @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
    

    下面

    if __name__ == '__main__':
        server_port = os.environ.get('PORT', '8080')
        app.run(debug=False, port=server_port, host='0.0.0.0')
    

    python语法逐行遍历代码,所以放在app.run()下面的所有东西都不会被执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多