Google云端点Python快速启动回显示例issu

2024-09-28 05:18:21 发布

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

在python标准环境快速启动中,端点方法test_api_key返回一个503服务不可用。使用dev运行时,API资源管理器中发生错误_应用程序.py以及部署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])

我不太了解。获取未识别的\u field_info('key'),因此我不确定问题是什么?谢谢。在


Tags: keyfromtestimportapimessageremotecontent
2条回答

造成503错误的原因有三个。在

首先,我需要使方法或整个Api require an Api Key。在本例中,我将其应用于整个Api:

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

其次,在云控制台中生成Api密钥后,我需要在部署它之前put the Key into the openapi.json file。在

最后,我仍然得到一个验证错误:

^{pr2}$

get_无法识别的_field_info()函数returns a tuple of (value, variant)。响应不需要元组,因此我将方法更新为只显示值:

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

首先,我建议阅读Google Protocol RPC Library Overview,因为它是Google云端点广泛使用的。在

在@端点.方法允许您在API中配置特定方法。配置选项在Google云平台文档中有文档记录,在创建API时使用Cloud Endpoints Frameworks for App Engine,在Defining an API method (@endpoints.method)一节中。在

如果您限制对test/getApiKey/test_api_key方法的访问,那么必须使用api_key_required=True选项配置该方法。Restricting API Access with API Keys (Frameworks)进一步讨论了这一点,但是您的方法注释应该是:

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

请注意,您的方法接受一个表示HTTP请求的请求参数(即使用API的客户端):

^{pr2}$

然而,request参数实际上是Google Protocol RPC Message(Proto-RPC)Message对象,因此定义得非常好。如果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.
    """

Message class code on GitHub有很好的文档记录。在

请求正文中不会出现任何参数,因为您已将方法配置为使用HTTP GET调用:

http_method='GET'

…您正确地使用了值message_types.VoidMessage。在

就您的错误而言,503只是一个普通的服务器错误,您能从StackDriver logs提供任何信息吗?它们会指出代码中的确切行和错误。在

相关问题 更多 >

    热门问题