Beispiel #1
0
async def fileStat1(request: Request,
                    fileList: List[bytes] = File(...),
                    fileName: List[UploadFile] = File(...)):
    return templates.TemplateResponse(
        'fileStat1.html', {
            'request': request,
            'fileSize': [len(file) for file in fileList],
            'fileName': [file.filename for file in fileName]
        })
Beispiel #2
0
async def fileStat2(request: Request,
                    file: bytes = File(...),
                    fileb: UploadFile = File(...),
                    note: str = Form(...)):
    return templates.TemplateResponse(
        'fileStat2.html', {
            'request': request,
            'fileSize': len(file),
            'fileName': fileb.filename,
            'note': fileb.content_type
        })
async def put_contract_file_upload(
        item_id: int,
        cpf: Optional[UploadFile] = File([]),
        proof_of_income: Optional[UploadFile] = File([]),
        property_images: Optional[List[UploadFile]] = File([]),
        db: Session = Depends(get_db),
):
    """
    Atualiza os arquivos enviados para um contrato por id
    """

    # contrato nao existe
    contract: Contract = db.query(Contract).get(item_id)
    if contract is None:
        raise HTTPException(HTTPStatus.NOT_FOUND)

    # atualizacao dos arquivos somente em alguns status
    if contract.status not in [
            ContractStatus.CREATED, ContractStatus.IMAGES_UPLOADED
    ]:
        raise HTTPException(HTTPStatus.BAD_REQUEST)

    ######
    # A maioria deste codigo estaria melhor posicionado em uma camada de servicos que tratasse o upload
    # para a cloud e atualizasse o contrato. Isto evitaria bastante duplicacao de codigo aqui.
    #
    # logica de negocios em views eh uma pessima pratica, mas isto eh soh um exemplo
    ######

    # aqui se faria o upload para algum storage como um AWS S3, etc... por simplicidade, vou apenas gerar uma URL
    # falsa que sera salva no banco de dados como se tivesse retornado do storage.
    if cpf:
        contract.cpf_url = f"http://dummy/{cpf.filename}"

    if proof_of_income:
        contract.proof_of_income_url = f"http://dummy/{proof_of_income.filename}"

    db.add(contract)

    # aqui optei por substituir as imagens anteriores, mas elas poderiam ser mantidas e mais endpoints
    # poderiam ser criados para um gerenciamento mais detelhado.
    if property_images:
        contract.property_images = []
        db.flush()
        for i in property_images:
            if i.filename:
                file_url = f"http://dummy/{i.filename}"
                image = PropertyImage(contract_id=contract.id, url=file_url)
                db.add(image)

    db.commit()
    db.refresh(contract)
    return contract
Beispiel #4
0
async def upload_photo(*,
                       db: Session = Depends(deps.get_db),
                       current_user: models.User = Depends(
                           deps.check_session_and_csrf),
                       id: int,
                       upload: UploadFile = File(...)):
    # exists recipe?
    recipe = _get(db, current_user.id, id)

    name = crud.recipe.handle_image(user_id=current_user.id,
                                    recipe_id=id,
                                    image=upload)
    if name is None:
        raise HTTPException(status_code=400, detail="Invalid image.")

    old_photo_name = recipe.photo
    updated_recipe = crud.recipe.update(db,
                                        db_obj=recipe,
                                        obj_in={"photo": name})

    if old_photo_name is not None and len(old_photo_name) > 0:
        # remove old photo and thumbnails
        old_images = glob(
            os.path.join(settings.upload_folder, f"{old_photo_name}*"))
        for file in old_images:
            print(f"Removing: {file}")
            os.remove(file)

    return updated_recipe
Beispiel #5
0
async def upload_image(upload_file: UploadFile = File(...),
                       private: bool = False,
                       clear_metadata: bool = False,
                       upload_action: SaveImageAction = Depends(),
                       authed_user: User = Depends(get_current_user)):
    return upload_action(
        upload_file, private, clear_metadata,
        UserGet(username=authed_user.username, id=authed_user.id))
