def delete_book_by_id(library_id: str = Path(None, min_length=5, max_length=5)): try: deleted_library_id, deleted_count = mongo_db.delete(library_id) except: raise HTTPException(status_code=500, detail="Something went wrong !!") if deleted_count == 0: raise HTTPException( status_code=404, detail= f"library Id: {deleted_library_id} is not Delete" #การลบรหัสที่ผิด ให้เอารหัสมาใหม่ ) return JSONResponse( content={ "status": "ok", "data": { "library_id": deleted_library_id, "deleted_count": deleted_count, }, }, status_code=200, )
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 delete_pet(id: int = Path(..., ge=1), db: Session = Depends(get_db)): return pets.delete_pet(db=db, id=id)
async def hidden_path(hidden_path: str = Path(..., include_in_schema=False)): return {"hidden_path": hidden_path}
async def get_user(id: int = Path(..., ge=1)): return {"id": id}
async def get_user_token_change_history( response: Response, username: str = Path( ..., title="Username", example="someuser", min_length=1, max_length=64, regex=USERNAME_REGEX, ), cursor: Optional[str] = Query( None, title="Cursor", description="Pagination cursor", example="1614985055_4234", regex=CURSOR_REGEX, ), limit: Optional[int] = Query( None, title="Row limit", description="Maximum number of entries to return", example=500, ge=1, ), since: Optional[datetime] = Query( None, title="Not before", description="Only show entries at or after this time", example="2021-03-05T14:59:52Z", ), until: Optional[datetime] = Query( None, title="Not after", description="Only show entries before or at this time", example="2021-03-05T14:59:52Z", ), key: Optional[str] = Query( None, title="Token", description="Only show changes for this token", example="dDQg_NTNS51GxeEteqnkag", min_length=22, max_length=22, ), token_type: Optional[TokenType] = Query( None, title="Token type", description="Only show tokens of this type", example="user", ), ip_address: Optional[str] = Query( None, title="IP or CIDR", description="Only show changes from this IP or CIDR block", example="198.51.100.0/24", ), auth_data: TokenData = Depends(authenticate_read), context: RequestContext = Depends(context_dependency), ) -> List[Dict[str, Any]]: token_service = context.factory.create_token_service() results = await token_service.get_change_history( auth_data, cursor=cursor, username=username, limit=limit, since=since, until=until, key=key, token_type=token_type, ip_or_cidr=ip_address, ) if limit: response.headers["Link"] = results.link_header(context.request.url) response.headers["X-Total-Count"] = str(results.count) return [r.reduced_dict() for r in results.entries]
def path_convertor(param: str = Path(...)): return {"path": param}
async def read_note(id: int = Path(..., gt=0),): fnote = await crud.get(id) if not fnote: raise HTTPException(status_code=404, detail="Feed not found") return fnote
def tile( z: int = Path(..., ge=0, le=30, description="Mercator tiles's zoom level"), x: int = Path(..., description="Mercator tiles's column"), y: int = Path(..., description="Mercator tiles's row"), tms: TileMatrixSet = Depends(self.tms_dependency), scale: int = Query( 1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." ), format: ImageType = Query( None, description="Output image type. Default is auto." ), src_path=Depends(self.path_dependency), layer_params=Depends(self.layer_dependency), dataset_params=Depends(self.dataset_dependency), render_params=Depends(self.render_dependency), kwargs: Dict = Depends(self.additional_dependency), ): """Create map tile from a dataset.""" timings = [] headers: Dict[str, str] = {} tilesize = scale * 256 with utils.Timer() as t: with rasterio.Env(**self.gdal_config): with self.reader( src_path.url, tms=tms, **self.reader_options ) as src_dst: data = src_dst.tile( x, y, z, tilesize=tilesize, **layer_params.kwargs, **dataset_params.kwargs, **kwargs, ) colormap = render_params.colormap or getattr( src_dst, "colormap", None ) timings.append(("dataread", round(t.elapsed * 1000, 2))) if not format: format = ImageType.jpeg if data.mask.all() else ImageType.png with utils.Timer() as t: image = data.post_process( in_range=render_params.rescale_range, color_formula=render_params.color_formula, ) timings.append(("postprocess", round(t.elapsed * 1000, 2))) with utils.Timer() as t: content = image.render( add_mask=render_params.return_mask, img_format=format.driver, colormap=colormap, **format.profile, ) timings.append(("format", round(t.elapsed * 1000, 2))) headers["Server-Timing"] = ", ".join( [f"{name};dur={time}" for (name, time) in timings] ) return Response(content, media_type=format.mimetype, headers=headers)
async def update_users_info(data: UserUpdateSchema, id: UUID = Path(..., description="User id for update")): return await update_user(id, data)
def get_model(resource: str = Path(...)): model = app.models.get(resource) return model
def update_plant( new_plant_data: schemas.PlantUpdate, db: Session = Depends(get_db), plant_id: int = Path(None, title="The ID for the plant to update", ge=1), ): return crud.update_plant(db, plant_id, new_plant_data)
def water_plant( plant_id: int = Path(None, title="The ID of the plant to kill", ge=1), db: Session = Depends(get_db), ): plant = _get_plant(db, plant_id) return crud.kill_plant(db, plant)
def get_plant( plant_id: int = Path(None, title="The ID of the plant to get", ge=1), db: Session = Depends(get_db), ): return _get_plant(db, plant_id)
async def get_specific_item(item_id: int = Path(..., gt=0)): if (item := Item.query.get(item_id)): return item
def single_post(post_id: int = Path(...)): post = get_or_404(Post, pk=post_id) payload = schema.PostJsonApi(data=post) return payload
async def api_get_analysis_module_type(name: str = Path(..., description="The name of the analysis mode type to get.")): amt = await app.state.system.get_analysis_module_type(name) if amt is None: raise HTTPException(status_code=404) return amt.to_model()
def tile( z: int = Path(..., ge=0, le=30, description="Mercator tiles's zoom level"), x: int = Path(..., description="Mercator tiles's column"), y: int = Path(..., description="Mercator tiles's row"), tms: TileMatrixSet = Depends(self.tms_dependency), scale: int = Query( 1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." ), format: ImageType = Query( None, description="Output image type. Default is auto." ), src_path=Depends(self.path_dependency), layer_params=Depends(self.layer_dependency), dataset_params=Depends(self.dataset_dependency), render_params=Depends(self.render_dependency), pixel_selection: PixelSelectionMethod = Query( PixelSelectionMethod.first, description="Pixel selection method." ), kwargs: Dict = Depends(self.additional_dependency), ): """Create map tile from a COG.""" timings = [] headers: Dict[str, str] = {} tilesize = scale * 256 threads = int(os.getenv("MOSAIC_CONCURRENCY", MAX_THREADS)) with utils.Timer() as t: with rasterio.Env(**self.gdal_config): with self.reader( src_path.url, reader=self.dataset_reader, reader_options=self.reader_options, ) as src_dst: mosaic_read = t.from_start timings.append(("mosaicread", round(mosaic_read * 1000, 2))) data, _ = src_dst.tile( x, y, z, pixel_selection=pixel_selection.method(), threads=threads, tilesize=tilesize, **layer_params.kwargs, **dataset_params.kwargs, **kwargs, ) timings.append(("dataread", round((t.elapsed - mosaic_read) * 1000, 2))) if not format: format = ImageType.jpeg if data.mask.all() else ImageType.png with utils.Timer() as t: image = data.post_process( in_range=render_params.rescale_range, color_formula=render_params.color_formula, ) timings.append(("postprocess", round(t.elapsed * 1000, 2))) with utils.Timer() as t: content = image.render( add_mask=render_params.return_mask, img_format=format.driver, colormap=render_params.colormap, **format.profile, ) timings.append(("format", round(t.elapsed * 1000, 2))) headers["Server-Timing"] = ", ".join( [f"{name};dur={time}" for (name, time) in timings] ) headers["X-Assets"] = ",".join(data.assets) return Response(content, media_type=format.mimetype, headers=headers)
def float_convertor(param: float = Path(...)): return {"float": param}
async def create_equipment(*, hospital_name: str = Path(..., description="Hospital Name"), product_name: str = Path(..., description="Product name. 'Any' creates a item without product assigned"), equipment: Optional[schemas.Equipment] = Body(..., descrption="Equipment description"), authorization: str = Header(None, alias='Authorization', convert_underscores=True)): headers = dict(Authorization=authorization) async with httpx.AsyncClient(headers=headers) as client: hospitals = await lookup(client, Resources.PROJECT.value, dict(name=hospital_name)) if not hospitals: return JSONResponse( status_code=HTTP_404_NOT_FOUND, content={"message": f"Hospital {hospital_name} not found"}) scopes = { "scopes": { "projects": [f'+{h["id"]}' for h in hospitals], } } product_id = None if product_name != 'any': products = await lookup(client, Resources.PRODUCT.value, dict(identifiers=dict(name=name_to_identifier(product_name)))) if len(products) > 1: return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": f"Product {product_name} is ambiguous"}) elif len(products) == 1: product_id = products.pop()['id'] else: return JSONResponse( status_code=HTTP_404_NOT_FOUND, content={"message": f"Product {product_name} not found"}) if equipment.name and (await lookup(client, Resources.THNG.value, dict(name=equipment.name))): return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": f"Equipment name {equipment.name} exists"}) if equipment.identifiers and ( await lookup(client, Resources.THNG.value, dict(name=equipment.identifiers))): return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": f"Equipment identifiers {equipment.identifiers} exists"}) if equipment.location and not ( await lookup(client, Resources.PLACE.value, dict(name=equipment.location))): return JSONResponse(status_code=HTTP_404_NOT_FOUND, content={"message": f"Location {equipment.location} does not exist"}) thng_document = ResourceDocument( name=equipment.name, identifiers=equipment.identifiers, tags=['free'], description=equipment.description).dict() thng_document['product'] = product_id thng = await new_resource(client, Resources.THNG, hospitals[0]['id'], thng_document) await new_property(client, thng['id'], hospitals[0]['id'], 'inUse', False); redirection = await create_redirection( client, thng['id'], 'thng', f'{HOSPITAL_HOST}/equipments/{thng["id"]}') update_document = dict(customFields={}) for k in redirection: update_document['customFields'][k] = redirection[k] await update_resource(client, Resources.THNG, thng['id'], update_document) response_message = {'name': thng['name'], 'createdAt': thng['createdAt']} if 'description' in thng: response_message['description'] = thng['description'] if 'location' in thng: response_message['location'] = thng['location'] return JSONResponse(status_code=HTTP_201_CREATED, content=response_message, headers=dict(Location=f'{EVT_HOST}/{Resources.THNG.value}/{thng["id"]}', ContentType='application/json'))
def int_convertor(param: int = Path(...)): return {"int": param}
async def create_location(*, hospital_name: str = Path(..., description="Hospital Name"), dep_or_ward: schemas.DepartmentOrWard = Body(..., descrption="Dep/Ward"), authorization: str = Header(None, alias='Authorization', convert_underscores=True)): headers = dict(Authorization=authorization) async with httpx.AsyncClient(headers=headers) as client: hospitals = await lookup(client, Resources.PROJECT.value, dict(name=hospital_name)) if not hospitals: return JSONResponse( status_code=HTTP_404_NOT_FOUND, content={"message": f"Hospital {hospital_name} not found"}) if len(hospitals) != 1: return JSONResponse( status_code=HTTP_400_BAD_REQUEST, content={"message": f"A location can only belong to one hospital, not {len(hospitals)}"}) hospital = hospitals.pop() scopes = { "scopes": { "projects": [f'+{hospital["id"]}'], } } locations = await lookup(client, Resources.PLACE.value, dict(identifiers=dict(name=name_to_identifier(dep_or_ward.name)))) if len(locations) > 1: return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": f"Location with the name {dep_or_ward.name} already exists"}) location_document = { "identifiers": {}, "position": { "coordinates": hospital['customFields']['coordinates'] , "type": "Point" }, 'tags': hospital['tags'], "customFields": {} } response_dep_or_ward = {} for k in dep_or_ward.dict(): if dep_or_ward.dict()[k] is None: continue if k == 'name': location_document[k] = dep_or_ward.dict()[k] location_document['identifiers'][k] = name_to_identifier(dep_or_ward.dict()[k]) elif k == 'description': location_document[k] = dep_or_ward.dict()[k] else: location_document['customFields'][k] = dep_or_ward.dict()[k] location_document['identifiers'][k] = name_to_identifier(dep_or_ward.dict()[k]) response_dep_or_ward[k] = dep_or_ward.dict()[k] location = await new_resource(client, Resources.PLACE, hospital['id'], location_document) await update_resource(client, Resources.PLACE, location['id'], scopes) return JSONResponse(status_code=HTTP_201_CREATED, content=response_dep_or_ward, headers=dict(Location=f'{EVT_HOST}/{Resources.PLACE.value}/{location["id"]}', ContentType='application/json'))
async def delete_asset_with_idx(uuid: UUID = Path(..., description="Asset UUID")): data.remove_asset(uuid) return {"msg": "success"}
async def read_file(*, page: str = Path(..., regex='\w+\.html$', description="COVID-19 related site")): # thngId: str = Query(default="", description="Thnd id")): return FileResponse(os.path.join('web', page))
async def get_item( item_id: int = Path(..., title="Item Identifier", gt=0, lt=1000) ): logging.info("getting item {}".format(item_id)) return {"item": item_id}
async def _(*, folder: str = Path(..., description="folder"), folder2: str = Path(..., description="folder"), page: str = Path(..., description="COVID-19 related site")): return FileResponse(os.path.join('web', folder, folder2, page))
def get_pet_owner(id: int = Path(..., ge=1), db: Session = Depends(get_db)): db_pet_owner = pets.get_pet_owner(db=db, id=id) if db_pet_owner is None: raise HTTPException(status_code=404, detail=f"Pet with id {id} not found") return db_pet_owner
async def create_product_category(*, hospital_name: str = Path(..., description="Hospital Name"), product_category: schemas.ProductCategory = Body(..., descrption="Adds a new hospital"), authorization: str = Header(None, alias='Authorization', convert_underscores=True)): headers = dict(Authorization=authorization, ContentType='application/json') async with httpx.AsyncClient(headers=headers) as client: hospitals = await lookup(client, Resources.PROJECT.value, dict(name=hospital_name)) if not hospitals: return JSONResponse( status_code=HTTP_404_NOT_FOUND, content={"message": f"Hospital {hospital_name} not found"}) scopes = { "scopes": { "projects": [f'+{h["id"]}' for h in hospitals], } } products = await lookup(client, Resources.PRODUCT.value, dict(identifiers=dict(name=name_to_identifier(product_category.name)))) if len(products) > 1: return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": f"Product {product_category.name} is ambiguous"}) elif len(products) == 1: product = await update_resource(client, Resources.PRODUCT, products[0]['id'], scopes) else: product_document = ResourceDocument( name=product_category.name, identifiers=dict( category=name_to_identifier(product_category.product_category), specification=name_to_identifier(product_category.specification), name=name_to_identifier(product_category.name)), description=product_category.specification, tags=[product_category.specification]).dict() product_document['brand'] = product_category.brand product_document['categories'] = [product_category.product_category, product_category.specification] product = await new_resource(client, Resources.PRODUCT, hospitals[0]['id'], product_document) # await update_resource(client, Resources.PRODUCT, product['id'], scopes) redirection = await create_redirection( client, product['id'], 'product', f'{HOSPITAL_HOST}/products/{product["id"]}') update_document = dict(customFields=dict( category=product_category.product_category, specification=product_category.specification)) for k in redirection: update_document['customFields'][k] = redirection[k] await update_resource(client, Resources.PRODUCT, product['id'], update_document) return JSONResponse(status_code=HTTP_201_CREATED, content={'brand': product['brand'], 'name': product['name'], 'createdAt': product['createdAt'], 'product_category': product['categories'][0], 'specification': product['description']}, headers=dict(Location=f'{EVT_HOST}/{Resources.PRODUCT.value}/{product["id"]}', ContentType='application/json'))
def get_item(item_id: int = Path(None, description='The id of the item you want to view', gt = 0)): return inventory[item_id]
def delete_post(post_id: int = Path(...)): Post.objects.filter(id=post_id).delete() response = Response(status_code=status.HTTP_204_NO_CONTENT, ) return response