使用Flask-Python创建数据流
我正在开发一个服务器,它使用使用Flask-Python创建数据流,python,rest,http,flask,stream,Python,Rest,Http,Flask,Stream,我正在开发一个服务器,它使用Flask从服务器获取日志文件。 下面是获取日志的方法的一个片段: @app.route('/logs', methods=['POST']) def logs(): if request.method == 'POST': if request.headers['Content-Type'] == 'application/octet-stream': return not_implemented() i
Flask
从服务器获取日志文件。
下面是获取日志的方法的一个片段:
@app.route('/logs', methods=['POST'])
def logs():
if request.method == 'POST':
if request.headers['Content-Type'] == 'application/octet-stream':
return not_implemented()
if request.headers['Content-Type'] == 'application/gzip':
# @TODO: Implement me: I must return a gzip file
return not_implemented()
我想要的是创建一个流,所以当我使用paramfilename=foo.txt
向/logs
发出POST
请求时,我想要返回一个流,这样我就可以在客户端读取该文件。到目前为止,我尝试编写以下方法:
def get_stream(filename):
"""Return the file as a stream of binaries
:return file: A file pointer for the binary file
"""
chunk_size = 4096
try:
if os.path.exists(filename):
with open(filename, "bw") as f:
while True:
chunk = f.read(chunk_size)
#@TODO: Add the remaining of the implementation
except Exception, ex:
log.error(ex)
return None
我不明白如何使用yield
向get\u stream()
方法返回迭代器。我知道我必须归还一些东西,比如:
return Response(get_stream("foo.txt"), mimetype="application/octet-stream")
有人能帮我吗