当前位置: 首页>>代码示例>>Python>>正文


Python fastapi.Query方法代码示例

本文整理汇总了Python中fastapi.Query方法的典型用法代码示例。如果您正苦于以下问题:Python fastapi.Query方法的具体用法?Python fastapi.Query怎么用?Python fastapi.Query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在fastapi的用法示例。


在下文中一共展示了fastapi.Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: read_items

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def read_items(
    q: Optional[str] = Query(
        None,
        alias="item-query",
        title="Query string",
        description="Query string for the items to search in the database that have a good match",
        min_length=3,
        max_length=50,
        regex="^fixedquery$",
        deprecated=True,
    )
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results 
开发者ID:tiangolo,项目名称:fastapi,代码行数:18,代码来源:tutorial010.py

示例2: get_directions_with_coordinates

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def get_directions_with_coordinates(
    # URL values
    f_lon: float,
    f_lat: float,
    t_lon: float,
    t_lat: float,
    # Query parameters
    type: str,
    language: str = "en",
    # Request
    request: Request = Depends(directions_request),
):
    from_place = Latlon(f_lat, f_lon)
    to_place = Latlon(t_lat, t_lon)
    if not type:
        raise HTTPException(status_code=400, detail='"type" query param is required')
    return directions_client.get_directions(
        from_place, to_place, type, language, params=request.query_params
    ) 
开发者ID:QwantResearch,项目名称:idunn,代码行数:21,代码来源:directions.py

示例3: get_directions

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def get_directions(
    # Query parameters
    origin: str = Query(..., description="Origin place id"),
    destination: str = Query(..., description="Destination place id"),
    type: str = Query(..., description="Transport mode"),
    language: str = Query("en", description="User language"),
    # Request
    request: Request = Depends(directions_request),
):
    rate_limiter.check_limit_per_client(request)
    try:
        from_place = place_from_id(origin)
        to_place = place_from_id(destination)
    except InvalidPlaceId as exc:
        raise HTTPException(status_code=404, detail=exc.message)

    return directions_client.get_directions(
        from_place, to_place, type, language, params=request.query_params
    ) 
开发者ID:QwantResearch,项目名称:idunn,代码行数:21,代码来源:directions.py

示例4: pydantic_exception_invalid_query

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def pydantic_exception_invalid_query(q: int = Query(...)):
    return {"q": q}


# def test_exception_handler_invalid_query():
#     with TestClient(app) as client:
#         response = client.get(
#             "/pydantic/exception/invalidquery/", params={"q": "$"}
#         )
#         assert response.status_code == 400
#         response = response.json()
#         assert response["error_codes"] == [400]
#         assert response["message"] == "Validation error."
#         assert response["fields"] == [
#             {
#                 "name": "q",
#                 "message": "Value is not a valid integer.",
#                 "error_code": 400,
#             }
#         ] 
开发者ID:identixone,项目名称:fastapi_contrib,代码行数:22,代码来源:test_exception_handlers.py

示例5: __new__

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def __new__(mcs, name, bases, namespace, *args, **kwargs):
        cls = super(PaginationMeta, mcs).__new__(mcs, name, bases, namespace)
        _cls__init__ = cls.__init__

        def __init__(
            self,
            request: Request,
            offset: int = Query(
                default=cls.default_offset, ge=0, le=cls.max_offset
            ),
            limit: int = Query(
                default=cls.default_limit, ge=1, le=cls.max_limit
            ),
        ):
            _cls__init__(self, request, offset, limit)

        setattr(cls, "__init__", __init__)
        return cls 
开发者ID:identixone,项目名称:fastapi_contrib,代码行数:20,代码来源:pagination.py

示例6: __init__

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def __init__(
        self,
        request: Request,
        offset: int = Query(default=default_offset, ge=0, le=max_offset),
        limit: int = Query(default=default_limit, ge=-1, le=max_limit),
        query: str = Query(default=""),
        multiple: bool = Query(default=False),
        sort: str = Query(default=""),
        desc: bool = Query(default=True),
    ):
        self.request = request
        self.offset = offset
        self.limit = limit
        self.query = query
        self.multiple = multiple
        if self.multiple:
            self.query = self.query.replace(",", "|")
        self.sort = sort
        self.desc = desc
        self.desc_s = "desc" if desc else ""
        self.model: Optional["ModelType"] = None 
开发者ID:MrNaif2018,项目名称:bitcart,代码行数:23,代码来源:pagination.py

示例7: __init__

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def __init__(
        self,
        *,
        response_format: str = Query(
            "json",
            description="The output format requested (see section Response Format).\nDefaults to the format string 'json', which specifies the standard output format described in this specification.\nExample: `http://example.com/v1/structures?response_format=xml`",
        ),
        email_address: EmailStr = Query(
            "",
            description="An email address of the user making the request.\nThe email SHOULD be that of a person and not an automatic system.\nExample: `http://example.com/v1/structures?email_address=user@example.com`",
        ),
        response_fields: str = Query(
            "",
            description="A comma-delimited set of fields to be provided in the output.\nIf provided, these fields MUST be returned along with the REQUIRED fields.\nOther OPTIONAL fields MUST NOT be returned when this parameter is present.\nExample: `http://example.com/v1/structures?response_fields=last_modified,nsites`",
            regex=r"([a-z_][a-z_0-9]*(,[a-z_][a-z_0-9]*)*)?",
        ),
        include: str = Query(
            "references",
            description='A server MAY implement the JSON API concept of returning [compound documents](https://jsonapi.org/format/1.0/#document-compound-documents) by utilizing the `include` query parameter as specified by [JSON API 1.0](https://jsonapi.org/format/1.0/#fetching-includes).\n\nAll related resource objects MUST be returned as part of an array value for the top-level `included` field, see the section JSON Response Schema: Common Fields.\n\nThe value of `include` MUST be a comma-separated list of "relationship paths", as defined in the [JSON API](https://jsonapi.org/format/1.0/#fetching-includes).\nIf relationship paths are not supported, or a server is unable to identify a relationship path a `400 Bad Request` response MUST be made.\n\nThe **default value** for `include` is `references`.\nThis means `references` entries MUST always be included under the top-level field `included` as default, since a server assumes if `include` is not specified by a client in the request, it is still specified as `include=references`.\nNote, if a client explicitly specifies `include` and leaves out `references`, `references` resource objects MUST NOT be included under the top-level field `included`, as per the definition of `included`, see section JSON Response Schema: Common Fields.\n\n> **Note**: A query with the parameter `include` set to the empty string means no related resource objects are to be returned under the top-level field `included`.',
        ),
    ):
        self.response_format = response_format
        self.email_address = email_address
        self.response_fields = response_fields
        self.include = include 
开发者ID:Materials-Consortia,项目名称:optimade-python-tools,代码行数:27,代码来源:query_params.py

示例8: matches

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def matches(
    hash: str, offset: int = Query(...), limit: int = Query(...)
) -> MatchesSchema:
    """
    Returns a list of matched files, along with metadata tags and other
    useful information. Results from this query can be used to download files
    using the `/download` endpoint.
    """
    return db.get_job_matches(JobId(hash), offset, limit) 
开发者ID:CERT-Polska,项目名称:mquery,代码行数:11,代码来源:app.py

示例9: test_invalid_sequence

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def test_invalid_sequence():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: List[Item] = Query(None)):
            pass  # pragma: no cover 
