我有以下非常简单的应用程序:
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
当我运行它时,我得到以下异常:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/me/dev/project/src/main.py", line 22, in do_in_request
app(*args, **kwargs)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 249, in error_router
if self._has_fr_route():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 230, in _has_fr_route
if self._should_use_fr_error_handler():
File "/Users/me/dev/project/src/lib/flask_restful/__init__.py", line 211, in _should_use_fr_error_handler
adapter = self.app.create_url_adapter(request)
File "/Users/me/dev/project/src/lib/flask/app.py", line 1601, in create_url_adapter
return self.url_map.bind_to_environ(request.environ,
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/me/dev/project/src/lib/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/me/dev/project/src/lib/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
所以我试着把我的整个应用程序放到我认为的请求上下文中。在上面的代码中,Flask对象和Api对象都被实例化一次,并且可以由服务器多次调用。从回溯中看,实例化应该在请求上下文中发生,所以我把它包装成这样:
def do_in_request(*args, **kwargs):
from lib.flask import Flask
from lib.flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class TestResource(Resource):
def get(self):
return {"a":"b","c":"d"}
api.add_resource(TestResource, "/")
app(*args, **kwargs)
app = do_in_request
仍然会引发同样的错误。发生了什么,“请求上下文”是什么意思,我该如何解决?
答案 0 :(得分:1)
我从头开始使用App Engine Flask Skeleton并在flask-restful
中添加了requirements.txt
作为依赖项,然后只添加了或多或少的上面代码,并且它没有问题。我将存储库添加到my github here,如果您想使用它 - 您可以在this commit中看到我对骨架所做的更改。
我不确定为什么你的例子不起作用,但有一点我注意到可能导致问题的是你正在做from lib.flask ...
。您的第三方软件包似乎存在于lib
中,并且您无法提升并且#34; lib
sys.path
。骨架包含vendoring library,以确保正确处理。这可能是问题的潜在根源。
无论哪种方式,我希望分叉的骨架可以帮助你起床和跑步。