當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。