开发者ID:tiangolo,项目名称:fastapi,代码行数:12,代码来源:test_invalid_sequence_param.py

示例10: test_invalid_tuple

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def test_invalid_tuple():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: Tuple[Item, Item] = Query(None)):
            pass  # pragma: no cover 
开发者ID:tiangolo,项目名称:fastapi,代码行数:12,代码来源:test_invalid_sequence_param.py

示例11: test_invalid_dict

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def test_invalid_dict():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: Dict[str, Item] = Query(None)):
            pass  # pragma: no cover 
开发者ID:tiangolo,项目名称:fastapi,代码行数:12,代码来源:test_invalid_sequence_param.py

示例12: test_invalid_simple_dict

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def test_invalid_simple_dict():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: Optional[dict] = Query(None)):
            pass  # pragma: no cover 
开发者ID:tiangolo,项目名称:fastapi,代码行数:12,代码来源:test_invalid_sequence_param.py

示例13: get_query_param

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def get_query_param(query=Query(None)):
    if query is None:
        return "foo bar"
    return f"foo bar {query}" 
开发者ID:tiangolo,项目名称:fastapi,代码行数:6,代码来源:main.py

示例14: get_query_param_required_type

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def get_query_param_required_type(query: int = Query(...)):
    return f"foo bar {query}" 
开发者ID:tiangolo,项目名称:fastapi,代码行数:4,代码来源:main.py

示例15: read_items

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import Query [as 别名]
def read_items(q: List[int] = Query(None)):
    return {"q": q} 
开发者ID:tiangolo,项目名称:fastapi,代码行数:4,代码来源:test_multi_query_errors.py


注:本文中的fastapi.Query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。