Beispiel #6
0
async def upload_picture(
        user_id: str,
        file: UploadFile = File(..., media_type='application/octet-stream'),
        user: UserInfo = Depends(Authentication(auto_error=False)),
        registration_token: Optional[str] = Header(None, alias="x-token"),
):
    """Uploads a new picture for the passed user."""
    if user is not None:
        is_admin = 'admin' in user['roles']
        is_self = user.sub == user_id
        if not is_self or not is_admin:
            raise HTTPException(401)
        user_data = await async_user_collection.find_one({'_id': user_id})
    elif registration_token is not None:
        check_token(registration_token)
        user_data = await async_user_collection.find_one(
            {'registration_token': registration_token})
    else:
        raise HTTPException(401)
    if user_data is None:
        raise HTTPException(404)
    user = User.validate(user_data)
    if user.picture is None:
        user.picture = generate_token(48)
        updated_at = int(time.time())
        await async_user_collection.update_one(
            {'_id': user_id},
            {'$set': {
                'picture': user.picture,
                'updated_at': updated_at
            }})
        await async_client_user_cache_collection.update_many(
            {'user_id': user_data['_id']},
            {'$set': {
                'last_modified': updated_at
            }},
        )
    else:
        try:
            await async_user_picture_bucket.delete(user.picture)
        except gridfs.errors.NoFile:
            pass
    hash_ = hashlib.sha512()
    while True:
        chunk = await file.read(4 * 1024)
        if not chunk:
            break
        hash_.update(chunk)
    await file.seek(0)
    file.file.seek(0)
    await async_user_picture_bucket.upload_from_stream_with_id(
        user.picture,
        user.id,
        file.file,
        metadata={
            'content_type': file.content_type,
            'hash': hash_.digest()
        })
Beispiel #7
0
def predict_number(file: UploadFile = File(default=None)):
    # Get a drawn image
    input_img = preprocess_drawn_image(file, (28, 28))

    # Predict number
    # results = cnn_model.predict({'X': input_img})["classification"][0]
    results = image_cls_workflow.predict({'X': input_img})["classification"][0]

    return {"prediction": int(results)}
async def post_contract_file_upload(
        item_id: int,
        cpf: UploadFile = File(...),
        proof_of_income: Optional[UploadFile] = File([]),
        property_images: Optional[List[UploadFile]] = File([]),
        db: Session = Depends(get_db),
):
    """
    Envia arquivos para um contrato existente por id
    """

    # contrato nao existe
    contract: Contract = db.query(Contract).get(item_id)
    if contract is None:
        raise HTTPException(HTTPStatus.NOT_FOUND)

    # upload de arquivos soh eh permitido no status CREATED
    if contract.status != ContractStatus.CREATED:
        raise HTTPException(HTTPStatus.BAD_REQUEST)

    # aqui se faria o upload para algum storage como um AWS S3, etc... por simplicidade, vou apenas gerar uma URL
    # falsa que sera salva no banco de dados como se tivesse retornado do storage.
    contract.cpf_url = f"http://dummy/{cpf.filename}"

    # comprovacao de renda foi enviada
    if proof_of_income:
        contract.proof_of_income_url = f"http://dummy/{proof_of_income.filename}"

    db.add(contract)

    # como a descricao do desafio diz que poderiam haver varias imagens do imovel, criei uma tabela associada
    if property_images:
        for i in property_images:
            if i.filename:
                file_url = f"http://dummy/{i.filename}"
                image = PropertyImage(contract_id=contract.id, url=file_url)
                db.add(image)

    # seta o novo status do contrato
    contract.status = ContractStatus.IMAGES_UPLOADED

    db.commit()
    db.refresh(contract)
    return contract
Beispiel #9
0
def create_file(*,
                file: UploadFile = File(...),
                db_session: Session = Depends(get_db)):
    """
    upload a new file.
    """
    meta_in = MetaCreate()
    meta_in.file_name, meta_in.content_type = file.filename, file.content_type
    meta_read = create(db_session=db_session, meta_in=meta_in)
    if meta_read.id > 0:
        with open(os.path.join(UPLOAD_FOLDER, 'temp', str(meta_read.id)),
                  "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    return meta_read
Beispiel #10
0
def create_database(
    name, database_file: Optional[bytes] = File(None)
) -> CreateDatabaseResponse:
    try:
        if database_file is not None:
            write_database_file(name, database_file)
        else:
            create_access_database(os.path.join(databases_directory, f"{name}.mdb"))
    except (AccessDatabaseAlreadyExist, FileExistsError):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT, detail="Access database already exist"
        )

    return CreateDatabaseResponse(name=f"{name}")
Beispiel #11
0
def update_picture(profile_id: str,
                   file: UploadFile = File(...),
                   db: Session = Depends(get_db)):
    """

    :param file:
    :param profile_id:
    :param db:
    :return:
    """
    picture = crud.upload_image(db=db, profile_id=profile_id, file=file)
    if picture is None:
        raise HTTPException(status_code=500,
                            detail="Error uploading the image")
    return picture
Beispiel #12
0
async def send_feed_back(file: UploadFile = File(default=None),
                         prediction: int = Form(None),
                         feedback: bool = Form(True),
                         correct_number: int = Form(None)):

    # save file into uploads folder
    with open(os.path.join('api', 'img_files', file.filename),
              'wb+') as buffer:
        shutil.copyfileobj(file.file, buffer)

    # Save feedback in database
    query = prediction_feedback.insert().values(filename=file.filename,
                                                prediction=prediction,
                                                feedback=feedback,
                                                correct_number=correct_number)
    obj = await database.execute(query)
    return {'result': obj}
