当前位置:   article > 正文

FastAPI Web框架教程 第2章 Path和Query_fastapi query

fastapi query

2-1 路径转换器

需求场景

我们知道路径中的参数(或者说从URL提取出来来的参数)都是字符串类型

需求1:如果我们定义了动态路径参数,那如果需要做类型转化的时候,除了在路径函数内使用类型提示的方式,还有其他方式吗?

需求2:如果我的动态路径参数就是路径,比如: /files/data/abc.txt,如何获取data/abc.txt这个参数?

FastAPI的解决方式

示例1:使用路径转化器 int,可以直接帮我们将这个参数转化为int类型

import typing
from fastapi import FastAPI


app = FastAPI(title="路径转化器")

books = {
   
    1: {
   "id": 1, "name": "图书1"},
    2: {
   "id": 2, "name": "图书2"},
    3: {
   "id": 3, "name": "图书3"},
}


@app.get("/books/{id:int}")		# 注意 {id:int}  :两边不能有空格
def get_books_by_id(id):
    print(id, type(id))
    return books.get(id)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注意1:get_books_by_id(id)因为此时没有在路径函数内使用类型提示,所以openapi文档没有了类型校验功能

注意2:如果参数类型不匹配,则直接返回404 Not Found,程序是不会执行路径函数内的代码。

示例2:普通路径参数无法获取路径值

# main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path}")
def read_file(file_path: str):
    print(file_path)
    with open(file_path, "r") as f:
        return f.read()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 比如,在当前路径下有一个aaa文件夹,其中有一个abc.txt文件

  • 此时,你想通过访问URL: /files/aaa/abc.txt,将变量:aaa/abc.txt传递给file_path这个形参

  • 那这种情况下示例2的代码不能解决我们的需求。

  • 此时需要使用路径转化器:path

示例3:使用路径转化器 path,帮我们找到路径值

# main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
def read_file(file_path: str):
    print(file_path)
    with open(file_path, "r") as f:
        return f.read()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

内置5中路径转化器

  • str 返回字符串(默认方式)
  • int 返回Python中的int
  • float 返回Python中的float.
  • uuid 返回Python中的uuid.UUID
  • path 返回路径,可以包含任意多个的/

补充1:这些内置转化器是Fastapi直接复用Starlette中的路径转化器

补充2:除了这5个转化器,我们也可以自定义符合自己需求的转化器(参考官网代码)

from datetime import datetime

from starlette.convertors import Convertor, register_url_convertor


class DateTimeConvertor(Convertor):
   regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?"

   def convert(self, value: str) -> datetime:
       return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")

   def to_string(self, value: datetime) -> str:
       return value.strftime("%Y-%m-%dT%H:%M:%S")

register_url_convertor("datetime", DateTimeConvertor())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2-2 路径参数枚举值

需求场景

我们有一个博客网站,需要定义一个根据标签来查询博客的接口,比如:/blogs/{tag}

这种情况下,一般有固定的几种标签类型,比如:tag的值只有三种类型:python、linux、web

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/912046
推荐阅读
相关标签
  

闽ICP备14008679号