Python 接收http
时间: 2023-07-02 08:18:18 浏览: 48
使用 Python 接收 http 请求可以使用 Python 内置的 http.server 模块。
1. 首先需要导入 http.server 模块:
```python
import http.server
import socketserver
```
2. 然后定义一个处理 http 请求的处理器类,并继承自 http.server.BaseHTTPRequestHandler,重写 do_GET 方法来处理 GET 请求:
```python
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<html><head><title>Python HTTP Server</title></head>")
self.wfile.write(b"<body><p>This is a test.</p>")
self.wfile.write(b"</body></html>")
```
3. 接着创建一个 http 服务器,并将处理器类传递给服务器:
```python
PORT = 8000
Handler = MyHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
```
以上代码将会监听本机的 8000 端口,并在收到请求时调用 MyHandler 类的 do_GET 方法来处理请求,并返回一个简单的 HTML 页面作为响应。
注意:在实际生产环境中,需要为服务器添加一些安全措施,例如验证请求、限制访问等。