Skip to main content
 首页 » 编程设计

python之从 Google Cloud Endpoints 中的请求路径获取参数

2025年05月04日7emanlee

我正在 App Engine 上用 Python 试验 Cloud Endpoint API,但我在获取简单的请求参数时遇到了一些困难。

我更熟悉 Java 的 Cloud Endpoints,所以我可能(很可能)遗漏了一些明显的东西。在这个例子中,我试图做的就是返回带有 id 的 ServiceInfo 对象。在 url 路径中指定,/services/<id>

我有一个简单的响应消息类:

class ServiceInfo(messages.Message): 
    crs = messages.StringField(1) 
    services = messages.StringField(2) 

和 API 类:

@endpoints.api(name='myApi', version='v1', description='My API', audiences=[endpoints.API_EXPLORER_CLIENT_ID]) 
class MyApi(remote.Service): 
 
    #No request body, but need to capture the id from the URL 
    ID_RESOURCE = endpoints.ResourceContainer( 
        message_types.VoidMessage, 
        id=messages.StringField(1, variant=messages.Variant.STRING, required=True)) 
 
    @endpoints.method(ID_RESOURCE, ServiceInfo, path='services/{id}', http_method='GET', name='station.getServices') 
    def get_services(self, request): 
        print request.id 
        ... 
        return ServiceInfo(crs=request.id, services=...) 

现在,如果我通过 API 资源管理器发出请求并输入 ABC 作为 id字段,我看到这个请求:

GET /_ah/api/myApi/v1/services/ABC

但是回复说

"Error parsing ProtoRPC request (Unable to parse request content: Message CombinedContainer is missing required field id)"

当我打印 request.id 时, 我得到 None .

我要做的就是获取 id从路径上看——我是否遗漏了一些非常明显的东西?

谢谢!

请您参考如下方法:

几天后重新访问后,我重新启动了本地开发服务器(使用 gcloud preview app run ...),它现在似乎正在使用 id 在 url 路径中(没有代码更改)所以也许开发服务器环境一直在缓存我的文件之一的旧版本?