Get the current user from BlobstoreUploadHandler

2020-04-21 07:48发布

问题:

I want to get the current user from BlobstoreUploadHandler. I'm using endpoints for my web application, but (outside of Endpoints) I built /uploadUrl to upload files to the Blobstore.

The image uploads correctly. So, I need to link the image uploaded to the user, but users.get_current_user() returns None. On the frontend side the user is logged using OAuth2. Any idea for this issue?

If I use endpoints.get_current_user() raise an error:

No valid endpoints user in environment

This is my code:

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_file_infos()
        file_info = upload_files[0]

        gcs_filename = file_info.gs_object_name
        file_key = blobstore.create_gs_key(gcs_filename)

        File(file=gcs_filename, owner=users.get_current_user() ).put()

回答1:

Each App requires its own login, and every class needs to have users imported and declared if you want to use User class in the code.

from google.appengine.api import users import webapp2

class MyHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = ('Welcome, %s! (<a href="%s">sign out</a>)' %
                        (user.nickname(), users.create_logout_url('/')))
        else:
            greeting = ('<a href="%s">Sign in or register</a>.' %
                        users.create_login_url('/'))

        self.response.out.write('<html><body>%s</body></html>' % greeting)

For more details please see this article - https://cloud.google.com/appengine/docs/python/users/



回答2:

in your app.yaml you have to add login: required or login: admin.

Example:

handlers:
- url: /upload_handler.*
  script: my_app.media_handlers.application
  login: required

After this, users.get_current_user() should work.

https://cloud.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Requiring_login_or_administrator_status

Other thread about this:Google App Engine get_current_user always return None, even if i'm logged