Python3 网络编程3:HTTP 网络编程
                           
天天向上
发布: 2025-03-16 12:12:36

原创
295 人浏览过

Python 提供多种方式进行 HTTP 网络编程,包括:

  • requests(用于客户端 HTTP 访问)
  • http.server(用于创建简单 HTTP 服务器)
  • aiohttp(异步 HTTP 客户端 & 服务器)
  • WebSocket(基于 websockets 库)

3.1 requests 客户端

requests 是 Python 最流行的 HTTP 客户端库,支持 GET、POST、PUT、DELETE 等操作。

3.1.1 发送 HTTP GET 请求

import requests

response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(response.status_code)  # HTTP 状态码
print(response.json())       # JSON 响应数据

3.1.2 发送 HTTP POST 请求

import requests

data = {"title": "New Task", "completed": False}
response = requests.post("https://jsonplaceholder.typicode.com/todos", json=data)

print(response.status_code)
print(response.json())

3.2 使用 http.server 创建 HTTP 服务器

Python 自带 http.server 模块,可快速创建 HTTP 服务器。

3.2.1 创建 HTTP 服务器

from http.server import SimpleHTTPRequestHandler, HTTPServer

class MyHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write(b"Hello, HTTP Server!")

server = HTTPServer(("0.0.0.0", 8080), MyHandler)
print("HTTP 服务器运行在端口 8080...")
server.serve_forever()

3.3 aiohttp 异步 HTTP

aiohttp 是 Python 的异步 HTTP 框架,适用于高并发应用。

3.3.1 aiohttp 客户端

import aiohttp
import asyncio

async def fetch():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://jsonplaceholder.typicode.com/todos/1") as resp:
            print(await resp.json())

asyncio.run(fetch())

3.3.2 aiohttp 服务器

from aiohttp import web

async def handle(request):
    return web.Response(text="Hello, aiohttp Server!")

app = web.Application()
app.router.add_get("/", handle)

web.run_app(app, port=8080)

3.4 WebSocket

WebSocket 是一种双向通信协议,适用于实时应用(如聊天室、游戏、股票推送)。

3.4.1 WebSocket 服务器

使用 websockets 创建 WebSocket 服务器:

import asyncio
import websockets

async def websocket_handler(websocket, path):
    async for message in websocket:
        print(f"收到消息: {message}")
        await websocket.send(f"服务器收到: {message}")

server = websockets.serve(websocket_handler, "0.0.0.0", 8765)

asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()

3.4.2 WebSocket 客户端

import asyncio
import websockets

async def websocket_client():
    async with websockets.connect("ws://127.0.0.1:8765") as websocket:
        await websocket.send("Hello WebSocket!")
        response = await websocket.recv()
        print(f"服务器响应: {response}")

asyncio.run(websocket_client())

下篇文章我们将深入介绍 paramiko 进行 SSH 远程操作、ftplib 进行 FTP 文件传输!

发表回复 0

Your email address will not be published. Required fields are marked *