• python requests上传文件 tornado 接收文件(示例代码)


    简介  这篇文章主要介绍了python requests上传文件 tornado 接收文件(示例代码)以及相关的经验技巧,文章约14653字,浏览量348,点赞数2,值得参考!

    requests 上传文件

    import requests
    
    def images():
        url = ‘http://127.0.0.1:8889/upload/image‘ 
        files = {‘file‘: open(‘desktop.png‘, ‘rb‘)}
        multiple_files = [
    (‘file‘, (‘11.png‘, open(‘11.png‘, ‘rb‘), ‘image/png‘)),
    (‘file‘, (‘desktop.png‘, open(‘desktop.png‘, ‘rb‘), ‘image/png‘))
    ] headers = {‘Api-Key‘: ‘InhpeWFuZzA4MDdJBtx4AWlPpI_Oxx1Ki8‘, ‘User-Agent‘: ‘Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36‘
    } r = requests.post(url, files=multiple_files, headers=headers) # 上传图片 r = requests.post(url, files=files, headers=headers) # 上传文件 print(r.text)


    tornado 接收文件

    #!/usr/bin/env python
    # Copyright 2009 Facebook
    #
    
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    import logging
    import sys
    import setting

    class UploadImageHandler(BaseHandler):
    def set_default_headers(self):
            print "setting headers!!!"
            self.set_header("Access-Control-Allow-Origin", "*")
            self.set_header("Access-Control-Allow-Headers", "x-requested-with")
            self.set_header(‘Access-Control-Allow-Methods‘, ‘POST, GET, OPTIONS‘)
    
        def options(self):
            pass
    
        def get(self):
            self.write(‘please upload a image url‘)
    
        def post(self):
            result = {}
            result[‘flag‘] = 0
            result[‘data‘] = ‘‘
            result[‘msg‘] = ‘‘
            try:
                is_admin = self.get_body_argument(‘is_admin‘, None)
                meta = self.request.files[‘file‘][0]
                suffix = meta[‘filename‘].split(‘.‘)[-1]
                fullname, arr, filename = self.get_full_file_name(‘image‘, suffix)
                while os.path.exists(fullname):
                    logging.info(‘已经存在文件:‘ + fullname)
                    fullname, arr, filename = self.get_full_file_name(‘image‘, suffix)
                f = open(fullname, ‘wb‘)
                f.write(meta[‘body‘])
                f.close()
                result[‘data‘] = setting.openHost+‘/‘+arr[0]+‘/‘+arr[1]+‘/‘+arr[2]+‘/‘+arr[3]+‘/‘ + filename
                result[‘flag‘] = 1
            except Exception, e:
                logging.info(‘Error: upload image failing,%s‘ % str(e))
                result[‘flag‘] = 0
                result[‘msg‘] = ‘fail in upload image‘
                self.write(simplejson.dumps(result))
                return
            self.set_header("Access-Control-Allow-Origin", "*")
            self.write(simplejson.dumps(result))


    class Application(tornado.web.Application): def __init__(self): self.session = memcache.Client([setting.memcache_host]) handlers = [ (r"/upload/image", UploadImageHandler) tornado.web.url(r".*", tornado.web.StaticFileHandler, dict(path=setting.imgDir), name=‘static_path‘) ] tornado.web.Application.__init__(self, handlers) if __name__ == "__main__": tornado.options.parse_command_line() application = Application() http_server = tornado.httpserver.HTTPServer(application, xheaders=True) port = 8889 if len(sys.argv) > 1: port = int(sys.argv[1]) http_server.listen(port) loop = tornado.ioloop.IOLoop.instance() logging.info(‘File Server running on http://127.0.0.1:%d‘ % port) loop.start()

     settin.py

    #!/usr/bin/env python
    # coding=utf8
    # file=setting.py
    
    imgDir = "/imgData/"  # 图片文件保存地址
    openHost = "http://img.520czj.com"  # 图片服务器的访问基URL
    serverName = ‘server1‘  # 保存在该图片服务器中文件的命名前缀,用于反向代理时快速定位图片所在服务器,如果禁用一台服务器,该字段无实际意义
    memcache_host = ‘127.0.0.1:11211‘
    domanName = ‘http://admin.520czj.com‘

    以上就是本文的全部内容,希望对大家的学习有所帮助,本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

     原文地址:http://www.cnblogs.com/aaron-agu/p/7509734.html

  • 相关阅读:
    图片上传记得要讲中文的重命名
    hihoCoder #1471 拥堵的城市
    搜狗拼音输入法的快捷键和其他应用快捷键冲突
    Codeforces #765D
    训练记录
    hihoCoder 1367 等式填空
    hihoCoder #1073 光棍节
    计算几何 I. 极角
    hihoCoder #1065 全图传送
    树的点分治专题
  • 原文地址:https://www.cnblogs.com/ykcbwdt/p/16381407.html
Copyright © 2020-2023  润新知