Example #1
0
async def deleteStocks(stock_request: StockRequest,
                       background_tasks: BackgroundTasks,
                       db: Session = Depends(get_db)):
    """
    tenteando deleta
    """
    stock = Stock()
    stock.symbol = stock_request.symbol

    db.remove(stock)
    db.commit()

    background_tasks.delete_task(delete, stock.id)
Example #2
0
async def register_user(user_info: SignupInfo,
                        background_task: BackgroundTasks) -> dict:
    """Register a new user."""
    user = await signup(user_info)
    verification_token = create_access_token(user.email, short_duration=True)

    background_task.add_task(
        send_verification_email,
        recipient_name=user.firstname,
        email=user.email,
        token=verification_token,
    )
    return responses.EmailMsg(detail="Email sent")
async def post_new_ids(ids: List[str],
                       background_tasks: BackgroundTasks,
                       credentials: HTTPBasicCredentials = Depends(security)):
    utils.get_basic_auth_client(credentials)

    # create subprocess: background task to get new protocols and iterate over (start parser/cme)
    logging.info(f"Received update request for sessions '{ids}'")
    background_tasks.add_task(controller.evaluate_newest_sessions, ids)

    return {
        "details: ":
        f"Background task has been created to evaluate newest sessions with ids: '{ids}'"
    }
Example #4
0
async def train(request: Request, background_tasks: BackgroundTasks, index_types=["flat", "flat_sklearn"], vectorizer_types=["tf_idf"]):
    vectorizer_types = str_to_ls(vectorizer_types)
    index_types = str_to_ls(index_types)
    background_tasks.add_task(ml_core.train, es,
                              index_types, vectorizer_types)
    log_stats(request, data=None)
    #message = {}
    # if in_progress:
    print("Training task created and sent to the background...")
    # message = {'status': 'training'}
    # else:
    message = {'status': 'in_progress'}
    return JSONResponse(message)
Example #5
0
def get_country(country_name: str, request: Request,
                background_tasks: BackgroundTasks) -> Dict[str, Any]:
    """ Search by name or ISO (alpha2) """
    try:
        background_tasks.add_task(write_log,
                                  requested_path=str(request.url),
                                  client_ip=str(request.client))
        raw_data = covid_api_v2.get_country(country_name.lower())

    except Exception as e:
        raise HTTPException(status_code=404, detail="Item not found")

    return raw_data
Example #6
0
async def create_summary(
        background_tasks: BackgroundTasks, model_name: str = Form(...), length: str = Form(...), file: UploadFile = File(...),
        authorization: Optional[str] = Header(None)
) -> SummaryResponseSchema:
    # logger.info("file " + file.filename)
    user = get_current_user(authorization)
    email = get_current_user_email(authorization)
    log.info("current user email " + email)
    new_task = Job()
    jobs[new_task.uid] = new_task
    payload = BulkSummaryPayloadSchema(modelName=model_name)
    background_tasks.add_task(generate_bulk_summary, new_task, payload.modelName, file, email, user.full_name, length)
    return new_task
Example #7
0
async def update_event(event_id: int,
                       event: schemas.EventBase,
                       background_tasks: BackgroundTasks,
                       db: Session = Depends(get_db)):
    print(event)
    update_event_encoded = jsonable_encoder(event)
    db_event = crud.update_event(db,
                                 event_id=event_id,
                                 event=update_event_encoded)

    background_tasks.add_task(
        email_updates.send_email_update(db, event_id=event_id))
    return db_event
Example #8
0
async def create_stock(stock_request: StockRequest,
                       background_tasks: BackgroundTasks,
                       db: Session = Depends(get_db)):

    stock = Stock()
    stock.symbol = stock_request.symbol

    db.add(stock)
    db.commit()

    background_tasks.add_task(fetch_stock_data, stock.id)

    return {"code": "success", "msg": "stock created"}
Example #9
0
async def ingest(background_tasks: BackgroundTasks):
    try:
        if not os.path.exists(INGEST_DIRECTORY):
            os.makedirs(INGEST_DIRECTORY)
        if not os.path.exists(TRAIN_DIRECTORY):
            raise Exception("Training data directory not exsists!!!")
        background_tasks.add_task(fetch_data, TRAIN_DIRECTORY)
        return {"status":"ingestion initiated"}
    except:
        #traceback.print_exc()
        msg=traceback.format_exception(*sys.exc_info())
        print(msg)
        raise HTTPException(status_code=500, detail=msg)
