问题
In my Flask-based Google App Engine server, I am trying to return a response with a 'content-length' header which will contain the final size of a blob being served to the client. This blob is a large media file, so this header is going to be used to set the maximum value of a progress bar on the UI frontend. The blob lives in Cloud Storage, but is using the blobstore API from the App Engine packages to retrieve the blob. Below returns with a 200
status code:
response.headers['Content-length'] = blobstore.BlobInfo(version.blob_key).size
return response
It is being received using the Requests Python package, and is streaming the data being received (This should be fine, since all the headers are received in the Response object first before data streaming begins). My code looks something like below:
with requests.get(url='/api/download', stream=True) as r:
print(r.headers)
However, there is no Content-length
header being set. Instead, I get something like this from the print()
above:
{'Cache-Control': 'no-cache',
'Content-Type': 'text/plain; charset=utf-8',
'X-Cloud-Trace-Context': '1bca54f9cdae7394de6cb2f1e824ba6f',
'Transfer-Encoding': 'chunked',
'Date': 'Thu, 26 Apr 2018 11:36:17 GMT',
'Server': 'Google Frontend'}
I noticed from this post that App Engine strips the content-length header and replaces it with the correct size, but I'm not getting a content-length header to begin with. What am I doing incorrectly? Am I serving the blob to the client wrong? Is the content-length simply unavailable and cannot be set? If so, how can I retrieve the size of the file so I can compute the size of my UI progress bar?
回答1:
The Content-Length
header is included in the list of headers that can't be modified.
As you and the documentation pointed out, App Engine calculates the Content-Length header from the request data and adds it to the request prior to sending.
You can always set a personalized header, Flask allows it, and GAE will let you use it.
For example, for your response:
response.headers['CL-blob'] = blobstore.BlobInfo(version.blob_key).size
来源:https://stackoverflow.com/questions/50042455/content-length-header-not-being-set-on-flask-app-engine-response-for-served-blob