在函数签名中指定Flask current_app.response_class类型的正确方法

时间:2019-07-04 00:09:03

标签: python flask types signature

我的问题:

在指定返回中调用jsonify()的函数的返回类型时,Flask应用程序遇到了麻烦。 Flask的jsonify最终将返回current_app.response_class。但是,通过在签名中指定这种返回类型,我会得到一个错误。

错误:

Traceback (most recent call last):
  File "wsgi.py", line 1, in <module>
    from app import app as application
  File "./app.py", line 94, in <module>
    def handle_msg_request() -> current_app.response_class:
  File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 307, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python3.7/site-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

违规代码:

from flask import Flask, render_template, request, jsonify, send_from_directory, current_app

@app.route("/requestmessages", methods=['POST'])
def handle_msg_request() -> current_app.response_class:
    last_id = int(request.form['lastId'])
    data = get_all_chat_dict(min=last_id)
    if len(data) == 0:
        return jsonify(hasNewData=False)
    return jsonify(hasNewData=True, dataRows=data)

相关/类似问题:

我看到了通过在上下文中使用with来解决this question的问题,但是我不太确定如何在这里应用它,因为我只是在尝试指定返回值函数的类型。

当这种类型似乎与应用程序的上下文交织在一起时,如何在签名中指定返回类型?

0 个答案:

没有答案