从 BlobstoreUploadHandler 获取当前用户

Get the current user from BlobstoreUploadHandler(从 BlobstoreUploadHandler 获取当前用户)

本文介绍了从 BlobstoreUploadHandler 获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()

解决方案

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/

这篇关于从 BlobstoreUploadHandler 获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 BlobstoreUploadHandler 获取当前用户

基础教程推荐