FastAPI from entry to actual combat (13) - common configuration items

The content of this part is mainly some common configurations, including routing, static files, etc., as well as some path and document modifiers, including introduction, label parameters, etc.

Configure static files

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

To configure static files, you need to import the fastapicorresponding staticfilespackage, and then use mountthe method to mount the corresponding static file directory to appthe application;

For parameters, the parameter /staticspecifies the path to mount, that is, the root path for client access; the parameter StaticFilesspecifies that the static file is mounted; the parameter directory="static"specifies the directory of the static file; name="static"specifies fastapithe name of the internal identification;

The access effect is as follows, just enter it directly in the browser ip:端口/路径/文件全名.后缀;

image-20221203191947908

routing configuration

The overall directory structure is as follows, the main application is placed in the root directory, and other application packages are placed in the same directory as the main application;

image-20221203194345896

  • Create a new application in the application package stu01.py, and at the same time use the create i application in the application , stu01and then write the code for it;fastapiAPIRouterfastapapp01app01
# -*- coding: utf-8 -*-
# @Time: 2022/11/24 16:24
# @Author: MinChess
# @File: stu01.py
# @Software: PyCharm

from fastapi import APIRouter,Path
from enum import Enum


app01 = APIRouter()


@app01.get("/stu01/parameters")
def path_params01():
    return {
    
    "message": "This is a message"}
  • Import related applications in stuthe package__init__.py
# -*- coding: utf-8 -*-
# @Time: 2022/11/24 16:24
# @Author: MinChess
# @File: __init__.py.py
# @Software: PyCharm

from .stu01 import app01
from .stu02 import app02
from .stu03 import app03
from .stu04 import app04
from .stu05 import app05
from .stu06 import app06
from .stu07 import app07
from .stu08 import app08
  • Import the relevant application in the main program from stu import app01, app02, app03, app04, app05, app06, app07, app08, and then include_routermount the sub-application to the main application by using the parameter. The parameter app01specifies the sub-application to be mounted, prefix='/stu'indicating the access path of the sub-application, tagswhich is the label of the corresponding application in the specified document; tagsthe configuration document identifies the , has no effect on the request.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, PlainTextResponse, HTMLResponse
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
from stu import app01, app02, app03, app04, app05, app06, app07, app08

app = FastAPI(
    title='FastAPI学习教程文档——title',
    description='这是FastAPI教程的文档——description',
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redoc',
)

app.include_router(app01, prefix='/stu', tags=['路径参数与数值参数校验'])
app.include_router(app02, prefix='/stu', tags=['查询参数与字符串参数校验'])
app.include_router(app03, prefix="/stu", tags=['请求体与混合参数'])
app.include_router(app04, prefix="/stu", tags=['请求体函数参数设置'])
app.include_router(app05, prefix="/stu", tags=['cookie和header参数设置'])
app.include_router(app06, prefix="/stu", tags=['响应模型与状态码'])
app.include_router(app07, prefix="/stu", tags=['表单请求与上传文件'])
app.include_router(app08, prefix="/stu", tags=['错误处理和更新请求体'])

It is relatively simple to configure routing. Create a new pythonpackage, pythonuse it to create an application in the package APIRouter, and then mount the application to the main application;

image-20221203192516716

document configuration

app = FastAPI(
    # 创建一个FastAPI实例\这里的变量 app 会是 FastAPI 类的一个「实例」。\这个实例将是创建你所有 API 的主要交互对象。\这个 app 同样在命令中被 uvicorn 所引用:
    title='FastAPI学习教程文档——title',
    description='这是FastAPI教程的文档——description',
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redoc',
)

This was mentioned at the beginning of the project . These metadata are also used to set the information of the document. For the specific effect, please refer to the picture below;

image-20221203193212996

path configuration

@app.get("/hello/{name}", tags=["默认"], summary="这个是summary")
async def say_hello(name: str):
    """
    这里是文档字符串,可以用MarkDown
    - 序号
    - 序号
    ## 二级标题
    ```
    @app.exception_handler(StarletteHTTPException)
    async def http_exception_handler(request, exc):
        print(f"全局异常:{request.method}URL{request.url}Headers:{request.headers}{traceback.format_exc()}")
        return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
    ```
    """
    return {
    
    "message": f"Hello {
      
      name}"}

Same as the document configuration, these data are also added information for each requested path operation, which is directly passed to the path decorator function, and cannot be passed to the path operation function, mainly display information in the document;

Here is the content wrapped docstringin the above code . Note that this part of the content cannot be displayed at the same time and will be overwritten . It supports parsing format content, but the indentation needs to be controlled;"""descriptiondescriptiondocstringdocstringMarkDown

image-20221203193438599

Response Description Configuration

@app01.get(
    "/stu01/parameters",
    summary="响应summary",
    response_description="响应description"
           )
def path_params01():
    return {
    
    "message": "This is a message"}

Like other setting methods, just set the metadata directly in the path operation decorator, and you can refer to the source code for details.

image-20221203201820448

Deprecated path operations

Same as the above response description configuration, just set deprecated=True in the path decorator:

@app01.get("/stu01/{str}", deprecated=True)

Such a configuration is only shown as deprecated in the document, but in fact this request can still be used!

image-20221203202204038

In addition, for the setting of parameters (path parameters, query parameters...), they have been set in the previous section 4, and the methods are similar:

https://blog.jiumoz.com/archives/fastapi-cong-ru-men-dao-shi-zhan-lu-jing-can-shu-yu-shu-zhi-xiao-yan#%E5%85%83%E6%95%B0%E6%8D%AE


Thanks for reading!

Jiumozhai Address: https://blog.jiumoz.com/archives/fastapi-cong-ru-men-dao-shi-zhan-13-chang-jian-pei-zhi-xiang

Welcome to follow the blogger's personal mini program!

Guess you like

Origin blog.csdn.net/qq_45730223/article/details/128167229