python的http服务的使用

在Python中,你可以使用内置的 http.server 模块来创建一个简单的HTTP服务器。这个模块提供了一个轻量级的HTTP服务器,适用于开发和调试。以下是一个简单的例子:

Python 3.x

from http.server import SimpleHTTPRequestHandler

from socketserver import TCPServer

设置服务器地址和端口

host = "localhost"

port = 8000

创建一个简单的HTTP请求处理器

handler = SimpleHTTPRequestHandler

启动HTTP服务器

with TCPServer((host, port), handler) as httpd:

print(f"Serving on http://{host}:{port}")

httpd.serve_forever()

将这段代码保存为 server.py,然后在命令行中运行它。你将在 http://localhost:8000 上启动一个简单的HTTP服务器,可以通过浏览器访问。

如果你需要提供自定义的处理逻辑,你可以继承 SimpleHTTPRequestHandler 并重写它的方法。以下是一个简单的示例,演示如何在请求中返回自定义响应:

from http.server import SimpleHTTPRequestHandler

from socketserver import TCPServer

class CustomHandler(SimpleHTTPRequestHandler):

def do_GET(self):

self.send_response(200)

self.send_header("Content-type", "text/html")

self.end_headers()

self.wfile.write(b"Hello, this is a custom response!")

设置服务器地址和端口

host = "localhost"

port = 8000

创建自定义HTTP请求处理器

handler = CustomHandler

启动HTTP服务器

with TCPServer((host, port), handler) as httpd:

print(f"Serving on http://{host}:{port}")

httpd.serve_forever()

这是一个简单的例子,你可以根据你的需求扩展和定制这个HTTP服务器。如果你需要更强大的功能,可能需要考虑使用第三方库,比如 Flask 或 Django。这些库提供了更复杂的功能,使得构建Web应用更容易。

相关推荐
孟健11 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞13 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽15 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程20 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪20 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook20 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
不可能的是21 小时前
前端 SSE 流式请求三种实现方案全解析
前端·http
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img