Example #10
0
def bookshelf_post(
    bid,
    shelf,
    background_tasks: BackgroundTasks,
    as_user: str = None,
    viewer: M.User = Depends(fastapi_users.get_current_user)
):
    background_tasks.add_task(ga, viewer.id, 'bookshelf', shelf)
    user, snooping = getuser(viewer, as_user)
    if snooping and not user.share_data.books:
        return cant_snoop('Books')
    M.Bookshelf.upsert(user.id, bid, shelf)
    return {}
Example #11
0
async def register_owner(
    *,
    db: Session = Depends(get_db),
    data: OwnerCreate,
    background_tasks: BackgroundTasks,
):
    """registering new owners."""
    otp = generate_random_otp()
    with expected_integrity_error(
        db, detail="There was a conflict with an existing owner.", debug=False
    ):
        if owner := create_owner(db, user_in=data, otp=otp):
            background_tasks.add_task(send_email_verify_otp, owner.email, owner.otp)
Example #12
0
def schedule_mission(request: schemas.ScheduleMissionRequest,
                     background_tasks: BackgroundTasks,
                     db: Session = Depends(get_db),
                     volunteer: models.Volunteer = Depends(get_current_active_volunteer)):
    mission = crud.get_mission_by_uuid(db, _uuid=request.mission_id)
    if not mission:
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail=schemas.MissionNotFound.description())
    if not has_role_or_above(volunteer, models.VolunteerRole.coordinator):
        check_volunteer_mission(db, mission, volunteer, VolunteerMissionState.accepted)

    crud.set_mission_schedule(db, mission, request.schedule_date, request.preferred_hours)
    background_tasks.add_task(crud.set_mission_approved_task, mission.uuid)
    return mission.to_dict()
Example #13
0
def create_meal_plan(
        background_tasks: BackgroundTasks,
        data: MealPlanIn,
        session: Session = Depends(generate_session),
        current_user: UserInDB = Depends(get_current_user),
):
    """ Creates a meal plan database entry """
    set_mealplan_dates(data)
    background_tasks.add_task(create_group_event,
                              "Meal Plan Created",
                              f"Mealplan Created for '{current_user.group}'",
                              session=session)
    return db.meals.create(session, data.dict())
Example #14
0
async def upload_file(background_tasks: BackgroundTasks, response: Response, file: UploadFile = File(...), folder: Optional[str] = Form(''), childOf: Optional[str] = Form(''), identity: str = Depends(get_jwt_identity)):
	try:
		if file.filename == '' or (len(folder) > 0 and folder[0] == '/'):
			raise SchemaValidationError
		User.objects.get(id=identity) # make sure the user exists
		if allowed_file(file.filename):
			# Handle filename collisions
			filename = file.filename
			counter = 2
			while True:
				try:
					Media.objects.get(filename=filename, folder=folder)
					newFilename = filename
					filenameSplit = newFilename.rsplit('.', 1)
					filename = filenameSplit[0] + '_' + str(counter) + '.' + filenameSplit[1]
					counter += 1
				except DoesNotExist:
					break
			mimetype = file.content_type
			if not mimetype:
				mimetype = mimetypes.guess_type(filename)
			
			if FileSettings.ENABLE_FFMPEG and FileSettings.ENABLE_FILE_PROCESSING and (mimetype[:6] == 'video/' or mimetype[:6] == 'audio/' or mimetype == 'application/x-subrip' or mimetype == 'application/ttml+xml'):
				# Process the file
				splitFilename = filename.rsplit('.', 1)
				media = Media(owner=identity, filename=splitFilename[0], folder=folder, container=True, processing=True)
				media.save()
				background_tasks.add_task(processMedia, media, file, splitFilename[1])
				#processMedia(media, file)
				response.status_code = 202
			else:
				media = Media(owner=identity, filename=filename, folder=folder)
				media.file.put(file.file, content_type=mimetype)
				media.save()

				for parent in childOf.split(','):
					try:
						if parent:
							Media.objects.get(id=parent).update(push__associatedMedia=media)
					except DoesNotExist:
						pass
			return media.serialize()
		raise SchemaValidationError
	except SchemaValidationError as e:
		raise SchemaValidationError().http_exception
	except DoesNotExist:
		raise UnauthorizedError().http_exception
	except MediaProcessingError:
		raise MediaProcessingError().http_exception
	except Exception as e:
		raise e
