воскресенье, 10 июля 2016 г.

Simple upload server on python

Небольшой сервак на питоне для аплоада

Very simple HTTP server in python. Usage:: ./dummy-web-server.py [] """ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import os import time import subprocess python_dir = "" python_script_name = "simpleUploadServer.py" log_file_name = "simpleUploadServer.log" class SimpleHandler(BaseHTTPRequestHandler): upload_dir = "upload" def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write("GET") def do_HEAD(self): self._set_headers() def do_POST(self): self.log_message('%s', "POST request") self.log_message('%s', self.headers) if self.path.startswith('/upload'): if 'content-length' not in self.headers: self._set_headers() self.log_message('%s', 'warning: no "content-length" header') self.send_response(406) return length = self.headers['content-length'] data = self.rfile.read(int(length)) url_path_name = self.path.split('/upload',1)[1] url_path_array = url_path_name.split('/') file_path = os.path.join(os.getcwd(), self.upload_dir) for f in url_path_array: file_path = os.path.join(file_path, f) millis = int(round(time.time() * 1000)) self.log_message('%s', 'POST upload ' + url_path_name + ', time: ' + str(millis) + 'ms') self.log_message('%s', 'upload file "' + file_path + '"') if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) time1 = time.time() with open(file_path, 'wb+') as fh: fh.write(data) time2 = time.time() self.log_message('%s', 'file uploaded: "' + str((time2 - time1) * 1000) + 'ms') self.send_response(200) else: # Doesn't do anything with posted data self._set_headers() self.wfile.write("POST") def log_date_time_string(self): """Return the current time formatted for logging.""" from datetime import datetime return str(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]) def run(server_class=HTTPServer, handler_class=SimpleHandler, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print('Starting httpd...') httpd.serve_forever() def start(): stop() from win32process import DETACHED_PROCESS process = subprocess.Popen([python_dir + 'python', python_script_name, 'daemon'], shell=True, creationflags=DETACHED_PROCESS) def stop(): title = python_dir + 'python ' + python_script_name + ' daemon' os.system('taskkill /f /t /fi "WINDOWTITLE eq ' + title) def run_system(): os.system(python_dir + 'python ' + python_script_name + ' > ' + log_file_name + ' 2>&1') if __name__ == "__main__": from sys import argv if len(argv) == 2: if argv[1] == "daemon": run_system() else: run()

Комментариев нет:

Отправить комментарий