美文网首页
HTTP临时文件上传服务 - Python3

HTTP临时文件上传服务 - Python3

作者: slords | 来源:发表于2018-10-09 15:24 被阅读0次

    server:

    import os
    import sys
    from http.server import BaseHTTPRequestHandler, HTTPServer
    
    upload_path = '/home/upload'
    host = '' # server host
    port = 2121 # port should be integer
    
    class UploadHandler(BaseHTTPRequestHandler):
    
        def do_POST(self):
            file_name = self.path.split('/')[-1]
            print(file_name)
            data = self.rfile.read(int(self.headers['content-length']))
            file_path = os.path.join(upload_path, file_name)
            with open(file_path, 'wb') as f:
                f.write(data)
            self.send_response(200, '--end--')
    
    
    if __name__ == '__main__':
        server_address = (host, port)
        httpd = HTTPServer(server_address, UploadHandler)
        server_host, server_port = httpd.socket.getsockname()[:2]
        print("Serving HTTP on", server_host, "port", server_port, "...")
        httpd.serve_forever()
    

    client:

    import os
    
    import requests
    
    file_name = ''
    host = ''
    port = 2121
    with open(file_name, 'rb') as f:
        data = f.read()
        
    print(
        requests.post(
            'http://{host}:{port}/{file_name}'.format(
                host=host,
                port=port, 
                file_name=file_name
            ),
            data=data).text
    )
    

    相关文章

      网友评论

          本文标题:HTTP临时文件上传服务 - Python3

          本文链接:https://www.haomeiwen.com/subject/pvmygftx.html