Python使用http.server库搭建http服务
实现效果:python使用http.server搭建http服务器,连接Mysql查询数据
模块
工程目录
tex├─juicy-ocr-api # 项目根目录 │ ├─api文件夹 │ │ │ actressApi.py # 具体的查询接口 │ │ │ ├─db文件夹 │ │ │ connection.py # mysql连接信息 │ │ │ ├─server.py # 服务器端入口server.py文件
pythonfrom http.server import HTTPServer, BaseHTTPRequestHandler from .api.actressApi import get_actress_list class Request(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/getActressList': self.get_actress_list() # 查询所有演员的名称和序号接口 def get_actress_list(self): try: response = get_actress_list().encode('utf-8') self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(response) except Exception as e: self.send_response(500) self.end_headers() self.wfile.write(str(e).encode()) if __name__ == '__main__': host = ('localhost', 8888) server = HTTPServer(host, Request) print(f"服务器已启动,监听 {host[0]}:{host[1]}") server.serve_forever()connection.py文件
pythonimport pymysql def get_connection(): return pymysql.connect( host='localhost', user='root', password='root', database='juicy', charset='utf8mb4' )actressApi.py文件
安装依赖
shellpip install PyMySQL连接mysql,定义查询方法
python# 导入模块 import json from ..db.connection import get_connection import pymysql # 查询所有演员的名称和序号接口 def get_actress_list(): connection = get_connection() try: with connection.cursor(pymysql.cursors.DictCursor) as cursor: cursor.execute("SELECT * FROM j_actress") result = cursor.fetchall() return json.dumps(result, default=str, ensure_ascii=False) finally: connection.close()
项目根目录下执行以下命令启动服务端
shellpython -m juicy-ocr-api.server访问 http://localhost:8888/getActressList 即可得到数据