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   明天有风吹  阅读(3302)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2013-12-28 http 协议 c++代码 获取网页

导航

+V atob('d2h5X251bGw=')

请备注:from博客园

点击右上角即可分享
微信分享提示