简体   繁体   English

使用Bottle框架在Python中通过HTTP发送文件

[英]Sending a file via http in Python with bottle framework

How can I send a file as answer to an HTTP request in Python using the bottle framework? 如何使用Bottle框架在Python中发送文件作为HTTP请求的答案?

For upload this code works for me: 对于上传,此代码对我有用:

@route('/upload', method='POST')
def do_upload():
    category   = request.forms.get('category')
    upload     = request.files.get('upload')
    name, ext = os.path.splitext(upload.raw_filename)
    if ext not in ('.png','.jpg','.jpeg'):
        return 'File extension not allowed.'

    save_path = category
    upload.raw_filename = "hoho" + ext
    upload.save(save_path) # appends upload.filename automatically
    return 'OK'

Just call Bottle's static_file function and return its result: 只需调用Bottle的static_file函数并返回其结果即可:

@route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root='/path/to/static/files')

That example, when called with url /static/myfile.txt , will return the contents file /path/to/static/files/myfile.txt . 该示例在使用url /static/myfile.txt调用时,将返回内容文件/path/to/static/files/myfile.txt

Other SO questions (like this one ) contain additional examples. 其他SO问题(例如this )包含其他示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM