async def config_validator( data: fastapi.UploadFile = fastapi.File(...), # noqa: B008 ) -> responses.PlainTextResponse: # pragma: no cover try: bytes_or_str = await data.read() if isinstance(bytes_or_str, str): content_bytes = bytes_or_str.encode() else: content_bytes = bytes_or_str rules.get_mergify_config( context.MergifyConfigFile({ "path": data.filename, "type": "file", "content": base64.b64encode(content_bytes).decode(), "decoded_content": content_bytes, "sha": github_types.SHAType( hashlib.sha1(content_bytes).hexdigest() # nosec ), })) except Exception as e: status = 400 message = str(e) else: status = 200 message = "The configuration is valid" return responses.PlainTextResponse(message, status_code=status)
async def upload_file(file: fa.UploadFile = fa.File(...), size: int = 100): """ Enpoint uploads an image. """ fl_img, fl_id = await get_new_dir() try: with open(fl_img, "wb") as buffer: shutil.copyfileobj(file.file, buffer) except Exception: err_msg = f"Cannot write image file: {fl_img}" logger.error(err_msg) raise fa.HTTPException(status_code=500, detail=err_msg) finally: file.file.close() status.uploaded_count += 1 task = BackgroundTask(queue_image, fl_id, size) message = {"image_id": str(fl_id)} metadata = { "filename": file.filename, "created": time.time(), "state": "Queued for processing" } fl_meta = os.path.join(conf.dst_dir, fl_id, conf.dst_meta) write_meta(fl_meta, metadata) return JSONResponse(message, background=task)
async def config_validator( data: fastapi.UploadFile = fastapi.File(...), ): # pragma: no cover try: rules.UserConfigurationSchema(await data.read()) except Exception as e: status = 400 message = str(e) else: status = 200 message = "The configuration is valid" return responses.PlainTextResponse(message, status_code=status)
async def scan(image: fastapi.UploadFile = fastapi.File(...)): """Scan a document.""" with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, os.path.basename(image.filename)) + ".png" # TODO: This is slow! We only need to convert to PNG because the qr # scanner does not execute correctly for JPEG... Image.open(io.BytesIO(await image.read())).save(path) try: result = scanner.main(path, debug=False) except UnidentifiedImageError as e: msg = "Unable to open image file: " + str(e) raise fastapi.HTTPException(HTTP_400_BAD_REQUEST, msg) from e except QRNotFound as e: msg = "Did not find QR code" raise fastapi.HTTPException(HTTP_400_BAD_REQUEST, msg) from e return {"checked_boxes": result}
async def upload(request: fast.Request, file: fast.UploadFile = fast.File(...), user: mdl.User = fast.Depends( api_users.get_current_active_user)): if not file.filename.endswith(VALID_EXTENSIONS): raise fast.HTTPException(status_code=400, detail='File extension not allowed.') dest = pathlib.Path('/'.join( (RESULTS_DIR, pathlib.Path(file.filename).name))) dest.parent.mkdir(parents=True, exist_ok=True) async with aiofiles.open(dest, 'wb') as buffer: await file.seek(0) contents = await file.read() await buffer.write(contents) return f'{HOST}:{PORT}/results/{dest.name}'
def upload_layer( ls: dependencies.LoginSession = f.Depends( dependencies.dependency_login_session), file: f.UploadFile = f.File(..., description="The file to be uploaded."), generate_entries: bool = f.Query( True, description= "Automatically generate entries (song, album, people) for the " "uploaded file.")): """ Upload a new track to the database, and start a task to process the uploaded track. **If `generate_entries` is selected, ensure the song has something in the Artist and Album Artist fields, or the generation will behave strangely due to a bug.** """ # file.file can't be directly pickled, transfer it to a bytesio object stream = io.BytesIO() while data := file.file.read(8192): stream.write(data)
def create_general_meme(image: _fastapi.UploadFile = _fastapi.File(...)): file_path = _services.upload_image("memes", image) if file_path is None: return _fastapi.HTTPException(status_code=409, detail="incorrect file type") return _responses.FileResponse(file_path)
def post_programmer_meme(image: _fastapi.UploadFile = _fastapi.File(...)): file_name = _services.upload_image("ProgrammerHumor", image) if file_name is None: return _fastapi.HTTPException(status_code=409, detail="incorrect file type") return _responses.FileResponse(file_name)