Google Cloud端点Python QuickStart回波样本问题



在python标准环境中,端点方法test_api_key返回503服务。当使用dev_appser.py运行时,并且部署API时,该错误发生在API资源管理器中。它的代码是:

import endpoints
from protorpc import message_types
from protorpc import messages
from protorpc import remote
class TestResponse(messages.Message):
    content = messages.StringField(1)
@endpoints.api(name='practice', version='v1', description='My Practice API')
class PracticeApi(remote.Service):
    @endpoints.method(
        message_types.VoidMessage,
        TestResponse,
        path='test/getApiKey',
        http_method='GET',
        name='test_api_key')
    def test_api_key(self, request):
        return TestResponse(content=request.get_unrecognized_field_info('key'))
api = endpoints.api_server([PracticeApi])

我对.get_unrecognized_field_info('key')没有很好的了解,所以我不确定问题是什么?谢谢。

首先,我建议阅读Google协议RPC库概述,因为它是Google Cloud Endpoints广泛使用它。

@endpoints.method允许您在API中配置特定方法。配置选项在Google Cloud Platform Document中记录在App Engine的API中,在本节中,定义API方法(@endpoints.method)。

如果您限制了对test/getApiKey/test_api_key方法的访问,则必须使用api_key_required=True选项配置该方法。使用API键(框架)限制API访问会进一步讨论,但是您的方法注释应为:

@endpoints.method(
        message_types.VoidMessage,
        TestResponse,
        path='test/getApiKey',
        http_method='GET',
        name='test_api_key',
        api_key_required=True
)

注意您的方法接受代表HTTP请求的请求参数(即客户使用API):

def test_api_key(self, request):

但是,request参数实际上是Google协议RPC消息(Proto RPC)消息对象,因此定义很好。如果protorpc请求参数中存在其他字段,则除了正式定义之外,它们仍然与请求对象一起存储,但必须使用以下方法检索:

def get_unrecognized_field_info(self, key, value_default=None,
                                  variant_default=None):
    """Get the value and variant of an unknown field in this message.
    Args:
      key: The name or number of the field to retrieve.
      value_default: Value to be returned if the key isn't found.
      variant_default: Value to be returned as variant if the key isn't
        found.
    Returns:
      (value, variant), where value and variant are whatever was passed
      to set_unrecognized_field.
    """

GITHUB上的消息类代码有很好的记录。。

没有参数出现在请求的正文中,因为您已经配置了使用http get调用的方法:

http_method='GET'

...您正确地使用了值message_types.VoidMessage

在您的错误方面,503只是一个通用服务器错误,您可以从stackdriver日志中提供任何信息吗?他们将指向您的代码中的确切线和错误。

有三件事造成503错误。

首先,我需要制作方法或整个API需要一个API键。在这种情况下,我只是将其应用于整个API:

@endpoints.api(name='practice', version='v1', api_key_required=True)
class PracticeApi(remote.Service):

其次,在我在云控制台中生成API键后,我需要将键放入OpenApi.json文件之前。

最后,我仍然遇到验证错误:

ValidationError: Expected type <type 'unicode'> for field content, found (u'My Api Key', Variant(STRING, 9)) (type <type 'tuple'>)

get_unrecognized_field_info()函数返回(value,variant)的元组。响应不会期望元组,因此我更新了该方法以显示值:

    def test_api_key(self, request):
        return TestResponse(content=request.get_unrecognized_field_info('key')[0])

最新更新