在应用程序上下文之外工作。 (Python:烧瓶错误!)

Working outside of application context. (Python: Flask error!)

我正在尝试为新项目构建框架代码设置。 在这种情况下,我需要使用从“flask”导入的 jsonify() 来生成 str -> json。 然而,当我尝试这样做时,我得到一个 RunTimeError: "Working outside of application context".

当我 google 时,我看到很多人实际使用 Flask 创建应用程序实例,但我不需要应用程序实例。我见过有人在不进行应用程序初始化的情况下使它工作 (app = Flask(name)).

任何人都可以解释我做错了什么?

这是我的控制器:

# Standard library imports
import requests
import json
import logging
# Third party imports
from flask import Flask, request, jsonify
# Internal codebase
from testing import TestObjects as testObj
from core import RequestHandler as rh
from intent import Heartbeat as hb
from intent import CenterCapacity as cc

class Controller():

    def __init__(self):
        # Key is the naming for action internally, value is the actual syntax for the action, mathcing the DialogFlow configuration.
        # If any actions change in DialogFlow, they should be corrected in the dictionary aswell.
        self.actionValues = {
            'getCenterCapacity': 'get.center.capacity', 'heartbeat': 'heartbeat'}

    def main(self, request):
        self.action = rh.getActionFromRequest(request)
        print(self.action)
        if self.action == self.actionValues.get('getCenterCapacity'):
            print(cc.getCenterCapacity())
        elif self.action == self.actionValues.get('heartbeat'):
            print(hb.emptyHeartbeat())


if __name__ == '__main__':
    c = Controller()
    c.main(testObj.getCapacityObj())
    c.main(testObj.getHeartbeatObj())

这是导致问题的我的意图“心跳”。

# Third party imports
from flask import jsonify


def emptyHeartbeat():
    print("You entered the heartbeat method!")
    msg = {
        "fulfillmentMessages": [
            {
                "text": {
                    "text": [""]
                }
            }
        ]
    }
    return jsonify(msg)

尝试用 json.dumps https://docs.python.org/3/library/json.html

替换 jsonify 函数