Connexion如何设置响应Content-Type?能否在接口函数中配置?
Great question! Yes, you absolutely can set the Content-Type header directly in your post_order function — and it’s a straightforward fix that will override the default behavior you’re running into.
Why Your Current Setup Works the Way It Does
When your OpenAPI spec lists multiple content types for a response (like both application/json and text/plain), Connexion defaults to using the first one it encounters (in your case, application/json). That’s why you keep seeing that header even though text/plain is also defined. When you removed application/json from the spec, Connexion had no other option but to use text/plain — which is why that scenario worked.
Fix: Return a Tuple with Custom Headers
The simplest way to force a specific Content-Type is to return a tuple from your endpoint function, containing three elements:
- The response body
- The HTTP status code
- A dictionary of custom headers
Here’s how to modify your post_order function to do this:
def post_order(platform, open_req=None): # noqa: E501 """order """ # Return (response body, status code, headers) return 'do some magic!', 200, {'Content-Type': 'text/plain; charset=utf-8'}
This will override any default Content-Type from your OpenAPI spec — even if you leave both application/json and text/plain listed in the YML. The header defined in your function takes precedence.
Alternative: Use Connexion’s Response Object
If you need more control over your response (like setting additional headers or cookies), you can use Connexion’s built-in Response object instead:
from connexion import Response def post_order(platform, open_req=None): # noqa: E501 """order """ response = Response(response='do some magic!', status_code=200) response.headers['Content-Type'] = 'text/plain; charset=utf-8' # Add any other headers you need here # response.headers['X-Custom-Header'] = 'value' return response
Both methods work reliably, but the tuple approach is ideal for simple cases like yours.
内容的提问来源于stack exchange,提问作者Song

