如何在云端点中使用Flask上下文

2024-10-04 07:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Flask构建了一个带有restapi的web应用程序。我利用Flask的g保存当前用户,并从数据存储中提取我想要的用户数据(该应用程序托管在Google云上)。但是,我希望实现Google云端点,因为它有一些优点,但是如果我调用云端点中的一个url,就会得到错误:

Traceback (most recent call last):
  File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/Users/manuelgodoy/Documents/Google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 95, in LoadObject
    __import__(cumulative_path)
  File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/application/apis.py", line 18, in <module>
    user = g.user
  File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/Users/manuelgodoy/Projects/Eatsy/Eatsy/src/lib/flask/globals.py", line 27, in _lookup_app_object
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

如何使用flask的上下文变量,如glogin_requiredcurrent_user等作为云端点?在

在我的代码中,我将current_user存储在g.user中,并且我有一个端点,在那里我可以得到g.user,这样我就可以得到id

在视图.py:

^{pr2}$

我的云端点文件如下所示:

from views import g

@endpoints.api(name='myapp', version='v1', description='myapp API',
                allowed_client_ids=[WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID])
class MyAppApi(remote.Service):
    @endpoints.method(IdRequestMessage, RecommendationsResponseMessage,
                      path='recommendations', http_method='GET',
                      name='recommendations.recommendations')
    def recommendations(self, request):
        # I would prefer to use this, but I get the
        # "Working outside the app context" error
        # when I uncomment it
        #user = User.get_by_id(g.user.key().id())
        user = User.get_from_message(request)
        response = user.get_recommendations()
        return response

我的Javascript函数如下:

    loadRecommendationsFromServer: function() {
      $.ajax({
        // This is how I *would* call it, if it worked
        //url: this.props.url+"/_ah/api/myapp/v1/recommendations",
        //data: JSON.stringify({'id':2}),
        url: this.props.url+"/recommendations",
        dataType: 'json',
        success: function(data) {
          this.setState({data: data.recommendations});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });

现有的代码是有效的-当我使用g.user时,如何避免不得不在视图处理程序中发出HTTP请求并避免MyAppApi服务中的RuntimeError?在


Tags: inpyurlgetgooglelinethisusers