具有 GET 功能的 Python 3 简单 HTTP 服务器

问题描述 投票:0回答:3

我找不到任何相当于

的Python代码
python -m http.server port --bind addr --directory dir

所以我基本上需要一个工作服务器类来处理至少 GET 请求。我在 Google 上找到的大多数东西要么是具有某些特殊需求的 HTTP 服务器,要么是类似的东西,您需要自己编写响应行为:

from http.server import BaseHTTPRequestHandler, HTTPServer

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

run()

我需要的只是一个 Python HTTP 服务器的默认工作框架,您可以在其中提供地址、端口和目录,并且它通常会处理 GET 请求。

python python-3.x httpserver
3个回答
2
投票

您需要对

BaseHTTPRequestHandler
进行子类化才能处理请求:

class HTTPRequestHandler(BaseHTTPRequestHandler):
    """HTTP request handler with additional properties and functions."""

     def do_GET(self):
        """handle GET requests."""
        # Do stuff.

1
投票

这就是我最终的结果:

# python -m http.server 8000 --directory ./my_dir

from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler
import os


class HTTPHandler(SimpleHTTPRequestHandler):
    """This handler uses server.base_path instead of always using os.getcwd()"""
    def translate_path(self, path):
        path = SimpleHTTPRequestHandler.translate_path(self, path)
        relpath = os.path.relpath(path, os.getcwd())
        fullpath = os.path.join(self.server.base_path, relpath)
        return fullpath


class HTTPServer(BaseHTTPServer):
    """The main server, you pass in base_path which is the path you want to serve requests from"""
    def __init__(self, base_path, server_address, RequestHandlerClass=HTTPHandler):
        self.base_path = base_path
        BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)


web_dir = os.path.join(os.path.dirname(__file__), 'my_dir')
httpd = HTTPServer(web_dir, ("", 8000))
httpd.serve_forever()

处理 GET 请求的简单 HTTP 服务器,使用特定目录


-2
投票

为什么不使用 requests 库?

import requests

#the required first parameter of the 'get' method is the 'url'(instead of get you can use any other http type, as needed):

r = requests.get('https://stackoverflow.com/questions/73089846/python-3-simple-http-get-functional')

#you can print many other things as well such as content, text and so on
print(r.status_code) 

查看文档 https://requests.readthedocs.io/en/latest/

© www.soinside.com 2019 - 2024. All rights reserved.