Example #15
0
async def handle_event(
        event: EventEnvelope,
        request: Request,
        response: Response,
        background_tasks: BackgroundTasks,
        x_slack_request_timestamp: int = Header(None),
        x_slack_signature: str = Header(None),
        db_session: Session = Depends(get_db),
):
    """Handle all incomming Slack events."""
    raw_request_body = bytes.decode(await request.body())

    # We verify the timestamp
    verify_timestamp(x_slack_request_timestamp)

    # We verify the signature
    verify_signature(raw_request_body, x_slack_request_timestamp,
                     x_slack_signature)

    # Echo the URL verification challenge code back to Slack
    if event.challenge:
        return {"challenge": event.challenge}

    event_body = event.event

    user_id = event_body.user
    channel_id = get_channel_id_from_event(event_body)

    if user_id and channel_id:
        conversation = conversation_service.get_by_channel_id_ignoring_channel_type(
            db_session=db_session, channel_id=channel_id)

        if conversation and dispatch_slack_service.is_user(user_id):
            # We create an async Slack client
            slack_async_client = dispatch_slack_service.create_slack_client(
                run_async=True)

            # We resolve the user's email
            user_email = await dispatch_slack_service.get_user_email_async(
                slack_async_client, user_id)

            # Dispatch event functions to be executed in the background
            for f in event_functions(event):
                background_tasks.add_task(f,
                                          user_email,
                                          conversation.incident_id,
                                          event=event)

    # We add the user-agent string to the response headers
    response.headers["X-Slack-Powered-By"] = create_ua_string()
    return {"ok"}
Example #16
0
async def handle_action(
    request: Request,
    response: Response,
    background_tasks: BackgroundTasks,
    x_slack_request_timestamp: int = Header(None),
    x_slack_signature: str = Header(None),
    db_session: Session = Depends(get_db),
):
    """Handle all incomming Slack actions."""
    raw_request_body = bytes.decode(await request.body())
    request_body_form = await request.form()
    action = json.loads(request_body_form.get("payload"))

    # We verify the timestamp
    verify_timestamp(x_slack_request_timestamp)

    # We verify the signature
    verify_signature(raw_request_body, x_slack_request_timestamp, x_slack_signature)

    # We create an async Slack client
    slack_async_client = dispatch_slack_service.create_slack_client(run_async=True)

    # We resolve the user's email
    user_id = action["user"]["id"]
    user_email = await dispatch_slack_service.get_user_email_async(slack_async_client, user_id)

    # We resolve the action name based on the type
    action_name = get_action_name_by_action_type(action)

    # if the request was made as a form submission from slack then we skip getting the incident_id
    # the incident will be created in in the next step
    incident_id = 0
    if action_name != NewIncidentSubmission.form_slack_view:
        # we resolve the incident id based on the action type
        incident_id = get_incident_id_by_action_type(action, db_session)

    # Dispatch action functions to be executed in the background
    for f in action_functions(action_name):
        background_tasks.add_task(f, user_id, user_email, incident_id, action)

    # We add the user-agent string to the response headers
    response.headers["X-Slack-Powered-By"] = create_ua_string()

    # When there are no exceptions within the dialog submission, your app must respond with 200 OK with an empty body.
    response_body = {}
    if action_name == NewIncidentSubmission.form_slack_view:
        # For modals we set "response_action" to "clear" to close all views in the modal.
        # An empty body is currently not working.
        response_body = {"response_action": "clear"}

    return response_body
