當前位置: 首頁>>代碼示例>>Python>>正文


Python fastapi.Request方法代碼示例

本文整理匯總了Python中fastapi.Request方法的典型用法代碼示例。如果您正苦於以下問題:Python fastapi.Request方法的具體用法?Python fastapi.Request怎麽用?Python fastapi.Request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在fastapi的用法示例。


在下文中一共展示了fastapi.Request方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_directions_with_coordinates

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [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

示例2: get_route_handler

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def get_route_handler(self):
        handler_name = self.name
        original_handler = super().get_route_handler()

        async def custom_handler(request: Request) -> Response:
            method = request["method"]
            REQUESTS_INPROGRESS.labels(method=method, handler=handler_name).inc()
            try:
                before_time = time.monotonic()
                response = await original_handler(request)
                after_time = time.monotonic()
            except Exception as e:
                raise e from None
            else:
                REQUEST_DURATION.labels(method=method, handler=handler_name).observe(
                    after_time - before_time
                )
                REQUEST_COUNT.labels(
                    method=method, handler=handler_name, code=response.status_code
                ).inc()
            finally:
                REQUESTS_INPROGRESS.labels(method=method, handler=handler_name).dec()
            return response

        return custom_handler 
開發者ID:QwantResearch,項目名稱:idunn,代碼行數:27,代碼來源:prometheus.py

示例3: get_entry_info

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def get_entry_info(request: Request, entry: str):
    from optimade.models import EntryInfoResource

    valid_entry_info_endpoints = ENTRY_INFO_SCHEMAS.keys()
    if entry not in valid_entry_info_endpoints:
        raise StarletteHTTPException(
            status_code=404,
            detail=f"Entry info not found for {entry}, valid entry info endpoints are: {', '.join(valid_entry_info_endpoints)}",
        )

    schema = ENTRY_INFO_SCHEMAS[entry]()
    queryable_properties = {"id", "type", "attributes"}
    properties = retrieve_queryable_properties(schema, queryable_properties)

    output_fields_by_format = {"json": list(properties.keys())}

    return EntryInfoResponse(
        meta=meta_values(str(request.url), 1, 1, more_data_available=False),
        data=EntryInfoResource(
            formats=list(output_fields_by_format.keys()),
            description=schema.get("description", "Entry Resources"),
            properties=properties,
            output_fields_by_format=output_fields_by_format,
        ),
    ) 
開發者ID:Materials-Consortia,項目名稱:optimade-python-tools,代碼行數:27,代碼來源:info.py

示例4: test_existing_user

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def test_existing_user(
        self, test_app_client: httpx.AsyncClient, after_forgot_password, user
    ):
        json = {"email": "king.arthur@camelot.bt"}
        response = await test_app_client.post("/forgot-password", json=json)
        assert response.status_code == status.HTTP_202_ACCEPTED
        assert after_forgot_password.called is True

        actual_user = after_forgot_password.call_args[0][0]
        assert actual_user.id == user.id
        actual_token = after_forgot_password.call_args[0][1]
        decoded_token = jwt.decode(
            actual_token,
            SECRET,
            audience="fastapi-users:reset",
            algorithms=[JWT_ALGORITHM],
        )
        assert decoded_token["user_id"] == str(user.id)
        request = after_forgot_password.call_args[0][2]
        assert isinstance(request, Request) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:22,代碼來源:test_router_reset.py

示例5: test_empty_body

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def test_empty_body(
        self, test_app_client: httpx.AsyncClient, user: UserDB, after_update
    ):
        response = await test_app_client.patch(
            "/me", json={}, headers={"Authorization": f"Bearer {user.id}"}
        )
        assert response.status_code == status.HTTP_200_OK

        data = cast(Dict[str, Any], response.json())
        assert data["email"] == user.email

        assert after_update.called is True
        actual_user = after_update.call_args[0][0]
        assert actual_user.id == user.id
        updated_fields = after_update.call_args[0][1]
        assert updated_fields == {}
        request = after_update.call_args[0][2]
        assert isinstance(request, Request) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:20,代碼來源:test_router_users.py

示例6: test_valid_body

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def test_valid_body(
        self, test_app_client: httpx.AsyncClient, user: UserDB, after_update
    ):
        json = {"email": "king.arthur@tintagel.bt"}
        response = await test_app_client.patch(
            "/me", json=json, headers={"Authorization": f"Bearer {user.id}"}
        )
        assert response.status_code == status.HTTP_200_OK

        data = cast(Dict[str, Any], response.json())
        assert data["email"] == "king.arthur@tintagel.bt"

        assert after_update.called is True
        actual_user = after_update.call_args[0][0]
        assert actual_user.id == user.id
        updated_fields = after_update.call_args[0][1]
        assert updated_fields == {"email": "king.arthur@tintagel.bt"}
        request = after_update.call_args[0][2]
        assert isinstance(request, Request) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:21,代碼來源:test_router_users.py

示例7: test_valid_body_is_active

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def test_valid_body_is_active(
        self, test_app_client: httpx.AsyncClient, user: UserDB, after_update
    ):
        json = {"is_active": False}
        response = await test_app_client.patch(
            "/me", json=json, headers={"Authorization": f"Bearer {user.id}"}
        )
        assert response.status_code == status.HTTP_200_OK

        data = cast(Dict[str, Any], response.json())
        assert data["is_active"] is True

        assert after_update.called is True
        actual_user = after_update.call_args[0][0]
        assert actual_user.id == user.id
        updated_fields = after_update.call_args[0][1]
        assert updated_fields == {}
        request = after_update.call_args[0][2]
        assert isinstance(request, Request) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:21,代碼來源:test_router_users.py

示例8: get_register_router

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def get_register_router(
        self, after_register: Optional[Callable[[models.UD, Request], None]] = None,
    ) -> APIRouter:
        """
        Return a router with a register route.

        :param after_register: Optional function called
        after a successful registration.
        """
        return get_register_router(
            self.db,
            self._user_model,
            self._user_create_model,
            self._user_db_model,
            after_register,
        ) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:18,代碼來源:fastapi_users.py

示例9: get_reset_password_router

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def get_reset_password_router(
        self,
        reset_password_token_secret: str,
        reset_password_token_lifetime_seconds: int = 3600,
        after_forgot_password: Optional[
            Callable[[models.UD, str, Request], None]
        ] = None,
    ) -> APIRouter:
        """
        Return a reset password process router.

        :param reset_password_token_secret: Secret to encode reset password token.
        :param reset_password_token_lifetime_seconds: Lifetime of reset password token.
        :param after_forgot_password: Optional function called after a successful
        forgot password request.
        """
        return get_reset_password_router(
            self.db,
            reset_password_token_secret,
            reset_password_token_lifetime_seconds,
            after_forgot_password,
        ) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:24,代碼來源:fastapi_users.py

示例10: get_users_router

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def get_users_router(
        self,
        after_update: Optional[
            Callable[[models.UD, Dict[str, Any], Request], None]
        ] = None,
    ) -> APIRouter:
        """
        Return a router with routes to manage users.

        :param after_update: Optional function called
        after a successful user update.
        """
        return get_users_router(
            self.db,
            self._user_model,
            self._user_update_model,
            self._user_db_model,
            self.authenticator,
            after_update,
        ) 
開發者ID:frankie567,項目名稱:fastapi-users,代碼行數:22,代碼來源:fastapi_users.py

示例11: group

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def group(request: Request, response: Response, group_name: Optional[str] = None) -> Response:
    global state

    if group_name is not None:
        res = []
        for s in state.sources:
            for k, p in sorted(s.packages.items()):
                if group_name in p.groups:
                    res.append(p)

        return templates.TemplateResponse("group.html", {
            "request": request,
            "name": group_name,
            "packages": res,
        }, headers=dict(response.headers))
    else:
        groups: Dict[str, int] = {}
        for s in state.sources:
            for k, p in sorted(s.packages.items()):
                for name in p.groups:
                    groups[name] = groups.get(name, 0) + 1
        return templates.TemplateResponse('groups.html', {
            "request": request,
            "groups": groups,
        }, headers=dict(response.headers)) 
開發者ID:msys2,項目名稱:msys2-web,代碼行數:27,代碼來源:web.py

示例12: package

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def package(request: Request, response: Response, package_name: Optional[str] = None, repo: Optional[str] = None, variant: Optional[str] = None) -> Response:
    global state

    packages = []
    for s in state.sources:
        for k, p in sorted(s.packages.items()):
            if package_name is None or p.name == package_name or package_name in p.provides:
                if not repo or p.repo == repo:
                    if not variant or p.repo_variant == variant:
                        packages.append((s, p))

    if package_name is not None:
        return templates.TemplateResponse("package.html", {
            "request": request,
            "packages": packages,
        }, headers=dict(response.headers))
    else:
        return templates.TemplateResponse("packages.html", {
            "request": request,
            "packages": packages,
        }, headers=dict(response.headers)) 
開發者ID:msys2,項目名稱:msys2-web,代碼行數:23,代碼來源:web.py

示例13: queue

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def queue(request: Request, response: Response) -> Response:
    # Create entries for all packages where the version doesn't match
    updates = []
    for s in state.sources:
        for k, p in sorted(s.packages.items()):
            if p.name in state.sourceinfos:
                srcinfo = state.sourceinfos[p.name]
                if package_name_is_vcs(s.name):
                    continue
                if version_is_newer_than(srcinfo.build_version, p.version):
                    updates.append((srcinfo, s, p))
                    break

    updates.sort(
        key=lambda i: (i[0].date, i[0].pkgbase, i[0].pkgname),
        reverse=True)

    return templates.TemplateResponse("queue.html", {
        "request": request,
        "updates": updates,
    }, headers=dict(response.headers)) 
開發者ID:msys2,項目名稱:msys2-web,代碼行數:23,代碼來源:web.py

示例14: new

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def new(request: Request, response: Response) -> Response:
    # Create dummy entries for all GIT only packages
    available = {}
    for srcinfo in state.sourceinfos.values():
        if package_name_is_vcs(srcinfo.pkgbase):
            continue
        available[srcinfo.pkgbase] = srcinfo
    for s in state.sources:
        available.pop(s.name, None)
    new = list(available.values())

    new.sort(
        key=lambda i: (i.date, i.pkgbase, i.pkgname),
        reverse=True)

    return templates.TemplateResponse("new.html", {
        "request": request,
        "new": new,
    }, headers=dict(response.headers)) 
開發者ID:msys2,項目名稱:msys2-web,代碼行數:21,代碼來源:web.py

示例15: github_payload

# 需要導入模塊: import fastapi [as 別名]
# 或者: from fastapi import Request [as 別名]
def github_payload(request: Request) -> Response:
    secret = os.environ.get("GITHUB_WEBHOOK_SECRET")
    if not secret:
        raise HTTPException(500, 'webhook secret config incomplete')

    if not await check_github_signature(request, secret):
        raise HTTPException(400, 'Invalid signature')

    event = request.headers.get('X-GitHub-Event', '')
    if event == 'ping':
        return JSONResponse({'msg': 'pong'})
    if event == 'push':
        account = os.environ.get("APPVEYOR_ACCOUNT")
        project = os.environ.get("APPVEYOR_PROJECT")
        token = os.environ.get("APPVEYOR_TOKEN")
        if not account or not project or not token:
            raise HTTPException(500, 'appveyor config incomplete')
        build_url = await trigger_appveyor_build(account, project, token)
        return JSONResponse({'msg': 'triggered a build: %s' % build_url})
    else:
        raise HTTPException(400, 'Unsupported event type: ' + event) 
開發者ID:msys2,項目名稱:msys2-web,代碼行數:23,代碼來源:web.py


注:本文中的fastapi.Request方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。