Beispiel #13
0
async def create_upload_files(file: UploadFile = File(...),
                              filemd5: str = Form(...)):
    y = Path("./.temp/" + file.filename)
    z = Path("./.serve/" + filemd5)
    #md5 = md5sum(y)
    if handleUpload.save_upload_file(file, y) is True:
        shutil.move(y, z)
        with engine.connect() as conn:
            conn.execute(
                text(f"""
                    INSERT INTO TEST1
                    (FILENAME, DIRECTORY, MD5, VERSION, MESSAGE, UPLOADER)
                    VALUES ('{file.filename}', 'serve',
                    '{filemd5}', {0}, 'first commit', 'billy');
                    """))
            print("done commiting")
        return {"filenames": file.filename}
Beispiel #14
0
async def update_image_post(
        *,
        id: int,
        db: Session = Depends(get_db),
        image: UploadFile = File(...),
):
    """
    Superuser updates another user's image
    """
    if image.content_type not in ['image/jpeg', 'image/png']:
        raise HTTPException(status_code=406,
                            detail="Only .jpeg or .png  files allowed")

    file_name = services.generate_unique_img_name(image=image)
    file_path = MEDIA_PATH + file_name

    services.save_image_in_db(db=db, post_id=id, file_path=file_path)
    services.save_image_in_folder(image=image, file_path=file_path)
    return {"id": id, "filename": image.filename}
async def extract_from_upload(file: UploadFile = File(
    ...)) -> ExtractorResponse:
    """
    Upload a file and extract text and (possibly) meta-data
    """
    ext = os.path.splitext(file.filename)[1]
    temp = tempfile.NamedTemporaryFile(prefix="jargonbuster_",
                                       suffix=f"{ext}",
                                       delete=False)

    # Set the content type
    meta = {"content_type": file.content_type}

    try:
        # Write into temp file
        data = await file.read()
        temp.write(data)

        # Extractor:  parse file into (raw) text
        log.info(
            f"Starting text extraction for '{file.content_type}' from uploaded file '{file.filename}' "
        )
        extractResponse = UNIVERSAL_EXTRACTOR.extract(
            ExtractorRequest(
                filename=temp.name,
                meta=meta,
            ))

        return extractResponse

    except Exception as e:
        log.error(str(e))
        raise HTTPException(
            400, f"Can't extract from the the uploaded file: {str(e)}")
    finally:
        log.debug(f"deleting upload temp file: {temp.name}")
        temp.close()
        os.unlink(temp.name)
async def execute_pipeline_upload(
    request: fastapi.Request, name: str,
    file: UploadFile = File(...)) -> PipelineExecutionResponse:

    # generate settings object from query params
    settings = dict(**request.query_params)

    try:
        # upload file to temp folder and extract the text
        extractResponse = await extract_from_upload(file)

        # Create new pipeline execution request, using extracted input text.
        execution_request = PipelineExecutionRequest(text=extractResponse.text,
                                                     meta=extractResponse.meta,
                                                     settings=settings)

        return await execute_pipeline(request=request,
                                      name=name,
                                      execution_request=execution_request)

    except Exception as e:
        log.error(f"Error running pipeline from file upload : {str(e)}")
        raise HTTPException(
            400, f"Error running pipeline from file upload: {str(e)}")
Beispiel #17
0
async def predict_digit(file: UploadFile = File(default=None)):
    file_path = os.path.join('api', 'img_files', file.filename)
    file_content = (file.file.read())
    with open(file_path, "wb+") as file_object:
        file_object.write(file_content)
        file_object.close()

    with open(file_path, "r") as file_object:
        # Get a drawn image
        input_img = preprocess_drawn_image(file_object, (28, 28))

        # Predict number
        results = digit_cls_workflow.predict({'X':
                                              input_img})["classification"][0]

    # Save feedback in database
    query = prediction_feedback.insert().values(
        filename=file.filename,
        prediction=int(results),
    )

    await database.execute(query)

    return {"prediction": int(results)}
Beispiel #18
0
async def upload_file(classroom_uid: str = Body(...),
                      path: str = Body(...),
                      token: dict = Depends(token_validation),
                      file: Optional[UploadFile] = File(None)):
    return await storage_routes.upload_file(token, classroom_uid, path, file)
Beispiel #19
0
class CreateFile(BaseModel):
    path = str
    file = File(...)
Beispiel #20
0
class AssetUploadModel(BaseModel):
    fileobject: UploadFile = File(...)
    filename: str = Body(default=None)
Beispiel #21
0
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}