async def api_get_global_leaderboard( sort: Literal["tscore", "rscore", "pp", "acc"] = "pp", mode_arg: int = Query(0, alias="mode", ge=0, le=7), limit: int = Query(25, ge=1, le=100), offset: int = Query(0, min=0, max=2_147_483_647), country: Optional[str] = Query(None, min_length=2, max_length=2), db_conn: databases.core.Connection = Depends(acquire_db_conn), ): mode = GameMode(mode_arg) query_conditions = ["s.mode = :mode", "u.priv & 1", f"s.{sort} > 0"] query_parameters: dict[str, object] = {"mode": mode} if country is not None: query_conditions.append("u.country = :country") query_parameters["country"] = country rows = await db_conn.fetch_all( "SELECT u.id as player_id, u.name, u.country, s.tscore, s.rscore, " "s.pp, s.plays, s.playtime, s.acc, s.max_combo, " "s.xh_count, s.x_count, s.sh_count, s.s_count, s.a_count, " "c.id as clan_id, c.name as clan_name, c.tag as clan_tag " "FROM stats s " "LEFT JOIN users u USING (id) " "LEFT JOIN clans c ON u.clan_id = c.id " f"WHERE {' AND '.join(query_conditions)} " f"ORDER BY s.{sort} DESC LIMIT :offset, :limit", query_parameters | {"offset": offset, "limit": limit}, ) return ORJSONResponse( {"status": "success", "leaderboard": [dict(row) for row in rows]}, )
def resize_image( src_path: str = Query(..., max_length=255), dst_path: str = Query(..., max_length=255), height: int = Query(..., gt=0), width: int = Query(..., gt=0), ): return redactor.resize(src_path, dst_path, width, height)
async def get_true_pos( planet: Planet, date_params: DateParams = Depends(), number_of_values: int = Query(1, ge=1), step: int = Query(1, ge=1), executor: ProcessPoolExecutor = Depends(get_executor), ): start_date = safe_date(JULIAN_CALENDAR, date_params) dates = (start_date + i for i in range(0, number_of_values * step, step)) loop = asyncio.get_running_loop() results = [ ( date.jdn, loop.run_in_executor( executor, compute_true_pos, planet, date.days_from_epoch() ), ) for date in dates ] return [ {"jdn": jdn, "position": await result_awaitable} for jdn, result_awaitable in results ]
async def api_get_map_info( map_id: Optional[int] = Query(None, alias="id", ge=3, le=2_147_483_647), md5: Optional[str] = Query(None, alias="md5", min_length=32, max_length=32), ): """Return information about a given beatmap.""" if map_id is not None: bmap = await Beatmap.from_bid(map_id) elif md5 is not None: bmap = await Beatmap.from_md5(md5) else: return ORJSONResponse( {"status": "Must provide either id or md5!"}, status_code=status.HTTP_400_BAD_REQUEST, ) if not bmap: return ORJSONResponse( {"status": "Map not found."}, status_code=status.HTTP_404_NOT_FOUND, ) return ORJSONResponse( { "status": "success", "map": bmap.as_dict, }, )
def read_pages(current_user: User = Security(get_current_user), page: Optional[int] = Query(1, gt=0), page_size: Optional[int] = Query(10, gt=0)): pages = services.pages.retrieve_multiple(current_user, page=page, page_size=page_size) results = parse_obj_as(List[Page], list(pages)) return results
def get_pages_by_type(page_type: str, current_user: User = Security(get_current_user), page: Optional[int] = Query(1, gt=0), page_size: Optional[int] = Query(10, gt=0)): pages = services.pages.retrieve_by_page_type(current_user, page_type, page, page_size) results = parse_obj_as(List[Page], list(pages)) return results
def get_search_customer( search_term: str = Query(..., title='String to search'), search_criteria: str = Query(..., title='Criteria to search'), ): search_object = SearchQuery(search_term=search_term, search_criteria=search_criteria) operator = CustomerOperator() cursor = operator.get_search_result(search_object) return {'results': list(cursor)}
async def get_items( db: Session = Depends(get_db), *, skip: int = Query(0), limit: int = Query(100), ) -> Any: """ Gets all the items """ return await crud.item.get_multi(db, skip=skip, limit=limit)
async def get_business( db: Session = Depends(get_db), *, skip: int = Query(0), limit: int = Query(100), ) -> Any: """ Gets all the Business """ b = await crud.business.get_multi(db, skip=skip, limit=limit) return b
def __init__( self, year: int, month: int = Query(..., ge=1), day: int = Query(..., ge=1), hours: int = Query(12, ge=0, lt=24), minutes: int = Query(0, ge=0, lt=60), ): self.year = year self.month = month self.day = day self.hours = hours self.minutes = minutes
async def get_users( db: Session = Depends(get_db), *, get_deactivated: bool = Query(False), skip: int = Query(0), limit: int = Query(100), ) -> Any: """ Gets all the users """ return await crud.user.get_multi( db, skip=skip, limit=limit, get_deactivated=get_deactivated )
async def api_get_player_most_played( user_id: Optional[int] = Query(None, alias="id", ge=3, le=2_147_483_647), username: Optional[str] = Query(None, alias="name", regex=regexes.USERNAME.pattern), mode_arg: int = Query(0, alias="mode", ge=0, le=7), limit: int = Query(25, ge=1, le=100), db_conn: databases.core.Connection = Depends(acquire_db_conn), ): """Return the most played beatmaps of a given player.""" # NOTE: this will almost certainly not scale well, lol. if user_id is not None: p = await app.state.sessions.players.from_cache_or_sql(id=user_id) elif username is not None: p = await app.state.sessions.players.from_cache_or_sql(name=username) else: return ORJSONResponse( {"status": "Must provide either id or name."}, status_code=status.HTTP_400_BAD_REQUEST, ) if not p: return ORJSONResponse( {"status": "Player not found."}, status_code=status.HTTP_404_NOT_FOUND, ) # parse args (mode, limit) mode = GameMode(mode_arg) # fetch & return info from sql rows = await db_conn.fetch_all( "SELECT m.md5, m.id, m.set_id, m.status, " "m.artist, m.title, m.version, m.creator, COUNT(*) plays " f"FROM {mode.scores_table} s " "INNER JOIN maps m ON m.md5 = s.map_md5 " "WHERE s.userid = :user_id " "AND s.mode = :mode_vn " "GROUP BY s.map_md5 " "ORDER BY plays DESC " "LIMIT :limit", {"user_id": p.id, "mode_vn": mode.as_vanilla, "limit": limit}, ) return ORJSONResponse( { "status": "success", "maps": [dict(row) for row in rows], }, )
def api_export_energy_year( engine: Any = Depends(get_database_engine), network_code: str = Query("WEM", description="Network code"), year: int = Query(YEAR_CURRENT, description="Year to query"), ) -> OpennemDataSet: if year > YEAR_CURRENT or year < 1996: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Invalid year" ) network: NetworkSchema = network_from_network_code(network_code) if not network: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Invalid network", ) stats = energy_network_fueltech_api( network_code=network.code, network_region=None, interval="1d", year=year, period="1Y", engine=engine, ) weather = station_observations_api( station_code="009021", interval="1d", year=year, network_code="WEM", engine=engine, period=None, ) price = price_network_region_api( engine=engine, network_code="WEM", network_region_code="WEM", interval="1d", period=None, year=year, ) stats.data += weather.data + price.data return stats
def read_page( uid: str, version: Optional[int] = Query(None, gt=0), current_user: User = Security(get_current_user), ): if version is not None: try: page = services.pages.retrieve_version(current_user, uid, version) except VersionNotFoundError: raise HTTPException( status_code=404, detail="version not found", ) except ObjectNotFoundError: raise HTTPException( status_code=404, detail="object not found", ) return page else: page = services.pages.retrieve_one(current_user, uid) if page is None: raise HTTPException( status_code=404, detail="object not found", ) return page
def thumb(id: str, background_tasks: BackgroundTasks, request: Request, user: Optional[UserBase] = Depends(auth_optional_dependency), analytics: bool = Query(True, description="Opt out of view recording.")): with get_conn() as conn: file_information = r.table("files").get(id).run(conn) if not file_information: raise HTTPException(status.HTTP_404_NOT_FOUND) file_information_parsed = FileInDB.parse_obj(file_information) thumb_path = Path(THUMBS_PATH, file_information_parsed.file) if not thumb_path.exists(): background_tasks.add_task(create_thumb, img_filename=file_information_parsed.file, mime=file_information_parsed.mime) return RedirectResponse(request.url_for("img", id=id)) if file_information_parsed.private and not compare_owner( file_information_parsed, user): raise HTTPException(status.HTTP_401_UNAUTHORIZED) if analytics: background_tasks.add_task( record_view, file_information_parsed=file_information_parsed) return FileResponse(thumb_path, media_type=file_information_parsed.mime)
async def get_orders( db: Session = Depends(get_db), *, get_active: bool = Query(None), skip: int = Query(0), limit: int = Query(100), ) -> Any: """ Gets all the Orders. **get_active**: gets only the orders where is_received is False. if set to False, gets only the order that has been received. """ orders = await crud.order.get_multi(db, get_active=get_active) return orders
async def api_get_score_info( score_id: int = Query(..., alias="id", ge=0, le=9_223_372_036_854_775_807), db_conn: databases.core.Connection = Depends(acquire_db_conn), ): """Return information about a given score.""" if SCOREID_BORDERS[0] > score_id >= 1: scores_table = "scores_vn" elif SCOREID_BORDERS[1] > score_id >= SCOREID_BORDERS[0]: scores_table = "scores_rx" elif SCOREID_BORDERS[2] > score_id >= SCOREID_BORDERS[1]: scores_table = "scores_ap" else: return ORJSONResponse( {"status": "Invalid score id."}, status_code=status.HTTP_400_BAD_REQUEST, ) row = await db_conn.fetch_one( "SELECT map_md5, score, pp, acc, max_combo, mods, " "n300, n100, n50, nmiss, ngeki, nkatu, grade, status, " "mode, play_time, time_elapsed, perfect " f"FROM {scores_table} " "WHERE id = :score_id", {"score_id": score_id}, ) if not row: return ORJSONResponse( {"status": "Score not found."}, status_code=status.HTTP_404_NOT_FOUND, ) return ORJSONResponse({"status": "success", "score": dict(row)})
def img(id: str, background_tasks: BackgroundTasks, user: Optional[UserBase] = Depends(auth_optional_dependency), analytics: bool = Query(True, description="Opt out of view recording.")): with get_conn() as conn: file_information = r.table("files").get(id).run(conn) if not file_information: raise HTTPException(status.HTTP_404_NOT_FOUND) file_information_parsed = FileInDB.parse_obj(file_information) img_path = Path(FILES_PATH, file_information_parsed.file) if not img_path.exists(): raise HTTPException(status.HTTP_404_NOT_FOUND) if file_information_parsed.private and not compare_owner( file_information_parsed, user): raise HTTPException(status.HTTP_401_UNAUTHORIZED) if analytics: background_tasks.add_task( record_view, file_information_parsed=file_information_parsed) return FileResponse(img_path, media_type=file_information_parsed.mime)
def fetch_chat_messages_between_two_users( between: List[str] = Query(...), desc: bool = True, page: int = 1, page_size: int = 20, admin: Session = Depends(get_current_admin_user), session: Session = Depends(get_database_session), ): if len(between) != 2 or (between[0] == between[1]): raise HTTPException(400, "between must contain two unique ids") between = [UUID(x) for x in between] query = session.query(ChatMessage).filter( or_(ChatMessage.from_user.in_(between), ChatMessage.to_user.in_(between))) if desc: query = query.order_by(ChatMessage.created_at.desc()) else: query = query.order_by(ChatMessage.created_at.asc()) count = query.count() query = query.offset((page - 1) * page_size).limit(page_size) return { "page": page, "page_size": page_size, "count": count, "data": query.all() }
def get_optional_current_user_from_state( session: Session = Depends(get_database_session), application: Application = Depends(get_application), state: Optional[str] = Query(None), ): """ Get and return user from state query parameter if any """ if not state or state.strip() == "": return credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload_from_state = serializer.loads(state) access_token = payload_from_state["access_token"] if not access_token: return user: User = application.authenticate_token(session, access_token) if user.role == UserRole.ADMIN: user = session.query(Admin).get(user.id) elif user.role == UserRole.TENANT: user = session.query(Tenant).get(user.id) elif user.role == UserRole.LANDLORD: user = session.query(Landlord).get(user.id) except ApplicationError: raise credentials_exception except BadSignature: raise credentials_exception except KeyError: raise credentials_exception return user
async def common_parameters( skip: int = 0, limit: int = 100, filter: List[str] = Query( None, description= "This filter can accept search query's like `key:value` and will split on the `:`. If it " "detects more than one `:`, or does not find a `:` it will search for the string in all columns.", ), sort: List[str] = Query( None, description= "The sort will accept parameters like `col:ASC` or `col:DESC` and will split on the `:`. " "If it does not find a `:` it will sort ascending on that column.", ), ) -> Dict[str, Union[List[str], int]]: return {"skip": skip, "limit": limit, "filter": filter, "sort": sort}
async def get_object( key: str = Query( ..., alias=key_name, title=f"The {key_name} of the {model_name} to get", ), path_type: BSPathType = Query( ..., title= "The k-path convention type for the band structure object", ), fields: STORE_PARAMS = Depends(field_input), ): f""" Get's a document by the primary key in the store Args: {key_name}: the id of a single {model_name} Returns: a single {model_name} document """ self.store.connect() self.s3.connect() bs_entry = self.store.query_one( criteria={self.store.key: key}, properties=[f"{str(path_type.name)}.task_id"], ) bs_task = bs_entry.get(str(path_type.name)).get("task_id", None) if bs_task is None: raise HTTPException( status_code=404, detail= f"Band structure with {self.store.key} = {key} not found", ) item = self.s3.query_one({"task_id": bs_task}, properties=fields["properties"]) response = item return response
def get_menus(categories: List[int] = Query(None), kinds: List[int] = Query(None), prices: List[int] = Query(None), db: Session = Depends(get_db)): if categories == None and kinds == None and prices == None: menus = crud.get_menus(db) return menus if not categories or not kinds or not prices: raise HTTPException(status_code=400) menus = crud.get_menus_by_recommendation(db, categories, kinds, prices) if menus is None: raise HTTPException(status_code=404) return menus
async def generate_api_key(scopes: List[str] = Query(...), user: User = Depends(get_current_user)): key = secrets.randbits(10) username = user["username"] database["users"][username]["api_keys"].append({ "key": key, "scopes": scopes }) return key
def get_ascendant( latitude: float = Query(..., ge=-90, le=90), date_params: DateParams = Depends() ): date = safe_date(JULIAN_CALENDAR, date_params) pos = ascendant(date.days_from_epoch(), latitude) return {"value": str(round(Sexagesimal(pos.value, 2)))}
async def get_token_payload_ws(token: str = Query(...)) -> Dict[str, Any]: if not token: return {"success": False, "payload": {}} try: decoded = jwt.decode( token, settings.ADMIN_TOKEN_SECRET_KEY, algorithms=["HS256"]) except jwt.InvalidTokenError as ex: return {"success": False, "payload": {}} else: return {"success": True, "payload": decoded}
async def recommend_projects_without_usertoken( limit: Optional[int] = Query(None), offset: Optional[int] = Query(None)): endpoint = 'http://projectapi:8000/projectapi/project/all' sorted_by_like_resp = requests.get( f'{endpoint}?sort_by=LIKE&reverse=false') if sorted_by_like_resp.status_code != 200: raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR) sorted_by_like: List[int] = sorted_by_like_resp.json() sorted_by_date_resp = requests.get( f'{endpoint}?sort_by=DATETIME&reverse=false') if sorted_by_date_resp.status_code != 200: raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR) sorted_by_date: List[int] = sorted_by_date_resp.json() result: List[int] = [] if len(sorted_by_date) != len(sorted_by_like): raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR) len_sorted_by_date = len(sorted_by_date) while len(result) < len_sorted_by_date: c = random.choice(['like', 'like', 'date']) # like:date = 2:1 print(c) if len(sorted_by_like) > 0 and c == 'like': p = sorted_by_like.pop() if p not in result: result.append(p) elif len(sorted_by_date) > 0 and c == 'date': p = sorted_by_date.pop() if p not in result: result.append(p) else: continue if offset is None: return result[:limit] if limit is None: return result[offset:] return result[offset:offset + limit]
async def api_get_match( match_id: int = Query(..., alias="id", ge=1, le=64), ): """Return information of a given multiplayer match.""" # TODO: eventually, this should contain recent score info. if not (match := app.state.sessions.matches[match_id]): return ORJSONResponse( {"status": "Match not found."}, status_code=status.HTTP_404_NOT_FOUND, )
def get_editor(editor_pk: int = Query(None), db: Session = Depends(get_db)): if editor_pk == None: # editor_pk가 없다면 전체 editor 가져옴 editors = crud.get_editors(db) return editors editor = crud.get_editor(db, editor_pk) if editor is None: raise HTTPException(status_code=404) return editor
def geo_facilities_api( only_approved: bool = Query(True, description="Only show approved stations"), session: Session = Depends(get_database_session), ) -> FacilityGeo: stations = get_stations(session, only_approved=only_approved) if not stations: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No stations found") stations_geo = stations_to_geojson(stations) return stations_geo