async def add_client(self, request): """ --- description: Запрос для добавления нового клиента tags: - Clients produces: - application/json - application/xml parameters: - name: card in: body description: данные нового клиента required: true schema: type: object properties: name: type: string description: имя клиента responses: "200": description: успех. Возвращает данные нового клиента "406": description: ошибка клиента. Указан неверный Accept """ encoder = self.__choose_encoder(request) data = await self.__decode_post(request) try: client = await self.__client_model.add_client(data) return web.HTTPCreated(content_type=encoder.content_type, body=encoder.encode(client)) except MultipleInvalid as e: raise web_exceptions.HTTPBadRequest(text=str(e))
async def add_job(self, request): data = await request.post() self.logger.debug("received add request {0}".format(data)) if 'command' not in data or \ 'minute' not in data or \ 'hour' not in data or \ 'dom' not in data or \ 'month' not in data or \ 'dow' not in data: return web.Response( status=500, text='not all mandatory fields submitted via form') cron_item = self.generate_cron_item(data) if 'disabled' in data: cron_item.enable(False) if cron_item in self.storage.cluster_jobs: raise web.HTTPConflict(text='job already exists') self.logger.debug("broadcasting add result") broadcast(self.udp_port, UdpSerializer.dump(cron_item, self.hash_key)) raise web.HTTPCreated()
async def submit_infernal_job(request): # validate the data data = await request.json() try: engine = request.app['engine'] job_id = data['job_id'] sequence = data['sequence'] except (KeyError, TypeError, ValueError) as e: logger.error(e) raise web.HTTPBadRequest(text=str(e)) from e consumer_ip = get_ip(request.app) # if request was successful, save the consumer state and infernal_job state to the database if engine and job_id and sequence: try: await set_consumer_fields(engine, consumer_ip, CONSUMER_STATUS_CHOICES.busy, job_chunk_id='infernal-job') await set_infernal_job_status( engine, job_id, status=JOB_CHUNK_STATUS_CHOICES.started) await set_consumer_to_infernal_job(engine, job_id, consumer_ip) except (DatabaseConnectionError, SQLError) as e: logger.error(e) raise web.HTTPBadRequest(text=str(e)) from e # spawn cmscan job in the background and return 201 await spawn(request, infernal(engine, job_id, sequence, consumer_ip)) return web.HTTPCreated() else: raise web.HTTPBadRequest( text='Invalid data. Engine, job_id and sequence not found.')
async def create_folders_from_project(request: web.Request): # FIXME: Update openapi-core. Fails with additionalProperties https://github.com/p1c2u/openapi-core/issues/124. Fails with project # params, query, body = await extract_and_validate(request) user_id = request.query["user_id"] body = await request.json() source_project = body.get("source", {}) destination_project = body.get("destination", {}) nodes_map = body.get("nodes_map", {}) assert set(nodes_map.keys()) == set( source_project["workbench"].keys()) # nosec assert set(nodes_map.values()) == set( # nosec destination_project["workbench"].keys() # nosec ) # nosec # TODO: validate project with jsonschema instead?? with handle_storage_errors(): dsm = await _prepare_storage_manager( params={"location_id": SIMCORE_S3_ID}, query={"user_id": user_id}, request=request, ) await dsm.deep_copy_project_simcore_s3(user_id, source_project, destination_project, nodes_map) raise web.HTTPCreated(text=json.dumps(destination_project), content_type="application/json")
async def post(self): """Создает новый рецепт""" user_id = int(await check_authorized(self.request)) if not await permits(self.request, "is_active"): raise web.HTTPForbidden user = await User.get(pk=user_id) try: json = await self.request.json() except JSONDecodeError: raise web.HTTPBadRequest try: steps = json.pop("cooking_steps") except KeyError: raise web.HTTPBadRequest try: recipe = await Recipe.create(author=user, **json) except IntegrityError: raise web.HTTPBadRequest for i, step in enumerate(steps): await CookingStep.create(recipe=recipe, order=i + 1, **step) raise web.HTTPCreated( headers={"Location": str(self.request.url / str(recipe.id))})
async def signup(request: web.Request): app = request.app # type: Application token = request.match_info.get('token') if request.content_type.startswith('application/json'): data = await request.json() else: data = await request.post() if not token: # Stage #1 of account registration email = data['email'] start_coro = app.signup_start(email) if request.path.endswith('/signup') else app.renew_start(email) if await start_coro: return web.HTTPOk() else: if request.method != 'POST': email_coro = app.signup_email(token) if '/signup/' in request.path else app.renew_email(token) email = await email_coro if email: return web.json_response({'email': email}) else: # stage #2 of signup password = data['password'] if '/signup/' in request.path: display_name = data.get('display_name') finish_coro = app.signup_finish(token, display_name, password) else: finish_coro = app.renew_finish(token, password) if await finish_coro: return web.HTTPCreated() return web.HTTPUnprocessableEntity()
async def post(self): """Добавляет этап приготовления""" user_id = int(await check_authorized(self.request)) if not await permits(self.request, "is_active"): raise web.HTTPForbidden try: recipe = await Recipe.get_or_none( pk=int(self.request.match_info["recipe_id"])) except ValueError: raise web.HTTPBadRequest if not recipe: raise web.HTTPNotFound await recipe.fetch_related("author") if recipe.author.id != user_id: raise web.HTTPForbidden try: json = await self.request.json() except JSONDecodeError: raise web.HTTPBadRequest try: async with in_transaction(): await CookingStep.filter( recipe=recipe, order__gte=json["order"]).update(order=F("order") + 1) step = await CookingStep.create(recipe=recipe, **json) except (KeyError, IntegrityError, ConfigurationError) as e: raise web.HTTPBadRequest(reason=e) raise web.HTTPCreated( headers={"Location": str(self.request.url / str(step.order))})
async def post(request: web.Request) -> web.Response: reader = await request.multipart() metadata, jpeg = await read_multipart(reader) identifier = make_identifier() storage_upload(request, identifier, bytes(jpeg)) metadata['content_id'] = identifier await mq_publish(request, metadata, 'uploads') raise web.HTTPCreated(headers={'Location': f'/content/{identifier}'})
async def create(request): body = await request.json() await db.create_object( request.app['db'], request.match_info['table'], body ) return web.HTTPCreated(headers={'Location': 'uid'})
async def add_object(request: web.Request) -> web.Response: data = await request.json() storage: DataStorage = await __get_collection_storage( request, request.match_info['collection']) await storage.put_object(uuid.uuid4(), data) return web.HTTPCreated()
async def agent_registration(request: Request): data = await request.text() data = json.loads(data) if 'token' not in data or data['token'] != test_config.registration_token: return web.HTTPUnauthorized() response_dict = {"name": data["name"], "token": test_config.agent_token, "id": test_config.agent_id} return web.HTTPCreated(text=json.dumps(response_dict), headers={'content-type': 'application/json'})
async def feed_callback(request): xml = await request.text() feed = feedparser.parse(xml) for e in feed.entries: text = (f'channel: {e.yt_channelid}\n' f'video_url: {e.link}\n' f'title: {e.title}') print(text) return web.HTTPCreated() # 201
async def create_dashboard(request: web.Request): post = await request.post() project = request.match_info['project'] dashboard = try_get(post, 'dashboard', str) created = await database.create_dashboard(project, dashboard) if not created: raise web.HTTPBadRequest() print("created") return web.HTTPCreated()
def test_system_route(): route = SystemRoute(web.HTTPCreated(reason='test')) with pytest.raises(RuntimeError): route.url_for() assert route.name is None assert route.resource is None assert "<SystemRoute 201: test>" == repr(route) assert 201 == route.status assert 'test' == route.reason
async def mkcol(self): try: current, resource = await self._instantiate_parent() except errors.ResourceDoesNotExist: raise web.HTTPNotFound(text="Parent does not exist") await resource.populate_props() if not resource.is_collection: raise web.HTTPBadRequest(text="Collection expected") await resource.make_collection(current) return web.HTTPCreated()
async def post_note(request: Request): d = await request.json() session = Session() note = Note(id=None, content=d['content'], create_date=datetime.now()) session.add(note) session.commit() session.close() return web.HTTPCreated()
async def post_start_urls_by_spider(request: web.Request) -> web.Response: """ Add start urls by spider name to Redis. :param request: web request :return: web response without body with 201 response status """ redis = request.app['create_redis'] data = await request.json() await redis.sadd(data['name'], *data['start_urls']) return web.HTTPCreated(text="")
async def wiki_edit(request): """Create a new revision for wiki page.""" # FIXME: validate title = request.match_info['title'] data = await request.json() body = data['body'] async with request.app['asyncpg'].acquire() as cnx: sql = 'INSERT INTO wiki (title, body, created_at) VALUES ($1, $2, now())' await cnx.execute(sql, title, body) raise web.HTTPCreated()
async def objects_create(request): try: body = await request.json() success = request.app['ldap'].add(body['dn'], [request.match_info['object_class']], body['attributes']) except (KeyError, JSONDecodeError, LDAPObjectClassError): raise web.HTTPBadRequest() if not success: raise web.HTTPBadRequest(text=str(request.app['ldap'].result)) return web.HTTPCreated()
async def create_tokens(request: web.Request): uid = request[RQT_USERID_KEY] # TODO: validate body = await request.json() # TODO: what it service exists already!? # TODO: if service already, then IntegrityError is raised! How to deal with db exceptions?? await users_api.create_token(request.app, uid, body) raise web.HTTPCreated(text=json.dumps({"data": body}), content_type="application/json")
async def create_group(request: web.Request): user_id = request[RQT_USERID_KEY] new_group = await request.json() try: new_group = await groups_api.create_user_group(request.app, user_id, new_group) raise web.HTTPCreated( text=json.dumps({"data": new_group}), content_type="application/json" ) except UserNotFoundError as exc: raise web.HTTPNotFound(reason=f"User {user_id} not found") from exc
async def create_model(request: web.Request): post = await request.post() project = request.match_info['project'] model = try_get(post, 'model', str) filename = try_get(post, 'filename', str) timestamp = datetime.now() created = await database.create_model(project, model, filename, timestamp) if not created: raise web.HTTPBadRequest() print("created") return web.HTTPCreated()
async def add_channel(request: web.Request): post = await request.post() project = request.match_info['project'] dashboard = request.match_info['dashboard'] tile = request.match_info['tile'] channel = try_get(post, 'channel', str) created = await database.add_channel(project, dashboard, tile, channel) print("created", created) if not created: raise web.HTTPBadRequest() return web.HTTPCreated()
def function2533(): var898 = SystemRoute(web.HTTPCreated(reason='test')) with pytest.raises(RuntimeError): var898.url() with pytest.raises(RuntimeError): var898.url_for() assert (var898.name is None) assert (var898.resource is None) assert ('<SystemRoute 201: test>' == repr(var898)) assert (201 == var898.status) assert ('test' == var898.reason)
async def daily_file_write_log(request): """Writes log into files """ data = await request.post() log_path = data.get('log_path', 'daily.log') msg = data.get('msg', '') day = data.get('day', '') if not DAILY_FILE_MANAGER.is_opened(log_path, day): DAILY_FILE_MANAGER.open(log_path) DAILY_FILE_MANAGER.write(log_path, msg) return web.HTTPCreated(text='ok')
async def copy(self): resource = await self._instantiate_resource(self.relative) try: await resource.copy(self.destination) created = True except errors.ResourceAlreadyExists: old = await self._instantiate_resource(self.destination) await old.delete() await resource.copy(self.destination) created = False return web.HTTPCreated() if created else web.HTTPNoContent()
async def create_event_trigger(request: web.Request): post = await request.post() project = request.match_info['project'] trigger_id = try_get(post, 'id', str) init_params = try_get(post, 'init_params', str) topic_id = try_get(post, 'topic_id', str) created = await database.create_event_trigger(project, trigger_id, init_params, topic_id) if not created: raise web.HTTPBadRequest() print("created") return web.HTTPCreated()
async def post(self): body = await self.get_body() redis_client = self.request.app["db_client"] try: microservice = Microservice(**body) except TypeError as exc: raise web.HTTPBadRequest(text=exc.args[0]) await microservice.save(redis_client) return web.HTTPCreated()
async def register(request): """ Regsiters a sample into a database. A list of samples has to be posted in HTTP body, in JSON format: [{"dataset": "/a/b/c", "run": "123456", "lumi": "0", "file": "/a/b/c.root", "fileformat": 1}] """ result = await service.register_samples(await request.text()) if result != True: return web.json_response(result, status=400) return web.HTTPCreated()
async def sessions(request): query = await request.post() session_name = query["name"] crossword_index = query["crossword"] try: crossword = await load_crossword(crossword_index) except: raise web.HTTPNotFound() session_id = str(uuid1()) session = Session(session_name, session_id, [], crossword, []) sessions[session_id] = session return web.HTTPCreated(headers={"Location": f"/sessions/{session_id}"})