DependsOnTrans, Router, ) from .common import ( parse_serialization_params, SerializationKeysQueryParam, SerializationViewQueryParam, ) log = logging.getLogger(__name__) router = Router(tags=['configuration']) EncodedIdPathParam: EncodedDatabaseIdField = Path( ..., title='Encoded id', description='Encoded id to be decoded', ) @router.cbv class FastAPIConfiguration: configuration_manager: ConfigurationManager = depends(ConfigurationManager) @router.get( '/api/whoami', summary="Return information about the current authenticated user", response_description="Information about the current authenticated user" ) def whoami( self,
async def delete_installation(installation_id: int = Path(..., gt=0), _=Security(get_current_access, scopes=["admin"])): """ Based on a installation_id, deletes the specified installation """ return await crud.delete_entry(installations, installation_id)
def get_language(lang_id: int = Path(..., ge=1), db: Session = Depends(get_db)): if lang := lang_utils.get_language(db, lang_id): return lang
def get_path_param_gt(item_id: float = Path(..., gt=3)): return item_id
def get_path_param_le(item_id: float = Path(..., le=3)): return item_id
def get_path_param_le_ge_int(item_id: int = Path(..., le=3, ge=1)): return item_id
def get_path_param_required_id(item_id: str = Path(...)): return item_id
contact=settings.CONTACT, openapi_tags=settings.TAGS, redoc_url="/", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) configure_logging(level=logging.INFO) PATH_DATASET = Path( settings.SCOPE_DATASET, description="Data source or collection name", example=settings.SCOPE_DATASET, ) QUERY_PREFIX = Query(None, min_length=1, description="Search prefix") @app.on_event("startup") async def startup_event(): get_index() db.session.close() def get_dataset(name: str) -> Dataset: dataset = Dataset.get(name) if dataset is None or dataset not in get_datasets(): raise HTTPException(status_code=404, detail="No such dataset.")
async def get_article_detail( db: Session = Depends(get_db), article_id: int = Path(..., title='The ID of the article to get details')): details = article_crud.get_aritles_by_id(db, article_id) return {'code': 1001, "msg": '完事', "data": details}
def show_pet_by_id(pet_id: str = Path(..., alias='petId')) -> Union[Pets, Error]: """ Info for a specific pet """ pass
async def user_data(id: int = Path(..., gt=0), ): data = await ws_manager.send_user_msg(id, {"msg": "asdasdasdasd"}) return data
async def read_note(id: int = Path(..., gt=0)): note = await notes_repository.get(id) if not note: raise HTTPException(status_code=404, detail="Note not found") return note
async def delete_site(site_id: int = Path(..., gt=0), _=Security(get_current_user, scopes=["admin"])): """ Based on a site_id, deletes the specified site """ return await crud.delete_entry(sites, site_id)
async def get_site(site_id: int = Path(..., gt=0)): """ Based on a site_id, retrieves information about the specified site """ return await crud.get_entry(sites, site_id)
def get_path_param_ge_int(item_id: int = Path(..., ge=3)): return item_id
async def read_summary(id: int = Path(..., gt=0)) -> SummarySchema: summary = await crud.get(id) if not summary: raise HTTPException(status_code=404, detail="Summary not found") return summary
def get_path_param_lt_gt_int(item_id: int = Path(..., lt=3, gt=1)): return item_id
async def get_words(*, projectName: str = Path(...), sortDict: Optional[str] = '{}', fullMatch:Optional[bool] = False,searchItem: Optional[str] = None, searchItemID: Optional[str] = None,dateRange: Optional[List[str]] = Query(['', '']), currentPage: int = 1, pageSize: int = 10, operatorFilter: Optional[List[str]] = Query(['']), wordLengthFilter: Optional[List[str]] = Query([''])): """ 获取用户词列表 """ projectId = await findProjectIdFromProjectName(dbPrefix, 'Project', queryDict={'projectName': projectName}, showDict={'_id': 1}) if not projectId: raise HTTPException(status_code=503, detail='projectNotExist') sortDict = json.loads(sortDict) # 配置 queryDict 和 showDict ,依据 目的的不同 queryDict = {} shownDict = {} queryDict['$and'] = [] if wordLengthFilter != ['']: wordLengthFilter = unquote(wordLengthFilter[0], 'utf-8').split(',') lengthDict = { '1':[0,2], '2':[2,4], '3':[4,8], '4':[8,1000], } # 因为可能有多段数据需要比较,所以先 构造比较的表达式, tempCampare= [] for ele in wordLengthFilter: tempCampare.append({'length':{'$gte':lengthDict[ele][0],'$lt':lengthDict[ele][1]}}) queryDict['$and'].append({'$or':tempCampare}) if operatorFilter != ['']: # 存在 operatorFilter 查询 operatorFilter = unquote(operatorFilter[0], 'utf-8').split(',') queryDict['operator'] = {'$in': operatorFilter} if dateRange != ['', '']: dateRange = unquote(dateRange[0], 'utf-8').split(',') if dateRange != ['', '']: queryDict['modifiedTime'] = { '$gte': dateRange[0], '$lt': dateRange[1]} if searchItemID: try: oid = ObjectId(searchItemID) except: raise HTTPException(status_code=503, detail='invalid ObjectID') else: queryDict['_id'] = oid else: if searchItem: # 有关键词查询 if fullMatch: queryDict['word']= searchItem # 精确匹配 else: queryDict['word'] = {'$regex': searchItem, '$options': 'i'} # 查询包含,且不区分大小写 #8 构造 排序 表达式,如果存在排序的话 sortMap= {'desc': -1, 'asc': 1} if sortDict != {}: # 前端有 排序信息发过来,检查是否有效 # 装换 sortDict 为 字典 for ele in list(sortDict.keys()): if sortDict[ele] == 'normal': sortDict.pop(ele) #print('sortDict',sortDict) if sortDict != {}: # 非空 sortDicttemp = [(ele,sortMap[sortDict[ele]]) for ele in sortDict] sortDict = sortDicttemp else: sortDict = [] if not queryDict['$and']: del queryDict['$and'] #print('ccc',queryDict,sortDict) result = await fetchDictItems(dbPrefix+'-'+projectId, 'UserDict', xfilter=queryDict, xshown=shownDict, xsort=sortDict, currentpage=currentPage, pagesize=pageSize) return (result)
def get_path_param_id(item_id: str = Path(None)): return item_id
async def get_words_es(*, projectName: str = Path(...),sortDict: Optional[str] = '{}',highlight: Optional[List[str]] = Query(['']), fullMatch:Optional[bool] = False,showReturn: Optional[List[str]] = Query(['']), searchItem: Optional[str] = None, searchItemID: Optional[str] = None,dateRange: Optional[List[str]] = Query(['', '']), currentPage: int = 1, pageSize: int = 10, operatorFilter: Optional[List[str]] = Query(['']), wordLengthFilter: Optional[List[str]] = Query([''])): """ 获取用户词列表 ES 版本 """ projectId = await findProjectIdFromProjectName(dbPrefix, 'Project', queryDict={'projectName': projectName}, showDict={'_id': 1}) if not projectId: raise HTTPException(status_code=503, detail='projectNotExist') # 页码起始 start = 0 end = 0 # 带搜索的 es索引 (等价于 mongo中的 数据库) _index = f'KWM-{projectId}.UserDict'.lower() #print('_index', _index) s = Search() if operatorFilter != ['']: # 存在 categoryFilter 查询 operatorFilter = unquote(operatorFilter[0], 'utf-8').split(',') #queryDict['operator'] = {'$in': operatorFilter} operatorFilter = '\"' + '\" \"'.join(operatorFilter) + '\"' #print('ccc',operatorFilter) q = Q("query_string", query=operatorFilter, fields=['operator']) s = s.query(q) if dateRange != ['', '']: dateRange = unquote(dateRange[0], 'utf-8').split(',') #print('dateRange',dateRange) if dateRange != ['', '']: #s = s.query('range',**{'timestamp': {'gte': dateRange[0], 'lt': dateRange[1]}}) # 这种也可以,为了统一Q,使用下面的表达式 r = Q('range',**{'modifiedTime': {'gte': dateRange[0],'lt': dateRange[1]}}) s = s.query(r) if searchItem: # single不走 es,所以,此处只有 searchItem 。不会有 searchItemID # 有关键词查询 #queryDict['word'] = {'$regex': searchItem, '$options': 'i'} # 查询包含,且不区分大小写 q = Q("multi_match", query=f"{searchItem.strip()}", fields=['word']) s = s.query(q) # length if wordLengthFilter != ['']: wordLengthFilter = unquote(wordLengthFilter[0], 'utf-8').split(',') #print('wordLengthFilter',wordLengthFilter) # 存在 lengthFilter 查询 #长度对应字典 lengthDict = { '1':[0,2], '2':[2,4], '3':[4,8], '4':[8,1000], } ss = '' for ele in wordLengthFilter: ss = ss + '|' + f'Q("range",**{{"length": {{"gte": {lengthDict[ele][0]},"lt": {lengthDict[ele][1]}}}}})' #print(ss[1:]) s = s.query(eval(ss[1:])) # 排序设定: 构造 排序 表达式,如果存在排序的话 sortMap = {'desc': -1, 'asc': 1} #print('sortDict',sortDict) if sortDict != '{}': # 前端有 排序信息发过来,检查是否有效 # 装换 sortDict 为 字典 sortDict = json.loads(sortDict) for ele in list(sortDict.keys()): if sortDict[ele] == 'normal': sortDict.pop(ele) #print('sortDict',sortDict) if sortDict != {}: # 非空 sortDicttemp = [(ele,sortMap[sortDict[ele]]) for ele in sortDict] sortDict = sortDicttemp else: sortDict = [] #print('sortDict',sortDict) # 构造 排序命令 sorts = [] for ss in sortDict: if ss[1] == 1: # asc sorts.append(ss[0]) else: # desc sorts.append('-'+ss[0]) #print('sorts', sorts) s = s.sort(*sorts) else: #s = s.sort('_id') pass # 返回哪些字段 if showReturn != ['']: showReturn = unquote(showReturn[0], 'utf-8').split(',') s = s.source(includes=showReturn) else: s = s.source(includes=[]) # 高亮哪些字段 if highlight != ['']: highlight = unquote(highlight[0], 'utf-8').split(',') #print(highlight) s = s.highlight_options(order='score') s = s.highlight_options(pre_tags="<strong>") s = s.highlight_options(post_tags = "</strong>") for ele in highlight: # 每一个逐个添加高亮 s = s.highlight(ele) # 返回页码 if currentPage == 0 and pageSize == 0: # 返回所有数据 s = s[0:10000] # 这里写死了10000, 如果超过,会报错。最好的解决方法是 用 scan,但是 scan 不会排序。后面再解决 else: start = (currentPage - 1) * pageSize end = start + pageSize s = s[start:end] # 执行 try: response = await esRun(s.to_dict(), _index) #s.execute(ignore_cache=True) except Exception as e: print(e) return ({'count': 0,'content':[]}) else: totalCount = response.hits.total.value temp = response.to_dict()['hits']['hits'] result = [] for item in temp: tt = {'_id': {'$oid':item['_id']}} tt.update(item['_source']) if item.get('highlight'): tt.update({'highlight':item['highlight']}) if start >=0 and end > 0: tt.update({'id': start+1}) result.append(tt) start = start +1 #print(result) return ({'count': totalCount, 'content': result})
def get_path_param_min_max_length(item_id: str = Path(..., max_length=3, min_length=2)): return item_id
from typing import List from fastapi import (Depends, Path) from fastapi.routing import APIRouter from fastapi_utils.cbv import cbv from galaxy.managers.licenses import (LicenseMetadataModel, LicensesManager) from galaxy.web import expose_api_anonymous_and_sessionless from galaxy.webapps.base.controller import BaseAPIController router = APIRouter(tags=['licenses']) LicenseIdPath: str = Path( ..., # Mark this Path parameter as required title="SPDX license short ID", description= "The [SPDX license short identifier](https://spdx.github.io/spdx-spec/appendix-I-SPDX-license-list/)", example="Apache-2.0") def get_licenses_manager() -> LicensesManager: return LicensesManager() @cbv(router) class FastAPILicenses: licenses_manager: LicensesManager = Depends(get_licenses_manager) @router.get('/api/licenses', summary="Lists all available SPDX licenses", response_model=List[LicenseMetadataModel],
def get_path_param_lt0(item_id: float = Path(..., lt=0)): return item_id
def get_stats_for_uid(uid: str = Path(..., description="The ID of the user")): result = { "uid": uid, "stats": uo.getUser(uid)["stats"], } return result
async def get_installation(installation_id: int = Path(..., gt=0)): """ Based on a installation_id, retrieves information about the specified installation """ return await crud.get_entry(installations, installation_id)
def get_path_param_lt_gt(item_id: float = Path(..., lt=3, gt=1)): return item_id
async def read_manager(id: int = Path(..., gt=0), ): manager = await backend.crud.get(id) if not manager: raise HTTPException(status_code=404, detail="Manager not found") return manager
def get_path_param_le_ge(item_id: float = Path(..., le=3, ge=1)): return item_id
def update_language(lang_id: int = Path(..., ge=1), language: schemas.LanguageBase = Body(...), db: Session = Depends(get_db)): if upd_lang := lang_utils.update_language(db, lang_id, language): return upd_lang
def verify(db: Session = Depends(get_db), answer: str = Path(...), id: int = Path(...)): return crud.questions.verify(db, id, answer)