async def get_question( question_id: UUID = Path(..., title="The ID of the question to get"), current_user: models.User = Depends(security.get_current_active_user), ): # TODO add user protection return crud.get_question(db=Session.object_session(current_user), question_id=question_id)
def get_model(resource: Optional[str] = Path(...)): if not resource: return for app, models in Tortoise.apps.items(): model = models.get(resource.title()) if model: return model
async def get_uniprot( qualifier: Any = Path( ..., description="UniProtKB accession number (AC) or entry name (ID)" ), provider: Optional[Any] = Query( None, enum=["swissmodel", "genome3d", "foldx", "pdb"] ), template: Optional[Any] = Query( None, description="Template is 4 letter PDB code, or 4 letter code with " "assembly ID and chain for SMTL entries", ), res_range: Optional[Any] = Query( None, description="Specify a UniProt sequence residue range", pattern="^[0-9]+-[0-9]+$", alias="range", ), ): """Returns experimental and theoretical models for a UniProt accession or entry name Args: qualifier (str): UniProtKB accession number (AC) or entry name (ID). provider (str, optional): Data provider template (str, optional): 4 letter PDB code, or 4 letter code with assembly ID and chain for SMTL entries res_range (str, optional): Residue range Returns: Result: A Result object with experimental and theoretical models. """ services = get_services(service_type="uniprot", provider=provider) calls = [] for service in services: base_url = get_base_service_url(service["provider"]) final_url = base_url + service["accessPoint"] + f"{qualifier}.json?" if res_range: final_url = f"{final_url}range={res_range}" calls.append(final_url) result = await send_async_requests(calls) final_result = [x.json() for x in result if x and x.status_code == 200] if not final_result: return JSONResponse(content={}, status_code=status.HTTP_404_NOT_FOUND) final_structures: List[Structure] = [] uniprot_entry: UniProtEntry = UniProtEntry(**final_result[0]["uniprot_entry"]) for item in final_result: final_structures.extend(item["structures"]) api_result: Result = Result( **{"uniprot_entry": uniprot_entry, "structures": final_structures} ) return api_result
async def get_courses( semester_id: str = Path( None, example="202101", description="The id of the semester, determined by the Registrar.", ), include_sections: bool = Query( False, description="Populate `sections` for each course."), include_periods: bool = Query( True, description="`NOT YET IMPLEMENTED` Populate `periods` of each section (only checked if `include_sections` is True)"), title: Optional[str] = Query(None, description="`NOT YET IMPLEMENTED`"), days: Optional[List[str]] = Query( None, description="`NOT YET IMPLEMENTED`"), subject_prefix: Optional[str] = Query( None, description="`NOT YET IMPLEMENTED`"), number: Optional[str] = Query(None, description="`NOT YET IMPLEMENTED`"), limit: int = Query( 10, description="The maximum number of course sections to return in the response. Max: 50", gt=0, lt=51, ), offset: int = Query( 0, description="The number of course sections in the response to skip." ), conn: RealDictConnection = Depends(postgres_pool.get_conn) ): courses = fetch_courses_without_sections(conn, semester_id, limit, offset) if include_sections: populate_course_periods(conn, semester_id, courses, include_sections) return courses
def get_model(resource: Optional[str] = Path(...)): if not resource: return for app, models in Tortoise.apps.items(): models = {key.lower(): val for key, val in models.items()} model = models.get(resource) if model: return model
async def delete_image( response: Response, image_id: str = Path(..., title="The ID of the image to delete"), authed_user: User = Depends(get_current_user), delete_image_action: DeleteImageAction = Depends(DeleteImageAction), ): delete_image_action( image_id, UserGet(username=authed_user.username, id=authed_user.id)) response.status_code = status.HTTP_204_NO_CONTENT
async def get_sections( semester_id: str = Path( None, example="202101", description="The id of the semester, determined by the Registrar.", ), crns: List[CRN] = Query( ..., description="The direct CRNs of the course sections to fetch.", example=["42608"], ), conn: RealDictConnection = Depends(postgres_pool.get_conn)): """Directly fetch course sections from CRNs.""" return fetch_course_sections(conn, semester_id, crns)
def post_items_all_params( item_id: str = Path(...), body: Item = Body(...), query_a: int = Query(None), query_b=Query(None), coo: str = Cookie(None), x_head: int = Header(None), x_under: str = Header(None, convert_underscores=False), ): return { "item_id": item_id, "body": body, "query_a": query_a, "query_b": query_b, "coo": coo, "x_head": x_head, "x_under": x_under, }
async def search_sections( semester_id: str = Path( None, example="202101", description="The id of the semester, determined by the Registrar.", ), course_subject_prefix: Optional[str] = Query(None), course_number: Optional[str] = Query(None), course_title: Optional[str] = Query(None), days: Optional[List[str]] = Query(None, title="Meeting days", description="`NOT YET IMPLEMENTED`"), has_seats: Optional[bool] = Query(None, title="Has open seats"), limit: int = Query( 10, description= "The maximum number of course sections to return in the response. Max: 50", gt=0, lt=51, ), offset: int = Query( 0, description="The number of course sections in the response to skip." ), conn: RealDictConnection = Depends(postgres_pool.get_conn)): """ Search course sections with different query parameters. Always returns a paginated response. """ return search_course_sections( conn, semester_id, limit, offset, course_subject_prefix=course_subject_prefix, course_number=course_number, course_title=course_title, has_seats=has_seats, )
def test_path_repr(params): assert repr(Path(params)) == "Path(Ellipsis)"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from fastapi.params import Path from luckydonaldUtils.logger import logging __author__ = 'luckydonald' logger = logging.getLogger(__name__) if __name__ == '__main__': logging.add_colored_handler(level=logging.DEBUG) # end if TOKEN_VALIDATION = Path(..., description="the bot's unique authentication token", min_length=1, regex=r"(bot\d+:[a-z0-9A-z-]|user\d+@[a-z0-9A-z_-])")
async def test2( moop: Json[TestModel] = Path(..., description='Something something'), foo: str = Query(...), ): return {'woop': moop, 'lol': foo}
class UserOperations: """ Operations on the User object """ @operation() @fastapi_route('GET', '/') def list(self) -> dict: """ Get a list of all users Returns: the list of users """ return {'users': []} @operation() @fastapi_route('POST', '/') def create(self, user: dict) -> dict: """ Create a user Args: user: The user to create Returns: the created user """ return {'user': user} @operation() @fastapi_route('GET', '/{id:int}', id=Path(...)) def get(self, id: int) -> dict: """ Get a user Args: id: The user to get Returns: the user """ return {'user': {'id': id}} @operation() @fastapi_route('PATCH', '/{id:int}', id=Path(...)) def update(self, id: int, user: dict) -> dict: """ Update a user Args: id: The user to update user: Updated fields Returns: the updated user """ return {'user': {'id': id, **user}} @operation() @fastapi_route('DELETE', '/{id:int}', id=Path(...)) def delete(self, id: int) -> dict: """ Delete a user Args: id: The user to delete Returns: the user """ return {'user': {'id': id}}
def get_path_param_required_id(item_id: str = Path(...)): return item_id
def get_path_param_id(item_id: str = Path(None)): return item_id