Python 常用代码

2018-07-22 language python example

HTTP 服务器

包括了 HTTP 和 HTTPS 两种,因为监听的是 80/443 端口,运行的时候需要使用 root 用户。

import ssl
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler

# openssl req -newkey rsa:2048 -nodes -keyout cert/foobar.key -x509 -days 365 -out cert/foobar.crt
class DummyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes('<html><head><title>Dummy</title></head></html>'.encode('utf-8')))

def handle_http(host, port):
    print(f'Serving(http) on {host}:{port} ...')
    HTTPServer((host, port), DummyHandler).serve_forever()

def handle_https(host, port):
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(certfile='cert/foobar.crt', keyfile="cert/foobar.key")

    httpd = HTTPServer((host, port), DummyHandler)
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

    print(f'Serving(https) on {port} (HTTPS) ...')
    httpd.serve_forever()

if __name__ == '__main__':
    addr = '127.0.0.1'
    http_thread = threading.Thread(target=handle_http, args=(addr, 80))
    http_thread.start()

    https_thread = threading.Thread(target=handle_https, args=(addr, 443))
    https_thread.start()