Example #17
0
async def handle_command(
        request: Request,
        response: Response,
        background_tasks: BackgroundTasks,
        x_slack_request_timestamp: int = Header(None),
        x_slack_signature: str = Header(None),
        db_session: Session = Depends(get_db),
):
    """Handle all incomming Slack commands."""
    raw_request_body = bytes.decode(await request.body())
    request_body_form = await request.form()
    command = request_body_form._dict

    # We verify the timestamp
    verify_timestamp(x_slack_request_timestamp)

    # We verify the signature
    verify_signature(raw_request_body, x_slack_request_timestamp,
                     x_slack_signature)

    # We add the user-agent string to the response headers
    response.headers["X-Slack-Powered-By"] = create_ua_string()

    # If the incoming slash command is equal to reporting new incident slug
    if command.get("command") == SLACK_COMMAND_REPORT_INCIDENT_SLUG:
        background_tasks.add_task(func=create_report_incident_modal,
                                  db_session=db_session,
                                  command=command)

        return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(
            command.get("command"),
            f"Unable to find message. Command: {command.get('command')}")
    else:
        # Fetch conversation by channel id
        channel_id = command.get("channel_id")
        conversation = get_by_channel_id(db_session=db_session,
                                         channel_id=channel_id)

        # Dispatch command functions to be executed in the background
        if conversation:
            for f in command_functions(command.get("command")):
                background_tasks.add_task(f,
                                          conversation.incident_id,
                                          command=command)

            return INCIDENT_CONVERSATION_COMMAND_MESSAGE.get(
                command.get("command"),
                f"Unable to find message. Command: {command.get('command')}")
        else:
            return render_non_incident_conversation_command_error_message(
                command.get("command"))
Example #18
0
def create_pdf(
        pdf_request: DocumentPdf,
        background_tasks: BackgroundTasks,
        db: Session = Depends(get_db),
):
    """
    Submit pdf creation
    """
    pdf_id = add_create_pdf(db, pdf_request)
    pdf_request_dict = pdf_request.dict()
    pdf_request_dict["id"] = pdf_id
    background_tasks.add_task(task_generate_pdf, pdf_request_dict)

    return {"id": pdf_id}
Example #19
0
async def create_stock(stock_request: StockRequest,
                       background_tasks: BackgroundTasks,
                       db: Session = Depends(get_db)):
    """
    Create a stock and store in Database.
    """
    stock = Stock()
    stock.symbol = stock_request.symbol
    db.add(stock)
    db.commit()

    background_tasks.add_task(fetch_stock_data, stock.id)

    return {"code": "Success", "message": "Stock Created"}
async def spread_notification_tts_body_age(
        item: Info,
        db: Session = Depends(get_db),
        background_tasks: BackgroundTasks = BackgroundTasks):
    records = db.query(
        models.Client).filter(models.Client.idade >= item.minAge)
    records = records.filter(models.Client.idade <= item.maxAge).all()

    for dados in records:
        message = item.company + ': ' + dados.nome.split(
            ' ')[0] + ', ' + item.message
        background_tasks.add_task(send_tts, dados.numero_telefone, message)

    return records
Example #21
0
async def get_confirmed(request: Request, background_tasks: BackgroundTasks) -> Dict[str, int]:
    """
    Get the total numbers of confirmed cases

    - **confirmed**: confirmed cases
    """
    try:
        background_tasks.add_task(write_log, requested_path=str(request.url), client_ip=str(request.client))
        data = COVID_API_V2.get_confirmed()

    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return data
Example #22
0
async def root(word: str, background_task: BackgroundTasks):
    task_name = None

    # set correct task name based on the way you run the example
    if not bool(os.getenv('DOCKER')):
        task_name = "app.worker.celery_worker.test_celery"
    else:
        task_name = "app.app.worker.celery_worker.test_celery"

    task = celery_app.send_task(task_name, args=[word])
    print(task)
    background_task.add_task(background_on_message, task)

    return {"message": "Word received"}
Example #23
0
def handle_modal_action(action: dict, background_tasks: BackgroundTasks):
    """Handles all modal actions."""
    view_data = action["view"]
    view_data["private_metadata"] = json.loads(view_data["private_metadata"])

    action_id = view_data["callback_id"]
    incident_id = view_data["private_metadata"].get("incident_id")

    channel_id = view_data["private_metadata"].get("channel_id")
    user_id = action["user"]["id"]
    user_email = action["user"]["email"]

    for f in action_functions(action_id):
        background_tasks.add_task(f, user_id, user_email, channel_id, incident_id, action)
