Skip to content

Python使用http.server库搭建http服务

  • 实现效果:python使用http.server搭建http服务器,连接Mysql查询数据

  • 模块

    1. 工程目录

      tex
      ├─juicy-ocr-api # 项目根目录
      │  ├─api文件夹
      │  │  │  actressApi.py # 具体的查询接口
      │  │          
      │  ├─db文件夹
      │  │  │  connection.py # mysql连接信息
      │  │  
      │  ├─server.py # 服务器端入口
    2. server.py文件

      python
      from 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()
    3. connection.py文件

      python
      import pymysql
      
      def get_connection():
          return pymysql.connect(
              host='localhost',
              user='root',
              password='root',
              database='juicy',
              charset='utf8mb4'
          )
    4. actressApi.py文件

      • 安装依赖

        shell
        pip 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()
    5. 项目根目录下执行以下命令启动服务端

      shell
      python -m juicy-ocr-api.server
    6. 访问 http://localhost:8888/getActressList 即可得到数据

MIT版权,未经许可禁止任何形式的转载