用Python创建自己的HTTP服务器
方案一
HTTP-Python官方
python -m http.server 80
方案二
HTTP-概念版
import socketIPV4_ADDR = '192.168.124.7'
IPV4_PORT = 8888# TCP 服务端程序必须绑定端口号,否则客户端找不到这个 TCP 服务端程序
class ServerSocket(object):def __init__(self):# 1 创建服务端套接字对象# socket.AF_INET IPV4# socket.SOCK_STREAM TCP# socket.SOCK_DGRAM UDPself.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置端口复用 如果程序执行结束,则让其占用的端口立即释放self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)# 2 绑定端口号self.tcp_server_socket.bind((IPV4_ADDR, IPV4_PORT))# 3 设置监听# listen 后的套接字属于被动套接字,只负责接收新的客户端的连接请求不能收发消息# 参数为允许最大的连接数self.tcp_server_socket.listen(1)def start(self):while True:# 4 等待接收客户端的连接请求# 当 TCP 客户端程序和 TCP 服务端程序连接成功后,TCP 服务端程序会产生一个新的套接字,收发客户端消息使用该套接字client_socket, client_connect = self.tcp_server_socket.accept()# 5 接收数据recv_data = client_socket.recv(1024).decode(encoding='utf-8')# 当客户端的套接字调用 close 后,服务器端的 recv 会解阻塞,返回的数据长度为0if len(recv_data) <= 0:client_socket.close()# 截取到用户的访问请求参数request = recv_data.split(' ', maxsplit=2)[1]# 6 发送数据send_data = self.init_web_data(request)client_socket.send(send_data)client_socket.close()def __del__(self):# 5 关闭套接字self.tcp_server_socket.close()@staticmethoddef init_web_data(request):if request == '/':request = '/index.html'file_path = './lanyue' + request# 解决 favicon.ico 或资源找不到的问题try:with open(file_path, "rb") as file:data = file.read()except:# HTML 标准样式为: 响应行 + 响应头 + 响应体 + 响应数据# 响应行response_line = "HTTP/1.1 404 NOT FOUND\r\n"# 响应体response_body = '资源不存在'.encode('utf-8')else:# HTML 标准样式为: 响应行 + 响应头 + 响应体 + 响应数据# 响应行response_line = "HTTP/1.1 200 OK\r\n"# 响应体response_body = data# 响应头response_header = "Server:PythonWeb1.0\r\n"# 响应数据response_data = (response_line + response_header + "\r\n").encode('utf-8') + response_bodyreturn response_dataif __name__ == '__main__':server_socket = ServerSocket()server_socket.start()
方案三
HTTP-FastApi版
安装依赖包
pip install fastapi
pip install uvicorn或conda install fastapi
conda install uvicorn或pipenv install fastapi
pipenv install uvicorn
代码
from fastapi import FastAPI
from fastapi import Response
import uvicornIPV4_ADDR = '192.168.124.7'
IPV4_PORT = 8888
app = FastAPI()@app.get('/lanyue')
def index():# 读取要返回的文件内容with open('./lanyue/index.html', 'rb') as file:data = file.read()# 把data数据以text/html格式返回给浏览器端return Response(content=data, media_type='text/html')uvicorn.run(app, host=IPV4_ADDR, port=IPV4_PORT)