Python'_AppCtxGlobals':Flask中的属性错误

问题描述 投票:2回答:1

我已经实现了用于计算API时间的代码。

@api.app.before_request
def before_request():
    g.request_start_time = time.time()

@api.app.after_request
def after_request():
    elapsed = time.time() - g.request_start_time ------> Error here.

我在1-2%的api调用中出错。

错误:

'_AppCtxGlobals' object has no attribute 'request_start_time'

我无法调试。仅当:

  1. api无法通过before_request函数。
  2. 全局上下文在代码之间重置。

首先似乎没有发生,因为每个api请求都应通过before_request函数。我找不到第二种情况何时可以发生。在两次调用之间重置全局上下文时会发生什么情况。

我在这里想念什么吗?

编辑:

我一直在观察发生此错误的情况,并发现所有呼叫都具有400 BAD REQUEST的相似性。但是我仍然无法找到这个的根本原因。

python flask http-status-code-400 bad-request
1个回答
0
投票

我有一个类似的问题,这是由于您调用了变量g,所以flask将其与也称为g的全局应用程序上下文混淆了。

[在这里看看:https://flask.palletsprojects.com/en/1.1.x/api/#flask.ctx._AppCtxGlobals

Creating an app context automatically creates this object, which is made available as the g proxy.

因此,请在g.request_start_time = time.time()中重命名您可能从其他地方继承的g变量。

如果您引用的是烧瓶上下文,并且错误与404请求相关,则可能是当您调用after_request()时找不到任何属性g.request_start_time,可能是因为如果请求失败,则不会创建该属性。

© www.soinside.com 2019 - 2024. All rights reserved.