繁体   English   中英

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

[英]Python 3 simple http server with GET functional

我找不到任何等效的python代码

python -m http.server port --bind addr --directory dir

所以我需要至少可以处理 GET 请求的基本工作服务器类。 我在谷歌上找到的大多数东西都是有一些特殊需求的 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 请求。

您需要BaseHTTPRequestHandler来处理请求:

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

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

为什么不使用请求库?

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/

这就是我最终的结果:

# 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 服务器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM