路径参数 (Path)

Oasis 使用 路径模版 来获取路径参数。即使用由大括号 ({}) 分隔的模板表达式,将 URL 路径的一部分标记为可使用路径参数进行替换。

路径参数会以同名关键字参数的形式传递给 API 类的 __init__ 方法,如下例:

views.py [示例1]
from django_oasis.core import Resource


@Resource("/pets/{pet_id}")
class API:
    def __init__(self, request, pet_id): ...

    def get(self): ...

这里在 URL 路径上标记了一个名为 pet_id 的路径参数,在处理请求时,API 类也将接收到同名的关键字参数。

SwaggerUI [示例1]

参数类型

路径参数默认类型为 django_oasis.schema.String,要为路径参数设置其他类型及验证规则需使用 Resource param_schemas 参数进行设置。

views.py [示例2]
from django_oasis import schema
from django_oasis.core import Resource


@Resource(
    "/pets/{pet_id}",
    param_schemas={"pet_id": schema.Integer()},
)
class API:
    def __init__(self, request, pet_id): ...

    def get(self): ...
SwaggerUI [示例2]

Path 类型

在获取路径参数时,默认是不匹配 ‘/’ 的。

django_oasis.schema.Path 用于匹配非空字段,包括路径分隔符 ‘/’。它允许匹配完整的 URL 路径而不是只匹配 URL 的一部分。

如下例,当请求路径为 /files/image/picture.png 时,获取的路径参数 filepathimage/picture.png

views.py [示例3]
from django_oasis import schema
from django_oasis.core import Resource


@Resource(
    "/files/{filepath}",
    param_schemas={"filepath": schema.Path()},
)
class API:
    def __init__(self, request, filepath): ...

    def get(self): ...

参数样式查询表

路径参数同样支持参数样式,使用 param_styles 参数进行设置。

数组样式

blue,black,brown (default)

以下示例的参数结果示例 color = ["blue", "black", "brown"]

views.py [示例4]
@Resource(
    "/array/simple/false/{color}",
    param_schemas={
        "color": schema.List(schema.String()),
    },
    param_styles={
        "color": Style("simple", False),  # 默认样式
    },
)
class ArraySimpleFalseAPI:
    def __init__(self, request, colors):
        self.colors = colors

    def get(self):
        ...

对象样式

以下示例的参数结果示例 color = {"R": 100, "G": 200, "B": 500}

R,100,G,200,B,150 (default)

views.py [示例4]
@Resource(
    "/object/simple/false/{color}",
    param_schemas={
        "color": schema.Model.from_dict(
            {
                "R": schema.Integer(),
                "G": schema.Integer(),
                "B": schema.Integer(),
            }
        )()
    },
    param_styles={
        "color": Style("simple", False),  # 默认样式
    },
)
class ObjectSimpleFalseAPI:
    def __init__(self, request, color):
        self.color = color

    def get(self):
        ...

R=100,G=200,B=150

views.py [示例4]
@Resource(
    "/object/simple/true/{color}",
    param_schemas={
        "color": schema.Model.from_dict(
            {
                "R": schema.Integer(),
                "G": schema.Integer(),
                "B": schema.Integer(),
            }
        )()
    },
    param_styles={
        "color": Style("simple", True),
    },
)
class ObjectSimpleTrueAPI:
    def __init__(self, request, color):
        self.color = color

    def get(self):
        ...
SwaggerUI [示例4]