Python fastapi.Request() Examples

The following are 30 code examples of fastapi.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fastapi , or try the search function .
Example #1
Source File: directions.py    From idunn with Apache License 2.0 7 votes vote down vote up
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
    ) 
Example #2
Source File: web.py    From msys2-web with MIT License 6 votes vote down vote up
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)) 
Example #3
Source File: web.py    From msys2-web with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: web.py    From msys2-web with MIT License 6 votes vote down vote up
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)) 
Example #5
Source File: web.py    From msys2-web with MIT License 6 votes vote down vote up
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)) 
Example #6
Source File: web.py    From msys2-web with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: prometheus.py    From idunn with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: fastapi_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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,
        ) 
Example #9
Source File: fastapi_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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,
        ) 
Example #10
Source File: fastapi_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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,
        ) 
Example #11
Source File: test_router_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: test_router_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: test_router_users.py    From fastapi-users with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: test_router_reset.py    From fastapi-users with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: info.py    From optimade-python-tools with MIT License 6 votes vote down vote up
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,
        ),
    ) 
Example #16
Source File: register.py    From fastapi-users with MIT License 5 votes vote down vote up
def get_register_router(
    user_db: BaseUserDatabase[models.BaseUserDB],
    user_model: Type[models.BaseUser],
    user_create_model: Type[models.BaseUserCreate],
    user_db_model: Type[models.BaseUserDB],
    after_register: Optional[Callable[[models.UD, Request], None]] = None,
) -> APIRouter:
    """Generate a router with the register route."""
    router = APIRouter()

    @router.post(
        "/register", response_model=user_model, status_code=status.HTTP_201_CREATED
    )
    async def register(request: Request, user: user_create_model):  # type: ignore
        user = cast(models.BaseUserCreate, user)  # Prevent mypy complain
        existing_user = await user_db.get_by_email(user.email)

        if existing_user is not None:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=ErrorCode.REGISTER_USER_ALREADY_EXISTS,
            )

        hashed_password = get_password_hash(user.password)
        db_user = user_db_model(
            **user.create_update_dict(), hashed_password=hashed_password
        )
        created_user = await user_db.create(db_user)

        if after_register:
            await run_handler(after_register, created_user, request)

        return created_user

    return router 
Example #17
Source File: web.py    From msys2-web with MIT License 5 votes vote down vote up
def is_endpoint(request: Request, endpoint: str) -> bool:
    path: str = request.scope["path"]
    return path == "/" + endpoint or path.startswith("/" + endpoint + "/") 
Example #18
Source File: test_router_register.py    From fastapi-users with MIT License 5 votes vote down vote up
def test_valid_body(self, test_app_client: httpx.AsyncClient, after_register):
        json = {"email": "lancelot@camelot.bt", "password": "guinevere"}
        response = await test_app_client.post("/register", json=json)
        assert response.status_code == status.HTTP_201_CREATED
        assert after_register.called is True

        data = cast(Dict[str, Any], response.json())
        assert "hashed_password" not in data
        assert "password" not in data
        assert data["id"] is not None

        actual_user = after_register.call_args[0][0]
        assert str(actual_user.id) == data["id"]
        request = after_register.call_args[0][1]
        assert isinstance(request, Request) 
Example #19
Source File: web.py    From msys2-web with MIT License 5 votes vote down vote up
def check_github_signature(request: Request, secret: str) -> bool:
    signature = request.headers.get('X-Hub-Signature', '')
    mac = hmac.new(secret.encode("utf-8"), await request.body(), hashlib.sha1)
    return hmac.compare_digest("sha1=" + mac.hexdigest(), signature) 
Example #20
Source File: oauth_full_sqlalchemy.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}") 
Example #21
Source File: web.py    From msys2-web with MIT License 5 votes vote down vote up
def get_etag(request: Request) -> str:
    return state.etag 
Example #22
Source File: test_router_oauth.py    From fastapi-users with MIT License 5 votes vote down vote up
def test_unknown_user(
        self,
        mock_user_db_oauth,
        test_app_client: httpx.AsyncClient,
        oauth_client,
        after_register,
    ):
        state_jwt = generate_state_token({"authentication_backend": "mock"}, "SECRET")
        with asynctest.patch.object(
            oauth_client, "get_access_token"
        ) as get_access_token_mock:
            get_access_token_mock.return_value = {
                "access_token": "TOKEN",
                "expires_at": 1579179542,
            }
            with asynctest.patch.object(
                oauth_client, "get_id_email"
            ) as get_id_email_mock:
                with asynctest.patch.object(
                    mock_user_db_oauth, "create"
                ) as user_create_mock:
                    get_id_email_mock.return_value = (
                        "unknown_user_oauth1",
                        "galahad@camelot.bt",
                    )
                    response = await test_app_client.get(
                        "/callback", params={"code": "CODE", "state": state_jwt},
                    )

        get_id_email_mock.assert_awaited_once_with("TOKEN")
        user_create_mock.assert_awaited_once()
        data = cast(Dict[str, Any], response.json())

        assert "token" in data

        assert after_register.called is True
        actual_user = after_register.call_args[0][0]
        assert str(actual_user.id) == data["token"]
        request = after_register.call_args[0][1]
        assert isinstance(request, Request) 
Example #23
Source File: full_mongodb.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_register(user: UserDB, request: Request):
    print(f"User {user.id} has registered.") 
Example #24
Source File: full_sqlalchemy.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}") 
Example #25
Source File: full_sqlalchemy.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_register(user: UserDB, request: Request):
    print(f"User {user.id} has registered.") 
Example #26
Source File: oauth_full_mongodb.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}") 
Example #27
Source File: oauth_full_mongodb.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_register(user: UserDB, request: Request):
    print(f"User {user.id} has registered.") 
Example #28
Source File: oauth_full_tortoise.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_register(user: UserDB, request: Request):
    print(f"User {user.id} has registered.") 
Example #29
Source File: web.py    From msys2-web with MIT License 5 votes vote down vote up
def package_name(request: Request, package: Package, name: str = None) -> str:
    name = name or package.name
    name = re.split("[<>=]+", name, 1)[0]
    return (name or package.name) 
Example #30
Source File: full_tortoise.py    From fastapi-users with MIT License 5 votes vote down vote up
def on_after_forgot_password(user: UserDB, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}")