如何从Python应用程序使用OAuth访问Google App Engine端点API?

2 投票
1 回答
536 浏览
提问于 2025-04-18 09:47

我该如何访问Google App Engine的端点API,使用Python(而不是网页、安卓或iOS)呢?

我看过这个教程,但里面的解释不够清楚,让我很难理解。

我发现,在服务器端我可以用这样的代码来识别用户:

@endpoints.method(message_types.VoidMessage, Greeting,
                  path='hellogreeting/authed', http_method='POST',
                  name='greetings.authed')
def greeting_authed(self, request):
    current_user = endpoints.get_current_user()
    email = (current_user.email() if current_user is not None
             else 'Anonymous')
    return Greeting(message='hello %s' % (email,))

API示例的完整代码

那么,我该如何从Python客户端连接到这个API,并用身份验证调用'hellogreeting/authed',确保current_user != None呢?

能不能分享一些代码来演示一下该怎么做?

app_id = 'xxx'
user = 'xxx'
password = 'xxx'
callAPI(app_id, user, password, 'hellogreeting/authed')

1 个回答

1

你需要配置你的App Engine实例,以便能够提供你的API服务。我建议你创建一个专门用于API的模块,具体可以参考这些文档:https://developers.google.com/appengine/docs/python/endpoints/api_server

一旦服务器端的设置都正确了,你就可以通过类似这样的链接来调用你的API:http://your-module.your-app.appspot.com/_ah/spi/hellogreeting/authed

如果你在使用开发服务器,访问模块的方式会稍微不同,但一旦你知道App Engine开发服务器为你的API模块分配了哪个端口号,你就可以在本地通过以下链接访问它:http://localost:<api_module_port_#>/_ah/spi/hellogreeting/authed

希望这些信息对你有帮助。

撰写回答