{"id":8940,"date":"2023-09-13T01:40:28","date_gmt":"2023-09-12T17:40:28","guid":{"rendered":"\/?p=8940"},"modified":"2023-09-13T01:40:28","modified_gmt":"2023-09-12T17:40:28","slug":"fastapi%e5%9f%ba%e7%a1%80%ef%bc%9a6-%e4%b8%ad%e9%97%b4%e4%bb%b6%e4%be%9d%e8%b5%96%e6%b3%a8%e5%85%a5","status":"publish","type":"post","link":"\/?p=8940","title":{"rendered":"FastAPI\u57fa\u7840\uff1a6.\u4e2d\u95f4\u4ef6&#038;\u4f9d\u8d56\u6ce8\u5165"},"content":{"rendered":"<h2>\u4e2d\u95f4\u4ef6<\/h2>\n<p>ps\uff1a\u8bbf\u95ee\u6d41\u7a0b\u5927\u81f4\u5982\u4e0b\uff1a\u8fdb\u5165\u4e2d\u95f4\u4ef6 - \u89c6\u56fe - \u51fa\u4e2d\u95f4\u4ef6 - \u5ba2\u6237\u7aef<\/p>\n<p><a href=\"https:\/\/zhuanlan.zhihu.com\/p\/124919549\">\u4ec0\u4e48\u662f\u8de8\u57df\uff1f\u5982\u4f55\u5b9e\u73b0\uff08\u8be6\u89e3\uff09 - \u77e5\u4e4e (zhihu.com)<\/a><\/p>\n<pre><code class=\"language-python\">from typing import Union\n\nfrom fastapi import FastAPI, HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom starlette.requests import Request\nfrom uvicorn import run\nfrom fastapi_04 import R\n\n&quot;&quot;&quot;\n\u4e2d\u95f4\u4ef6 &amp; \u4f9d\u8d56\n&quot;&quot;&quot;\nfrom fastapi.middleware.cors import CORSMiddleware\n\n# \u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef6\n# 2023-07-01 \u5efa\u8bae\u4f7f\u7528route_class\u5b9e\u73b0\u8bf7\u6c42\u54cd\u5e94\u65e5\u5fd7\u8bb0\u5f55\uff1a\n# https:\/\/github.com\/zy7y\/mini-rbac\/commit\/0ef41c6cdecf18c444010dd6fdc14e5c3a015728\nclass CustomHeaderMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request, call_next):\n        print(&quot; CustomHeaderMiddleware \u6536\u5230\u4e86\u8bf7\u6c42-\u5230\u8fbe\u4e2d\u95f4\u4ef6\uff0c\u5904\u7406\u8bf7\u6c42\u903b\u8f91\u5f00\u59cb&quot;)\n        response = await call_next(request)\n        print(&quot;CustomHeaderMiddleware \u6267\u884c\u4e86\u89c6\u56fe\u51fd\u6570\uff0c\u62ff\u5230\u54cd\u5e94\u6570\u636e\uff0c\u5904\u7406\u54cd\u5e94\u6570\u636e&quot;)\n        response.headers[&#039;Custom&#039;] = &#039;Example&#039;\n        print(&quot;CustomHeaderMiddleware \u5904\u7406\u5b8c\u4e86 \u8fd4\u56de&quot;)\n        return response\n\nmiddleware = [\n    # \u8de8\u57df\u4e2d\u95f4\u4ef6\n    Middleware(CORSMiddleware, allow_origins=[&#039;*&#039;]),\n    Middleware(CustomHeaderMiddleware) # \u6700\u5148\u6dfb\u52a0\u7684\u4e2d\u95f4\u4ef6\n]\n# \u7ec4\u518c\u4e2d\u95f4\u4ef6\u7684\u65b9\u5f0f1\napp = FastAPI(middleware=middleware)\n\n# \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684\u6e90\u5217\u8868 [&#039;*&#039;] \u4ee3\u8868\u6240\u6709\norigins = [\n    &quot;http:\/\/localhost.tiangolo.com&quot;,\n    &quot;https:\/\/localhost.tiangolo.com&quot;,\n    &quot;http:\/\/localhost&quot;,\n    &quot;http:\/\/localhost:8080&quot;,\n]\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=origins,\n    allow_credentials=True,\n    allow_methods=[&quot;*&quot;],  # \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684 HTTP \u65b9\u6cd5\u5217\u8868\n    allow_headers=[&quot;*&quot;],  # \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684 HTTP \u8bf7\u6c42\u5934\u5217\u8868\n)\n\n# \u6ce8\u518c\u4e2d\u95f4\u4ef6\u65b9\u5f0f2\n@app.middleware(&quot;http&quot;)  # \u6700\u540e\u6dfb\u52a0\u7684\u4e2d\u95f4\u4ef6\nasync def globalExceptionHandler(request: Request, call_next):\n    try:\n        print(&quot; globalExceptionHandler \u68c0\u67e5\u662f\u5426\u5b58\u5728\u5f02\u5e38&quot;)\n        response = await call_next(request)\n    except HTTPException as e:\n        print(&quot; globalExceptionHandler \u8fd4\u4f1a\u5f02\u5e38\u5bf9\u8c61&quot;)\n        return R.fail(str(e))\n    print(&quot;globalExceptionHandler \u65e0\u5f02\u5e38\u8fd4\u56de&quot;)\n    return response\n\n@app.get(&quot;\/&quot;)\nasync def main():\n    return {&quot;message&quot;: &quot;Hello World&quot;}\n\nif __name__ == &quot;__main__&quot;:\n    # \u542f\u7528web\u670d\u52a1\uff0c reload -&gt; \u5f53\u6539\u53d8\u4ee3\u7801\u65f6\u81ea\u52a8\u91cd\u542f # fastapi_02:app\n    run(&quot;__main__:app&quot;, reload=True)<\/code><\/pre>\n<p>ps\uff1a\u8bbf\u95eemain\u6253\u5370\u4fe1\u606f<\/p>\n<pre><code class=\"language-shell\">globalExceptionHandler \u68c0\u67e5\u662f\u5426\u5b58\u5728\u5f02\u5e38\u3002# \u5148\u6267\u884c\u6700\u540e\u6dfb\u52a0\u4e2d\u95f4\u89c1\u7684call-next\u524d\u9762\u90e8\u5206\nCustomHeaderMiddleware \u6536\u5230\u4e86\u8bf7\u6c42-\u5230\u8fbe\u4e2d\u95f4\u4ef6\uff0c\u5904\u7406\u8bf7\u6c42\u903b\u8f91\u5f00\u59cb# \u6267\u884c\u6700\u5148\u6dfb\u52a0\u7684 call-next\u524d\u9762\u90e8\u5206\nCustomHeaderMiddleware \u6267\u884c\u4e86\u89c6\u56fe\u51fd\u6570\uff0c\u62ff\u5230\u54cd\u5e94\u6570\u636e\uff0c\u5904\u7406\u54cd\u5e94\u6570\u636e # \u6267\u884c\u5b8c\u540e\u6267\u884c\u6700\u5148\u6dfb\u52a0\u7684 call-next\u540e\u9762\u90e8\u5206\nCustomHeaderMiddleware \u5904\u7406\u5b8c\u4e86 \u8fd4\u56de\nglobalExceptionHandler \u65e0\u5f02\u5e38\u8fd4\u56de # \u6700\u540e\u6267\u884c\u6700\u540e\u6dfb\u52a0\u7684\u4e2d\u95f4\u4ef6call-next\u540e\u9762\u90e8\u5206<\/code><\/pre>\n<h2>\u4f9d\u8d56\u6ce8\u5165<\/h2>\n<p>ps\uff1a \u591a\u79cd\u5f62\u5f0f, \u4e2a\u4eba\u611f\u89c9\u548c\u4e2d\u95f4\u4ef6\u6709\u70b9\u7c7b\u4f3c<\/p>\n<pre><code class=\"language-python\"># \u4f9d\u8d56\u6ce8\u5165\ndef depends_hello():\n    print(&quot;depends_hello , run&quot;)\n    yield 1\n    print(&quot;depends_hello, over&quot;)\n\n# \u7c7b\u4f9d\u8d56\nclass CommonQueryParams:\n    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):\n        self.q = q\n        self.skip = skip\n        self.limit = limit\n\nfrom fastapi import APIRouter, Depends\n\n# \u8be5router\u4e0b\u6240\u6709\u8def\u7531\u90fd\u4f1a\u6267\u884c\u8fd9\u4e2a \u4f9d\u8d56\uff1b \u5168\u5c40\u4f9d\u8d56\u6ce8\u5165\u3001\nrouter = APIRouter(dependencies=[Depends(CommonQueryParams)])\n\n@router.get(&quot;\/123&quot;)\nasync def hello123():\n    return 123\n\n# \u5bf9\u8fd9\u4e2a\u89c6\u56fe\u6ce8\u5165\uff0c\u53ef\u4ee5\u62ff\u5230\u53c2\u6570\n@router.get(&quot;\/456&quot;)\nasync def hello456(num: int = Depends(depends_hello)):\n    print(&quot;\u8fdb\u4e86\u8bf7\u6c42&quot;)\n    return num\n\napp.include_router(router, dependencies=[])\n\n@app.get(&quot;\/321&quot;)\nasync def hello321(num = Depends(CommonQueryParams)):\n    return num\n<\/code><\/pre>\n<h2>\u5b8c\u6574\u4ee3\u7801<\/h2>\n<pre><code class=\"language-python\">from typing import Union\n\nfrom fastapi import FastAPI, HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom starlette.requests import Request\nfrom uvicorn import run\nfrom fastapi_04 import R\n\n&quot;&quot;&quot;\n\u4e2d\u95f4\u4ef6 &amp; \u4f9d\u8d56\n&quot;&quot;&quot;\nfrom fastapi.middleware.cors import CORSMiddleware\n\n# \u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef6\nclass CustomHeaderMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request, call_next):\n        print(&quot; CustomHeaderMiddleware \u6536\u5230\u4e86\u8bf7\u6c42-\u5230\u8fbe\u4e2d\u95f4\u4ef6\uff0c\u5904\u7406\u8bf7\u6c42\u903b\u8f91\u5f00\u59cb&quot;)\n        response = await call_next(request)\n        print(&quot;CustomHeaderMiddleware \u6267\u884c\u4e86\u89c6\u56fe\u51fd\u6570\uff0c\u62ff\u5230\u54cd\u5e94\u6570\u636e\uff0c\u5904\u7406\u54cd\u5e94\u6570\u636e&quot;)\n        response.headers[&#039;Custom&#039;] = &#039;Example&#039;\n        print(&quot;CustomHeaderMiddleware \u5904\u7406\u5b8c\u4e86 \u8fd4\u56de&quot;)\n        return response\n\nmiddleware = [\n    # \u8de8\u57df\u4e2d\u95f4\u4ef6\n    Middleware(CORSMiddleware, allow_origins=[&#039;*&#039;]),\n    Middleware(CustomHeaderMiddleware)\n]\n\napp = FastAPI(middleware=middleware)\n\n# \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684\u6e90\u5217\u8868 [&#039;*&#039;] \u4ee3\u8868\u6240\u6709\norigins = [\n    &quot;http:\/\/localhost.tiangolo.com&quot;,\n    &quot;https:\/\/localhost.tiangolo.com&quot;,\n    &quot;http:\/\/localhost&quot;,\n    &quot;http:\/\/localhost:8080&quot;,\n]\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=origins,\n    allow_credentials=True,\n    allow_methods=[&quot;*&quot;],  # \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684 HTTP \u65b9\u6cd5\u5217\u8868\n    allow_headers=[&quot;*&quot;],  # \u4e00\u4e2a\u5141\u8bb8\u8de8\u57df\u8bf7\u6c42\u7684 HTTP \u8bf7\u6c42\u5934\u5217\u8868\n)\n\n@app.middleware(&quot;http&quot;)\nasync def globalExceptionHandler(request: Request, call_next):\n    try:\n        print(&quot; globalExceptionHandler \u68c0\u67e5\u662f\u5426\u5b58\u5728\u5f02\u5e38&quot;)\n        response = await call_next(request)\n    except HTTPException as e:\n        print(&quot; globalExceptionHandler \u8fd4\u4f1a\u5f02\u5e38\u5bf9\u8c61&quot;)\n        return R.fail(str(e))\n    print(&quot;globalExceptionHandler \u65e0\u5f02\u5e38\u8fd4\u56de&quot;)\n    return response\n\n@app.get(&quot;\/&quot;)\nasync def main():\n    return {&quot;message&quot;: &quot;Hello World&quot;}\n\n@app.get(&quot;\/ok&quot;)\nasync def ok():\n    raise HTTPException(status_code=401)\n\n    # \u4f9d\u8d56\u6ce8\u5165\ndef depends_hello():\n    print(&quot;depends_hello , run&quot;)\n    yield 1\n    print(&quot;depends_hello, over&quot;)\n\n    # \u7c7b\u4f9d\u8d56\nclass CommonQueryParams:\n    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):\n        self.q = q\n        self.skip = skip\n        self.limit = limit\n\nfrom fastapi import APIRouter, Depends\n\n# \u8be5router\u4e0b\u6240\u6709\u8def\u7531\u90fd\u4f1a\u6267\u884c\u8fd9\u4e2a \u4f9d\u8d56\uff1b \u5168\u5c40\u4f9d\u8d56\u6ce8\u5165\u3001\nrouter = APIRouter(dependencies=[Depends(CommonQueryParams)])\n\n@router.get(&quot;\/123&quot;)\nasync def hello123():\n    return 123\n\n # \u62ff\u5230\u53c2\u6570\uff0c \u5bf9\u8fd9\u4e2a\u89c6\u56fe\u6ce8\u5165\uff0c\u53ef\u4ee5\u62ff\u5230\u53c2\u6570\uff0cnum \u662f\u6ce8\u5165\u4f9d\u8d56\u7684\u8c03\u7528\u7ed3\u679c\uff0c\u4e0d\u4f1a\u88ab\u4f5c\u4e3a\u67e5\u8be2\u53c2\u6570\n@router.get(&quot;\/456&quot;)\nasync def hello456(num: int = Depends(depends_hello)):\n    print(&quot;\u8fdb\u4e86\u8bf7\u6c42&quot;)\n    return num\n\napp.include_router(router, dependencies=[])\n\n@app.get(&quot;\/321&quot;)\nasync def hello321(num = Depends(CommonQueryParams)):\n    return num\n\nif __name__ == &quot;__main__&quot;:\n    # \u542f\u7528web\u670d\u52a1\uff0c reload -&gt; \u5f53\u6539\u53d8\u4ee3\u7801\u65f6\u81ea\u52a8\u91cd\u542f # fastapi_02:app\n    run(&quot;__main__:app&quot;, reload=True)\n<\/code><\/pre>\n<p><img src=\"https:\/\/lemon-guess.oss-cn-hangzhou.aliyuncs.com\/img\/1670145286601-46dab43f-ebc9-4fee-bca9-786b1887f000.png\" alt=\"image.png\" \/><\/p>\n<p>ps\uff1a\u8bbf\u95ee \/hello456 \u6253\u5370<\/p>\n<pre><code class=\"language-python\">globalExceptionHandler \u68c0\u67e5\u662f\u5426\u5b58\u5728\u5f02\u5e38\nCustomHeaderMiddleware \u6536\u5230\u4e86\u8bf7\u6c42-\u5230\u8fbe\u4e2d\u95f4\u4ef6\uff0c\u5904\u7406\u8bf7\u6c42\u903b\u8f91\u5f00\u59cb\ndepends_hello , run\n\u8fdb\u4e86\u8bf7\u6c42\nCustomHeaderMiddleware \u6267\u884c\u4e86\u89c6\u56fe\u51fd\u6570\uff0c\u62ff\u5230\u54cd\u5e94\u6570\u636e\uff0c\u5904\u7406\u54cd\u5e94\u6570\u636e\nCustomHeaderMiddleware \u5904\u7406\u5b8c\u4e86 \u8fd4\u56de\nglobalExceptionHandler \u65e0\u5f02\u5e38\u8fd4\u56de\nINFO:     127.0.0.1:50879 - &quot;GET \/456?q=123&amp;skip=0&amp;limit=100 HTTP\/1.1&quot; 200 OK\ndepends_hello, over<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u4e2d\u95f4\u4ef6 ps\uff1a\u8bbf\u95ee\u6d41\u7a0b\u5927\u81f4\u5982\u4e0b\uff1a\u8fdb\u5165\u4e2d\u95f4\u4ef6 &#8211; \u89c6\u56fe &#8211; \u51fa\u4e2d\u95f4\u4ef6 &#8211; \u5ba2\u6237\u7aef \u4ec0\u4e48\u662f\u8de8\u57df\uff1f\u5982\u4f55\u5b9e\u73b0\uff08\u8be6\u89e3\uff09 &#8211; \u77e5\u4e4e (zhihu.c   \u2026 &#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ngg_post_thumbnail":0},"categories":[204],"tags":[116],"_links":{"self":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8940"}],"collection":[{"href":"\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=8940"}],"version-history":[{"count":1,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8940\/revisions"}],"predecessor-version":[{"id":8941,"href":"\/index.php?rest_route=\/wp\/v2\/posts\/8940\/revisions\/8941"}],"wp:attachment":[{"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=8940"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=8940"},{"taxonomy":"post_tag","embeddable":true,"href":"\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=8940"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}