python 启动一个 http server

启动一个简单的 web 服务器

python2

python -m SimpleHTTPServer 8080

python3

python3 -m http.server 8080 --bind 127.0.0.1

3.8 以上可以 bind IPv6

python3 -m http.server --bind :: 8080

3.8 以下 bind IPv6

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler


class HTTPServerV6(HTTPServer):
    address_family = socket.AF_INET6

server = HTTPServerV6(('::', 8080), SimpleHTTPRequestHandler)
server.serve_forever()

test

curl http://localhost:8080
curl http://[::]:8080

https

#!/usr/bin/env python3
# coding: utf8

import os
import json
from http.server import SimpleHTTPRequestHandler, HTTPServer

class handler(SimpleHTTPRequestHandler):
    def do_GET(self):
        SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        path = self.path
        print(f'path: {path}')

        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)

        print(f'body: {body}')

        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        message = "Hello, World! Here is a POST response"
        self.wfile.write(bytes(message, "utf8"))


with HTTPServer(('', 8443), handler) as server:
    # ----------- https ------------ #
    MYSERV_FULLCHAIN = '/your/path/to/fullchain.cer'
    MYSERV_PRIVKEY = '/your/path/to/example.com.key'
    import ssl
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ssl_context.load_cert_chain(MYSERV_FULLCHAIN, MYSERV_PRIVKEY)
    server.socket = ssl_context.wrap_socket(server.socket)
    # ----------- https ------------ #

    server.serve_forever()

test

curl -k https://192.168.1.6:4443/

-k, --insecure
(TLS) By default, every SSL connection curl makes is verified to be secure. This option allows curl to proceed and operate even for server connections otherwise considered insecure.
The server connection is verified by making sure the server's certificate contains the right name and verifies successfully using the cert store.
See this online resource for further details: https://curl.haxx.se/docs/sslcerts.html


.

posted on 2016-12-28 12:40  明天有风吹  阅读(3247)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园