tornado 后端通过http(第三方路径)传文件

谁说胖子不能爱 提交于 2019-12-05 01:52:59
import asyncioimport binasciiimport siximport osfrom io import BytesIOfrom tornado.httpclient import AsyncHTTPClient, HTTPRequest
def choose_boundary():    """    Our embarrassingly-simple replacement for mimetools.choose_boundary.    """    boundary = binascii.hexlify(os.urandom(16))    if six.PY3:        boundary = boundary.decode('ascii')    return boundarydef encode_multipart_formdata3(data=None, files=None):    """    fields is a sequence of (name, value) elements for regular form fields.    files is a sequence of (name, filename, value) elements for data to be    uploaded as files.    Return (content_type, body) ready for httplib.HTTP instance    """    body = BytesIO()    boundary = choose_boundary()    for key, value in data.items():        body.write(six.b('--%s\r\n' % boundary))        body.write(six.b('Content-Disposition:form-data;name="%s"\r\n' % str(key)))        body.write(six.b('\r\n'))        body.write(six.b('%s\r\n' % value))    for key, value in files.items():        body.write(six.b('--%s\r\n' % boundary))        body.write(six.b('Content-Disposition:form-data;name="file";filename="%s"\r\n' % key))        body.write(six.b('\r\n'))        body.write(value)        body.write(six.b('\r\n'))    body.write(six.b('--%s--\r\n' % boundary))    content_type = 'multipart/form-data;boundary=%s' % boundary    return content_type, body.getvalue()async def file_uploading():   #使用前段传来的文件是,在这里填一个file    print(1111111111111)    data = {"subpath": "", "unformat": "0"}    files = {        "1.mp3": open("1.mp3", "rb").read()  #这个是本地文件    }    # files = {    #     file.filename: file.body         # 这个是前段传来的文件    # }    content_type, body = encode_multipart_formdata3(data=data, files=files)    client = AsyncHTTPClient()    request_url = "http://27.128.181.220:85/php/addmediadata.php"    request = HTTPRequest(        url=request_url,        method="POST",        headers={"Content-Type": content_type, 'content-length': str(len(body))},        body=body    )    resp = await client.fetch(request)    print(str(resp.body.decode(encoding="utf-8")))    return str(resp.body.decode(encoding="utf-8"))if __name__ == "__main__":    loop = asyncio.get_event_loop()    loop.run_until_complete(file_uploading())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!