python构建一个 REST API 框架(精简版 Flask)。

以下是精简版Flask风格REST API框架的实现,包含核心路由、请求处理和响应封装功能:


from http.server import BaseHTTPRequestHandler, HTTPServer

import json

import re


class Request:

    def __init__(self, method, path, headers, body):

        self.method = method

        self.path = path

        self.headers = headers

        self.body = body


class Response:

    def __init__(self, data="", status=200, content_type="application/json"):

        self.data = json.dumps(data) if isinstance(data, dict) else data

        self.status = status

        self.content_type = content_type


class MiniFlask:

    def __init__(self):

        self.routes = {}

    

    def route(self, path, methods=["GET"]):

        def wrapper(handler):

            for method in methods:

                self.routes[(method.upper(), re.compile(path))] = handler

            return handler

        return wrapper

    

    def __call__(self, port=8000):

        class Handler(BaseHTTPRequestHandler):

            def do_GET(self): self.handle_request('GET')

            def do_POST(self): self.handle_request('POST')

            

            def handle_request(self, method):

                content_length = int(self.headers.get('Content-Length', 0))

                body = self.rfile.read(content_length).decode('utf-8')

                req = Request(method, self.path, self.headers, body)

                

                for (route_method, pattern), handler in self.routes.items():

                    if route_method == method and pattern.fullmatch(self.path):

                        resp = handler(req)

                        self.send_response(resp.status)

                        self.send_header('Content-type', resp.content_type)

                        self.end_headers()

                        self.wfile.write(resp.data.encode('utf-8'))

                        return

                

                self.send_response(404)

                self.end_headers()

        

        server = HTTPServer(('', port), Handler)

        print(f"Server running on port {port}")

        server.serve_forever()

from mini_flask import MiniFlask, Response


app = MiniFlask()


@app.route("/")

def home(request):

    return Response({"message": "Welcome to MiniFlask"})


@app.route("/hello/(.+)", methods=["GET"])

def hello(request):

    name = request.path.split('/')[-1]

    return Response(f"Hello, {name}!")


@app.route("/data", methods=["POST"])

def process_data(request):

    try:

        data = json.loads(request.body)

        return Response({"received": data})

    except:

        return Response({"error": "Invalid JSON"}, status=400)


if __name__ == "__main__":

    app(port=8080)

该实现包含路由装饰器、请求/响应对象和基础HTTP服务,支持动态路径参数和JSON处理。运行app.py即可启动示例API服务。

http://www.thedesignrepublic.com/

http://www.yxhgq.com/

http://www.jianhuotech.com/

http://www.bjyozd.com

http://www.sunny-way.cn/

http://www.cnsenkai.com/

http://www.zluren.com.cn/

http://www.cddtk119.com/

http://www.boao168.com.cn/

http://www.czs365.net/

http://www.ianvan.com/

http://www.fangzhoushidai.com

http://www.qiaosen-kj.com

http://gzhyxjj.cn

http://xatlzg.com

http://www.doushiwang.cn

http://www.sxyuanzheng.com

http://www.jwdyd.com

http://www.xaminglang.com

http://www.lboneti.cn

http://www.ahlongda.com

http://www.gdlanye.com

http://www.ktlcutter.com

http://www.hbzfjn.com

http://www.shbaimule.com

http://www.clgzkj.com

http://www.fjjhwy.cn

http://www.goodluck-lift.com

http://www.storlead.shop

http://magicians.com.cn

http://mall.yeepayer.com

http://tzkqzj.com

http://www.jinfanweilai.com

https://www.durkflex.cn/

http://www.szfmhj168.com.cn/

http://hfnz.ahaiba.com/

http://sjmzjypx010.ahaiba.com/

http://nyh.ahaiba.com/

http://thszsgs.com/

请使用浏览器的分享功能分享到微信等