Example #24
0
async def chat_bot_action_transmit(chat_event: ChatEventBody,
                                   background_tasks: BackgroundTasks,
                                   request: Request):
    if chat_event.event == ChatEventEnum.new_chat:
        logger.debug(f'process new chat event with body: {chat_event}')
        background_tasks.add_task(on_new_chat_event, chat_event.chat.id,
                                  chat_event.chat.language,
                                  chat_event.visitor.field_value.orderId)
    elif chat_event.event == ChatEventEnum.new_message:
        logger.debug(f'process new message event with body: {chat_event}')
        if chat_event.message.kind == MessageKindEnum.file_visitor:
            logger.debug('run on_new_file handler')
            background_tasks.add_task(on_new_file, chat_event.message.data,
                                      chat_event.chat_id)
        elif chat_event.message.kind == MessageKindEnum.keyboard_response:
            logger.debug('run on_keyboard_response handler')
            background_tasks.add_task(on_keyboard_response, chat_event.chat_id,
                                      chat_event.message.data.button.text,
                                      chat_event.message.data.button.id)
        else:
            logger.debug('run on_new_message_event handler')
            background_tasks.add_task(on_new_message_event, chat_event.chat_id,
                                      chat_event.message.text)
    else:
        return Response(status_code=status.HTTP_400_BAD_REQUEST)
    return {'result': 'ok'}
Example #25
0
async def merge_branches(merge: Merge, background_tasks: BackgroundTasks):
    """
    Simple endpoint to simulate a shared resource we want to merge that must
    be locked when active. We simulate for 10 seconds.
    """
    global _shared_resources_dict
    if _shared_resources_dict.get(merge.branch_name):
        logger.warning("We got a request but the shared resource is in use!")
        raise HTTPException(
            status_code=400,
            detail=f"Branch {merge.branch_name} already in use!")

    background_tasks.add_task(use_shared_resource, merge.branch_name)
    return {'message': f'merge for branch: {merge.branch_name} in progress'}
Example #26
0
async def import_from_urlscan(uuid: str,
                              background_tasks: BackgroundTasks) -> Snapshot:
    try:
        result = await URLScan.import_as_snapshot(uuid)
    except httpx.HTTPError:
        raise HTTPException(status_code=404, detail=f"{uuid} is not found")

    snapshot = await save_snapshot(result)

    background_tasks.add_task(MatchinbgTask.process, snapshot)
    background_tasks.add_task(UpdateProcessingTask.process, snapshot)

    model = cast(Snapshot, snapshot.to_model())
    return model
Example #27
0
def handle_block_action(action: dict, background_tasks: BackgroundTasks):
    """Handles a standalone block action."""
    view_data = action["view"]
    view_data["private_metadata"] = json.loads(view_data["private_metadata"])

    incident_id = view_data["private_metadata"].get("incident_id")
    channel_id = view_data["private_metadata"].get("channel_id")
    action_id = action["actions"][0]["action_id"]

    user_id = action["user"]["id"]
    user_email = action["user"]["email"]

    for f in block_action_functions(action_id):
        background_tasks.add_task(f, user_id, user_email, channel_id, incident_id, action)
Example #28
0
def bulk_update_rating_database(background_task: BackgroundTasks,
                                csv_file: UploadFile = File(...)):
    jobId = str(uuid.uuid4())
    csv_file.file.seek(0, 2)
    file_size = csv_file.file.tell() / 1000
    job_doc = {"jobId": jobId, "status": "inProgress", "percentage": 0}
    insert_status(job_doc)
    background_task.add_task(save_ratings_to_db, csv_file, file_size, jobId)

    return {
        "filename": csv_file.filename,
        "file_size": file_size,
        "job": job_doc
    }
Example #29
0
def create_registration(registration: Registation,
                        tasks: BackgroundTasks,
                        x_token: str = Header(None)):
    if x_token == os.getenv("DETA_API_TOKEN"):
        obj = db.put({
            "event_name": registration.event_name,
            "email": registration.email,
            "needs_gear": registration.needs_gear,
            "created_at": str(datetime.datetime.now()),
        })
        tasks.add_task(send_registration_mail, registration, obj["key"])

        return
    return Response(status_code=401, )
Example #30
0
async def create_group(
        background_tasks: BackgroundTasks,
        group_data: GroupBase,
        current_user=Depends(get_current_user),
        session: Session = Depends(generate_session),
):
    """ Creates a Group in the Database """

    try:
        db.groups.create(session, group_data.dict())
        background_tasks.add_task(create_group_event, "Group Created",
                                  f"'{group_data.name}' created", session)
    except Exception:
        raise HTTPException(status.HTTP_400_BAD_REQUEST)