async def process(client: SocketModeClient, req: SocketModeRequest): db_session = SessionLocal() background_tasks = BackgroundTasks() if req.type == "events_api": response = await handle_slack_event( db_session=db_session, client=client.web_client, request=req.payload, background_tasks=background_tasks, ) if req.type == "slash_commands": response = await handle_slack_command( db_session=db_session, client=client.web_client, request=req.payload, background_tasks=background_tasks, ) if req.type == "interactive": response = await handle_slack_action( db_session=db_session, client=client.web_client, request=req.payload, background_tasks=background_tasks, ) response = SocketModeResponse(envelope_id=req.envelope_id, payload=response) await client.send_socket_mode_response(response) # run the background tasks await background_tasks()
def test_send(session, bad_user, event): background_task = BackgroundTasks() assert not send(session=session, event_used=1, user_to_send=1, title="Test", background_tasks=background_task)
def __init__(self) -> None: """ Crud instances of the collections needed. """ self.crud = CRUD(organizations_collection) self.users = CRUD(users_collection) self.events = CRUD(events_collection) self.backgroud_task = BackgroundTasks()
async def _predict_label( data: Data, job_id: str, background_tasks: BackgroundTasks = BackgroundTasks() ) -> Dict[str, Dict[str, float]]: label_proba = await __async_predict_label(data) store_data_job._save_data_job(data, job_id, background_tasks, False) return {'prediction': label_proba, 'job_id': job_id}
async def _predict_async_post( data: Data, job_id: str, background_tasks: BackgroundTasks = BackgroundTasks() ) -> Dict[str, List[float]]: image = base64.b64decode(str(data.image_data)) io_bytes = io.BytesIO(image) data.image_data = Image.open(io_bytes) store_data_job._save_data_job(data, job_id, background_tasks, True) return {'job_id': job_id}
async def _handle_request(self, request: Request) -> Response: # route GET requests to the IDE if request.method == "GET" and "text/html" in request.headers.get("Accept", ""): # read the GraphiQL playground html and serve it as content graphiql = pathlib.Path(__file__).parent / "graphiql.html" raw_html = None with open(graphiql.absolute(), "r") as f: raw_html = f.read() return HTMLResponse(raw_html) # route POST requests to the graphql executor elif request.method == "POST": content_type = request.headers.get("Content-Type", "") # parse graphql according to content type if "application/json" in content_type: data = await request.json() else: return PlainTextResponse( "Unsupported Media Type", status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, ) else: return PlainTextResponse( "Method Not Allowed", status_code=status.HTTP_405_METHOD_NOT_ALLOWED ) # attempt to pull final query and vars try: query = data["query"] variables = data.get("variables") except KeyError: return PlainTextResponse( "No GraphQL query found in the request", status_code=status.HTTP_400_BAD_REQUEST, ) # construct foundation fastapi context background = BackgroundTasks() context = {"request": request, "background": background} result = await self._execute_graphql(query, variables, context) # parse graphql result response = {} if not result.invalid: response["data"] = result.data if result.errors: response["errors"] = [format_error(e) for e in result.errors] status_code = ( status.HTTP_400_BAD_REQUEST if result.errors else status.HTTP_200_OK ) return ORJSONResponse(response, status_code=status_code, background=background)
async def _predict_label( data: Data, job_id: str, background_tasks: BackgroundTasks = BackgroundTasks() ) -> Dict[str, List[float]]: image = base64.b64decode(str(data.image_data)) io_bytes = io.BytesIO(image) data.image_data = Image.open(io_bytes) label_proba = await __async_predict_label(data) store_data_job._save_data_job(data, job_id, background_tasks, False) return {'prediction': label_proba, 'job_id': job_id}
async def post_message_async( content: ItemInParse, # user: User = Depends(get_current_user_authorizer()), ): if not content.message: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=f"Couldn't find the message: {content}", ) backgroundtask = BackgroundTasks() backgroundtask.add_task(dummy_background_task, content.message) return JSONResponse( {"status": "Starting dummy background task"}, background=backgroundtask, )
async def upload_py(file: UploadFile = File(...), message_format: str = None, background_tasks: BackgroundTasks = BackgroundTasks()): message = '' msg_format = 'text' if message_format.lower() == 'json': msg_format = 'json' log.info( f'{datetime.datetime.now().strftime("%Y-%m-%d-%H:%M.%S")}: ' f'Запрос на выполнение статического анализа файла "{file.filename}" ' f'с выводом отчета в формате {msg_format}') if file.filename[-3:] != '.py': message = f'Получен файл "{file.filename}" с неправилным расширением. Необходим файл с расширением .py' log.warning( f'{datetime.datetime.now().strftime("%Y-%m-%d-%H:%M.%S")}: {message}' ) else: if not os.path.exists(today_folder): os.mkdir(today_folder) file_name = f'{file.filename[:-3]}_{datetime.datetime.now().strftime("%H-%M-%S")}' file_path = os.path.join(today_folder, f'{file_name}.py') try: with open(file_path, 'wb') as buffer: shutil.copyfileobj(file.file, buffer) except Exception: message = f'Ошибка сервера' log.exception( f'{datetime.datetime.now().strftime("%Y-%m-%d-%H:%M.%S")}: {message}: {Exception}' ) else: message = f'Файл "{file.filename}" успешно загружен, ' \ f'сохранен под названием "{file_name}.py" ' \ f'и начaлся статический анализ с использованием pylint' log.info( f'{datetime.datetime.now().strftime("%Y-%m-%d-%H:%M.%S")}: {message}' ) background_tasks.add_task(pylint_analyse, file_path, file_name, msg_format) return {f'message': message}
async def process(client: SocketModeClient, req: SocketModeRequest): background_tasks = BackgroundTasks() if req.type == "events_api": response = await handle_slack_event( config=config, client=client.web_client, event=EventEnvelope(**req.payload), background_tasks=background_tasks, ) if req.type == "slash_commands": response = await handle_slack_command( config=config, client=client.web_client, request=req.payload, background_tasks=background_tasks, ) if req.type == "interactive": if req.payload["type"] == "block_suggestion": response = await handle_slack_menu( config=config, client=client.web_client, request=req.payload, ) else: response = await handle_slack_action( config=config, client=client.web_client, request=req.payload, background_tasks=background_tasks, ) response = SocketModeResponse(envelope_id=req.envelope_id, payload=response) await client.send_socket_mode_response(response) # run the background tasks await background_tasks()
async def run_ranking(ranker: Ranker): background_tasks = BackgroundTasks() background_tasks.add_task(rank_service.rank_by_session, ranker) response = JSONResponse(status_code=200, content="Ranking is running", background=background_tasks) return response
def startup_event(): background_tasks = BackgroundTasks() background_tasks.add_task(self.end) return True
async def predict_label(data: Data, background_tasks: BackgroundTasks = BackgroundTasks()): job_id = data.job_id if data.job_id is not None else get_job_id() return await _predict._predict_label(data, job_id, background_tasks)
def background_tasks(): bg_tasks = BackgroundTasks() return bg_tasks
import pytest import json from PIL import Image from typing import List, Tuple, Any from fastapi import BackgroundTasks from src.constants import PLATFORM_ENUM, CONSTANTS from src.jobs import store_data_job import src.jobs from src.app.ml.base_predictor import BaseData, BaseDataInterface test_job_id = '550e8400-e29b-41d4-a716-446655440000_0' test_uuid = '550e8400-e29b-41d4-a716-446655440000' mock_image = Image.open('src/app/ml/data/good_cat.jpg') labels = ['a', 'b', 'c'] mock_BackgroundTasks = BackgroundTasks() class MockData(BaseData): data: List[List[int]] = [[5.1, 3.5, 1.4, 0.2]] test_data: List[List[int]] = [[5.1, 3.5, 1.4, 0.2]] labels: List[str] = labels class MockDataImage(BaseData): image_data: Any = mock_image data: List[List[int]] = [[5.1, 3.5, 1.4, 0.2]] test_data: List[List[int]] = [[5.1, 3.5, 1.4, 0.2]] labels: List[str] = labels
async def create_ihou(info: dict): try: await IHou.objects.get(title=info['title']) except orm.exceptions.NoMatch as e: document = await IHou.objects.create(**info) BackgroundTasks().add_task(insert_values(document.__dict__))
async def predict(data: Data, background_tasks: BackgroundTasks = BackgroundTasks()): job_id = data.job_id if data.job_id is not None else get_job_id() result = await _predict_image._predict(data, job_id, background_tasks) return result
async def predict(data: Data, background_tasks: BackgroundTasks = BackgroundTasks()): job_id = data.job_id if data.job_id is not None else get_job_id() return await _predict_ab_test._predict(data, job_id, background_tasks, AB_TEST_GROUP)
def test_send_mail_bad_invitation_internal(client, configured_smtpd, sender_name, recipient_name, recipient_mail): background_task = BackgroundTasks() assert not send_email_invitation(sender_name, recipient_name, recipient_mail, background_task)
def test_send_mail_good_file_internal(client, configured_smtpd): background_task = BackgroundTasks() assert send_email_file(__file__, "*****@*****.**", background_task)
def test_send_mail_bad_file_internal(client, configured_smtpd, recipient_mail, file_path): background_task = BackgroundTasks() assert not send_email_file(file_path, recipient_mail, background_task)