class Product(BaseModel): title: str = Form(...) description: Optional[str] = None link: Optional[str] = None image: Optional[str] = None buy: Optional[bool] = False
async def login(username: str = Form(...), password: str = Form(...)): return {"username": username}
async def root(username: str = Form(...), password: str = Form(...)): return username # pragma: nocover
async def get_photo_settings(photo_settings: str = Form(...)): return PhotoSettingsUpdate(**json.loads(photo_settings))
def startfast(request: Request, fdate=Form(...), fduration=Form(...)): new_fast = Fast.start_fast(fdate, fduration) response = RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER) return response
def log(username: str = Form(...),password: str = Form(...),db: Session = Depends(get_db)): return{"username": username, "pass": password}
def as_form(cls, url: str = Form(...), download_format: str = Form(...)): return cls(url=url, download_format=download_format)
async def put(memo_id, memo: str = Form(...)): return JSONResponse( content={"message": MemoHandleInteractor().update(memo_id, memo)})
async def upload_file( request: Request, response: Response, file: UploadFile=File(...), file_id: str = Form(" ") ): out_file_path = join(HOME_DIR, "content", "public", "users_files", "no_name") # , in_file.filename if not path.exists(out_file_path): makedirs(out_file_path, mode=0o777, exist_ok=False) out_file_path = join(out_file_path, file.filename) return_filename = join("content", "public", "users_files", "no_name", file.filename) try: async with aiofiles.open(out_file_path, 'wb') as out_file: content = await file.read() # async read await out_file.write(content) # async write return SaveFileResponse(filename=return_filename, file_id=file_id) except ValueError as e: print("ошибка в upload_file", e, [e], __file__) response.status_code = status.HTTP_422_UNPROCESSABLE_ENTITY return SaveFileResponse(filename="", success=False, file_id=file_id) # @public_router # @db_session # def get_question(request: Request, answer_email = Form(...)): # pass # @public_router.get("/competition") # @db_session # def get_public_pages(request: Request): # if (ent := m.Page.get(page_url="/competition")) or (ent := m.Page.get(page_url="competition")): # return public_templates.TemplateResponse(ent.page_path, { # "request": request, # "directions": [out_pd.Direction.from_pony_orm(i) for i in m.Direction.select()[:]]}) # raise HTTPException(request=request, **error_404_Page) # # # @public_router.get("/competition/{direction}") # @db_session # def get_public_pages(request: Request, direction: str): # if ent := m.Direction.get(name=direction): # return public_templates.TemplateResponse("competition/direction.html", { # "request": request, # "direction": out_pd.Direction.from_pony_orm(ent)}) # # raise HTTPException(request=request, **error_404_Page) # @public_router.get("/{file_path:path}") # @db_session # def get_public_pages(file_path: str, request: Request): # print('=-098765456789', file_path) # file_path = file_path.removeprefix("/") # ent = None # if m.Page.exists(page_url=file_path): # print('456') # ent = m.Page.get(page_url=file_path) # # elif m.Page.exists(page_url="/" + file_path): # print('4erter') # ent = m.Page.get(page_url="/" + file_path) # print(ent) # if ent: # return public_templates.TemplateResponse(ent.page_path, {"request": request}) # raise HTTPException(request=request, **error_404_Page)
async def pushdatapost(question: str = Form(...), answer: str = Form(...)): db.child('chatbot').child('data').push({"Question":question,"Answer":answer}) return {"message":"success"}
class MobileVerificationRequestSchema: email: EmailStr = Form(...) comment: str = Form(..., max_length=consts.COMMENT_LENGTH) url: ShortHttpUrl = Form(...) image: Optional[UploadFile] = File(None)
async def post_file(file: UploadFile = File(...), token: str = Form(...)): return { "file_size": len(file), "token": token, "file_type": file.content_type }
def login_form(userName=Form(None), userPwd=Form(None)): return {"data": {"name": userName, "passwd": userPwd}}
def get_product_form(id: Optional[str] = Form(None), name: str = Form(...), price: float = Form(...), stock: int = Form(...)): return schema.Product(id=id, name=name, price=price, stock=stock, image="")
def analyze_answers(UserIdentifier: str = Form(...)): """ Analyzes the answers given by the user, see that we are not parsing the Memory object, that's because on every questions the answers were validated by the endpoint defined below and added to the Endless Medical API session """ # We don't need to access collect since arriving here means # all answers have been added to the Endless Medical Session try: session_id = UserDocument.get_by_phone( UserIdentifier).endless_medical_token except AttributeError as err: capture_message(err) return {"actions": {"redirect": "task://fallback"}} # Just an inline function to clean the user def reset_session_id_token(): user = UserDocument.get_by_phone(UserIdentifier) user.endless_medical_token = None user.update() try: # Analyse data and get only the posible diseases outcomes: List[Dict[str, str]] = endless_medical_api.analyse( session_id)["Diseases"] logger.debug(outcomes) # Parsing the diseases, the API returns a confidence from 0.0 to 1.0 for every predicted disease # if COVID-19 has >= 50 % we recommend calling the doctor; else we check if any other diseases has at least # 50 % chance, if so, COVID-19 it's discarded but we recommend calling the doctor anyway # Check if COVID-19 passes threshold if check_outcomes(outcomes, outcomes_mapping.get("covid-19")): return { "actions": list( chain( [{ "say": "You should seek medical attention as soon as possible" }], screening_pre_results_warning, )) } # COVID-19 did not pass threshold, check now if any other outcome does if check_outcomes(outcomes): return { "actions": list( chain( [{ "say": "You probably do not have COVID-19, but, according to your symptoms, " "you should seek medical attention anyways " }], self_screening_lives_in_area, )) } # User is probably ok return { "actions": [ { "say": "Great news! You don not have anything to worry about 🥳\U0001f973" }, { "redirect": "task://menu-description" }, ] } except BaseHTTPError as err: capture_message(err) return { "actions": [ { "say": "Sorry, our super AI doctor had a problem analysing the results; please try again." }, { "redirect": "task://menu-description" }, ] } finally: reset_session_id_token()
def __init__(self, file: UploadFile = Form(...)): self.file = file
def self_screening_start(UserIdentifier: str = Form(...), Memory: str = Form(...)): """ Starts the screening process :param: UserIdentifier: Phone number from Twilio :param: Memory: JSON Stringified object from Twilio """ memory = json.loads(Memory) twilio = memory.pop("twilio") start_screening = twilio["collected_data"]["accepts-test"]["answers"][ "start-screening"]["answer"] user = UserDocument.get_by_phone(UserIdentifier) try: if start_screening == "No": return { "actions": [ { "say": "Ok no problem! Let's go back to the menu" }, { "redirect": "task://menu-description" }, ] } # Check if user is in db, otherwise we cannot continue if start_screening == "Yes" and not user: return { "actions": [ { "say": "Sorry, I cannot continue until you give me your name \U00012639" }, { "redirect": "task://can-have-name" }, ] } # Check if the user lives in a COVID-19 affected area lives_in_risky_area = novelcovid_api.lives_in_risky_zone(user.country) # Said yes but is not in risky area if start_screening == "Yes" and not lives_in_risky_area: return screening_not_in_danger # Said yes and IS in risky area, so we can mark the first question as "yes" if start_screening == "Yes" and lives_in_risky_area: accept_tos_and_store_session_id(UserIdentifier) return { "actions": [ { "say": "Your country already has cases of COVID-19, so we will skip that question; let's go " "with the rest " }, { "redirect": "task://self-screening-q-rest" }, ] } # Continue if user accepts if start_screening == "Yes": return { "actions": [ { "say": "Alright, let's start" }, { "redirect": "task://self-screening-lives-in-area" }, ] } return { "actions": [ { "say": "Cool! No problem, let's get back to the menu" }, { "redirect": "task://menu-description" }, ] } except faunadb.errors.BadRequest as err: capture_message(err) return {"actions": [{"redirect": "task://fallback"}]} except BaseHTTPError as err: capture_message(err) return {"actions": [{"redirect": "task://fallback"}]} except Exception as err: capture_message(err) return {"actions": [{"redirect": "task://fallback"}]}
def post_token(request_data: OAuth2PasswordRequestForm = Form(...)): data = request_data.parse() access_token = data.username + ":" + data.password return {"access_token": access_token}
def form_body(cls): cls.__signature__ = cls.__signature__.replace(parameters=[ arg.replace(default=Form(...)) for arg in cls.__signature__.parameters.values() ]) return cls
def upVersion(ipns: str = Form(...), title: str = Form(...), version: str = Form(...), build: str = Form(...), log: str = Form(...), apk: UploadFile = File(None)): try: ipfs = api.files.stat("/IPNSCACHE_%s" % ipns)['Hash'] except ipfshttpclient.exceptions.ErrorResponse: ipfs = None if ipfs is None: return 'no Version.' files = api.object.links(ipfs) dirhash = api.object.new("unixfs-dir") for fl in files['Links']: if fl['Name'] == conf['storageSubPath']: dirhash = fl if apk: with open("/tmp/tmp.apk", "wb") as f: f.write(apk.file.read()) package, version, code = get_android_info("/tmp/tmp.apk") apkname = "%s_%s_%s.apk" % (package, version, code) apkpath = os.path.join(conf['localStorage'], conf['storageSubPath']) if not os.path.isdir(apkpath): os.mkdir(apkpath) shutil.move("/tmp/tmp.apk", os.path.join(apkpath, apkname)) apkhash = api.add(os.path.join(apkpath, apkname), chunker='size-1048576', nocopy=True) update = getupdatejson(ipfs) newupdate = { "title": conf['projectName'], "data": [], } for item in update['data']: if not item['build'] == build: newupdate['data'].append(item) else: if apk: apk_file = os.path.join(conf['storageSubPath'], apkname) dirhash = api.object.patch.rm_link(dirhash['Hash'], item['apk_file'].split('/')[1]) dirhash = api.object.patch.add_link(dirhash['Hash'], apkname, apkhash['Hash']) else: apk_file = item['apk_file'] newupdate['data'].append({ "title": title, "version": version, "build": build, "log": log, "apk_file": apk_file, "datetime": int(time.time()) }) newupdate['last'] = build updatehash = api.add_json(newupdate) hash = uiTemplate hash = api.object.patch.add_link(hash, conf['storageSubPath'], dirhash['Hash']) hash = api.object.patch.add_link(hash['Hash'], 'update.json', updatehash) publish(ipns, hash['Hash']) api.files.rm("/IPNSCACHE_%s" % ipns, recursive=True) api.files.cp('/ipfs/%s' % hash['Hash'], "/IPNSCACHE_%s" % ipns) return {"newhash": hash['Hash']}
class SignUpForm(BaseModel): user_id: str = Form(..., **_c_user_id) email: EmailStr = Form(...) password: str = Form(..., **_c_password) password_confirm: str = Form(..., **_c_password)
async def add_photo(*, img_files : List[UploadFile] = File(...) , db : Session = Depends(get_db) , eventId : int = Form(2) , photoLabel : str = Form(...) , token : str = Form(...)): try: payload = jwt.decode(token , SECRET_KEY , algorithms=[ALGORITHM]) except: return "TOKEN EXPIRED" username : str = payload.get('sub') if username is None: raise credentials_exception else: for f in img_files: data = await f.read() b64data = base64.b64encode(data) newImage = { 'event_id' : eventId, 'label' : photoLabel, 'image' : b64data } newImageRow = schemas.AddPhoto(**newImage) db_img = models.Photos(**newImageRow.dict()) db.add(db_img) db.commit() db.refresh(db_img) return "photo saved in db"
def get_input(uname: str = Form(...)): return getuser(uname)
def post_form_param_set(items: set = Form(...)): return items
def editfast(id, request: Request, fdate=Form(...), fduration=Form(...)): Fast.get(id).edit_fast(fdate, fduration) response = RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER) return response
def post_form_param_tuple(items: tuple = Form(...)): return items
async def root(username: str = Form(...), f: UploadFile = File(...)): return username # pragma: nocover
def post_form_param_list(items: list = Form(...)): return items
class UserCreateForm(BaseModel): active: bool = Form(...) name: str = Form(...) email: str = Form(...) password: str = Form(...) avatar: str = Form(...)
async def post(memo_id: int, memo: str = Form(...)) -> str: return JSONResponse(content={"message": MemoHandler().save(memo_id, memo)})