【问题标题】:Working outside of application context. (Python: Flask error!)在应用程序上下文之外工作。 (Python:烧瓶错误!)
【发布时间】:2020-06-24 11:23:31
【问题描述】:

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

当我谷歌时,我看到很多人实际上用 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)

【问题讨论】:

    标签: python json python-3.x flask runtime-error


    【解决方案1】:

    尝试将 jsonify 函数替换为 json.dumps https://docs.python.org/3/library/json.html

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多