Google Cloud Endpoints Python能否返回纯文本字符串而非JSON?
Got it, let's tweak your endpoint to return plain text instead of the structured JSON message. Here's a straightforward way to make this change:
First, you’ll need to bypass the default JSON serialization behavior of Cloud Endpoints (which kicks in when you use a custom message class like Site_response_new). We’ll use endpoints.Response to directly control the response content and type, along with message_types.VoidMessage to signal we aren’t returning a structured protobuf.
Step 1: Update the endpoint's return type
Replace Site_response_new in your @endpoints.method decorator with message_types.VoidMessage (make sure you’ve imported this from protorpc first). This tells Cloud Endpoints we won’t be sending a structured message back.
Step 2: Return a plain text response
Inside your method, create an endpoints.Response instance, set its body to your desired plain text string, and specify content_type='text/plain' to ensure the client gets the correct content header.
Here’s the modified code:
# Ensure these imports are included from protorpc import message_types import endpoints @endpoints.method( Site_resource, message_types.VoidMessage, # Replaced Site_response_new here path='test', http_method='POST', name='testsystem' ) def testsystem(self, request): # Replace with your actual plain text content plain_text_result = "Your custom plain text string goes here" return endpoints.Response(body=plain_text_result, content_type='text/plain')
Quick breakdown of why this works:
message_types.VoidMessagedisables the automatic JSON serialization that Cloud Endpoints applies to custom message classes.endpoints.Responselets us explicitly define the raw response body and content type, so the server sends back plain text directly instead of wrapping it in a JSON object.
Special characters in your plain text will be handled automatically—no need for manual encoding.
内容的提问来源于stack exchange,提问作者Tal Yahav

