HTTP临时文件上传服务 - Python3

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)