def categories(request): user = request.user if user is None: raise HTTPForbidden if request.method == 'GET': data = request.params if 'creator_id' in data: categories = CategoryRecordService.by_creator_id(int(data['creator_id']), request) return list_to_json(categories, 'categories') categories = CategoryRecordService.by_creator_id(user.id, request) json_obj = list_to_json(categories, 'categories') return json_obj if request.method == 'POST': data = json.loads(json.dumps(request.json)) category_name = '' category_type_id = 0 if 'category_name' in data: category_name = data['category_name'] if 'category_type_id' in data: category_type_id = data['category_type_id'] if len(category_name) > 0 and category_type_id > 0: newcategory = Category(name=category_name, type_id=category_type_id, creator_id=user.id) with transaction.manager: zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager) request.dbsession.add(newcategory) transaction.commit() responseCreated = HTTPCreated() responseCreated.body = "category created" return responseCreated
def followees(request): user = request.user if user is None: raise HTTPForbidden if request.method == 'GET': followees = FollowRecordService.by_follower_id(user.id, request) return list_to_json(followees, 'followees') if request.method == 'POST': data = json.loads(json.dumps(request.json)) if 'followee_id' in data: follow = Follow(follower_id=user.id, followee_id=int(data['followee_id'])) with transaction.manager: zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager) request.dbsession.add(follow) responseCreated = HTTPCreated() responseCreated.body = "followed" return responseCreated if request.method == 'DELETE': data = json.loads(json.dumps(request.json)) if 'followee_id' in data: with transaction.manager: zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager) request.dbsession.query(Follow).filter_by(followee_id=int(data['followee_id'])).filter_by(follower_id=user.id).delete() transaction.commit() responseDeleted = HTTPOk() responseDeleted.body = "unfollowed" return responseDeleted
def __call__(self): new_user = IUser(self.request) checks = component.subscribers((new_user,), IRedundancyCheck) if any([check.check(new_user, self.request) for check in checks]) or\ not self.context.insert(new_user, check_member=True): return exception_response(409) return HTTPCreated()
def create_sub(request): # Params: # 'parent' : <parent name> or 'root' # 'name' : <subscription name> ensure_params(request, ('parent', 'name')) parent = request.params['parent'] name = request.params['name'] session = DBSession() # Verify parent's existence: try: if parent != 'root': parent = session.query(EventType).filter(EventType.name==parent).one() else: parent = None except NoResultFound: raise HTTPBadRequest('No subscription by that name: ' + parent) # Check if the mapping already exists: existing = session.query(EventType).filter(EventType.name==name).first() if existing and existing.parent != parent: raise HTTPBadRequest('Cant change subscription parent: ' + name) elif existing: return {} # The subscription already exists. It's all good. # Add the subscription to our subscriptions (but its ok if it already exists). eventType = EventType(name=name, parent=parent) session.add(eventType) session.flush() return HTTPCreated()
def create_forgot_password_request(self, email: str) -> Response: """Create a new email activation token for a user and produce the following screen. * Sets user password reset token * Sends out reset password email * The existing of user with such email should be validated beforehand :param email: User email. :return: Response. :raise: CannotResetPasswordException if there is any reason the password cannot be reset. Usually wrong email. """ request = self.request user_registry = UserRegistry(request) reset_info = user_registry.create_password_reset_token(email) if not reset_info: raise CannotResetPasswordException("Cannot reset password for email: {email}".format(email=email)) user, token, expiration_seconds = reset_info url = get_config_url(self.request, 'tm.ui_reset_password_url') link = '{}?code={}'.format(url, token) context = dict(link=link, user=user, expiration_hours=int(expiration_seconds / 3600)) send_templated_mail(request, [email, ], "login/email/forgot_password", context=context) return HTTPCreated(json={'message': 'Please check your email to continue password reset.'})
def put_document(request): """Adiciona ou atualiza registro de documento. A atualização do documento é idempotente. A semântica desta view-function está definida conforme a especificação: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6 """ data_url = request.validated["data"] assets = { asset["asset_id"]: asset["asset_url"] for asset in request.validated.get("assets", []) } try: request.services["register_document"]( id=request.matchdict["document_id"], data_url=data_url, assets=assets) except exceptions.AlreadyExists: try: request.services["register_document_version"]( id=request.matchdict["document_id"], data_url=data_url, assets=assets) except exceptions.VersionAlreadySet as exc: LOGGER.info( 'skipping request to add version to "%s": %s', request.matchdict["document_id"], exc, ) return HTTPNoContent("document updated successfully") else: return HTTPCreated("document created successfully")
def post(self): user, date = self.v['user'], self.v['date'] try: schema = AddEntrySchema() data = schema.deserialize(self.request.POST) except colander.Invalid as e: return HTTPBadRequest(e.asdict()) project_id = data.get('project_id') project = Project.query.get(project_id) if not project: raise HTTPBadRequest("Project is required") time = TimeEntry( date=date, user_id=user.id, time=data.get('time'), description=data.get('description'), ticket_id=data.get('ticket_id'), project_id=project_id if project_id else None, timer_ts=datetime.datetime.now() if data.get('timer') else None, frozen=bool(data.get('start_timer'))) self.session.add(time) return HTTPCreated('OK')
def signup(context, request): """ Create new user. :param request: Pyramid request object """ domain = 'encode.auth0.com' access_token = request.json.get('accessToken') if not access_token: raise HTTPBadRequest(explanation='Access token required') url = 'https://{domain}/userinfo?access_token={access_token}'.format(domain=domain, access_token=access_token) user_data_request = requests.get(url) if user_data_request.status_code != 200: raise HTTPBadRequest(explanation='Could not get user data') user_data = user_data_request.json() if user_data['email_verified'] is not True: raise HTTPBadRequest(explanation='Unverified email') user_info = _get_user_info(user_data) validate_request(context.type_info.schema, request, user_info) if request.errors: raise ValidationError(', '.join(request.errors)) result = collection_add(context, request, user_info) if not result or result['status'] != 'success': raise HTTPInternalServerError(explanation='attempt to create account was not successful') return HTTPCreated(explanation='User created')
def add_provider(request): """ Add a provider. """ store = get_db(request).get_store(StoreServices) try: new_service = Service(url=request.json["url"], name=get_any_id(request.json)) except KeyError as exc: raise OWSMissingParameterValue( "Missing json parameter '{!s}'.".format(exc), value=exc) if "public" in request.json: new_service["public"] = request.json["public"] if "auth" in request.json: new_service["auth"] = request.json["auth"] try: store.save_service(new_service) except NotImplementedError: raise OWSNotImplemented( sd.NotImplementedPostProviderResponse.description, value=new_service) return HTTPCreated(json=get_capabilities(new_service, request))
def add_provider(request): # type: (PyramidRequest) -> AnyViewResponse """ Register a new service provider. """ schema = sd.CreateProviderRequestBody() schema_ref = get_schema_ref(schema, request) try: body = schema.deserialize(request.json) except colander.Invalid as invalid: data = { "description": f"Invalid schema: [{invalid!s}]", "value": invalid.value } data.update(schema_ref) raise HTTPBadRequest(json=data) store = get_db(request).get_store(StoreServices) prov_id = get_any_id(body) try: store.fetch_by_name(prov_id) except ServiceNotFound: pass else: raise HTTPConflict(f"Provider [{prov_id}] already exists.") try: new_service = Service(url=body["url"], name=prov_id) except KeyError as exc: raise OWSMissingParameterValue(f"Missing JSON parameter '{exc!s}'.", value=exc) if "public" in body: new_service["public"] = body["public"] if "auth" in body: new_service["auth"] = body["auth"] try: # validate that metadata or any pre-fetch operation can be resolved service = new_service.summary(request, fetch=True, ignore=False) if not service: raise colander.Invalid(None, value=body) store.save_service(new_service) except NotImplementedError: # raised when supported service types / conversion raise OWSNotImplemented( sd.NotImplementedPostProviderResponse.description, value=new_service) except ServiceParsingError: # derives from HTTPUnprocessableEntity with relevant error message raise except colander.Invalid as invalid: data = { "description": "Provider properties could not be parsed correctly.", "value": invalid.value } data.update(schema_ref) raise HTTPUnprocessableEntity(json=data) data = get_schema_ref(sd.ProviderSummarySchema, request) data.update(service) return HTTPCreated(json=data)
def create_client(request): new_client = Client(name=request.json_body['name'], cpf=request.json_body['cpf'], email=request.json_body['email']) request.tm.commit() return HTTPCreated(json=ClientSchema().dump(new_client))
def create_sale(request): cart = Cart() for product in request.json.get('products'): cart.products.append(Product(**product)) request.dbsession.add(cart) request.dbsession.flush() schema = CartSchema() return HTTPCreated(json=schema.dump(cart).data)
def ban(self): try: schema = BanLinkSchema(self.request.json_body) # Can raise ModelConversionError schema.validate() # Can raise ModelValidationError self.link_svc.ban_url(self.link.url, schema.mode) return HTTPCreated("link's %s banned" % schema.mode) except (ModelConversionError, ModelValidationError), e: return HTTPBadRequest(json.dumps(e.messages))
def put_documents_bundle(request): try: request.services["create_documents_bundle"]( request.matchdict["bundle_id"], metadata=request.validated) except exceptions.AlreadyExists: return HTTPNoContent("bundle updated successfully") else: return HTTPCreated("bundle created successfully")
def __call__(self): pc = HamProductCollection.from_json(self.request.json) if pc is None: return HTTPBadRequest() pc.__parent__ = self.context if pc.title in self.context: return HTTPConflict() self.context[pc.__name__] = pc return HTTPCreated()
def add_statement_attitude(request): db_user: User = request.validated['user'] db_statement: Statement = request.validated['statement'] is_supportive = request.validated['attitude'] == Attitudes.AGREE event = UserStatementAttitude(db_user, db_statement, is_supportive) request.registry.notify(event) return HTTPCreated()
def ban_api(request): link_svc = request.find_service(name='link') try: schema = BanSchema(request.json_body) # Can raise ModelConversionError schema.validate() # Can raise ModelValidationError link_svc.ban_url(schema.url, schema.mode) return HTTPCreated("link's %s banned" % schema.mode) except (ModelConversionError, ModelValidationError), e: return HTTPBadRequest(json.dumps(e.messages))
def create_product(request): new_product = Product(name=request.json_body['name'], code=request.json_body['code'], price=request.json_body['price']) request.tm.commit() return HTTPCreated(json=ProductSchema().dump(new_product))
def get_job_submission_response(body): # type: (JSON) -> HTTPCreated """ Generates the successful response from contents returned by job submission process. .. seealso:: :func:`weaver.processes.execution.submit_job` """ return HTTPCreated(location=body["location"], json=body)
def post(self): form = NewsForm(**self.request.POST) if not form.validate(): self.request.response.status = 400 return {'form': form} obj = models.News() form.populate_obj(obj) self.db.add(obj) transaction.commit() return HTTPCreated()
def create_user(request): user = User() try: user.name = request.POST['name'] except KeyError: raise HTTPBadRequest('no name parameter') request.sqla_session.add(user) return HTTPCreated()
def get_job_submission_response(body): # type: (JSON) -> HTTPCreated """ Generates the successful response from contents returned by job submission process. .. seealso:: :func:`weaver.processes.execution.submit_job` """ body["description"] = sd.CreatedLaunchJobResponse.description body = sd.CreatedJobStatusSchema().deserialize(body) return HTTPCreated(location=body["location"], json=body)
def collection_post(self): """ Create a new flag. """ data = self.request.json_body try: name = data.pop("name") except KeyError: raise HTTPBadRequest() BinaryFlag.create(name, **data) return HTTPCreated()
def put_journal(request): """Registra um periódico a partir de dados submetidos e validados por meio do JournalSchema.""" try: request.services["create_journal"](id=request.matchdict["journal_id"], metadata=request.validated) except exceptions.AlreadyExists: return HTTPNoContent("journal already exists") except (TypeError, ValueError) as err: return HTTPBadRequest(str(err)) else: return HTTPCreated("journal created successfully")
def put(self): # we never accept id, it doesn't conform to jsonapi format data = self.request.json_body['data'] klass = get_content_factory(self.request, data['type']) add_permission = klass.type_info.add_permission if not self.request.has_permission(add_permission, self.context): raise HTTPForbidden() schema_name = _schema_factory_name(type_name=data['type']) schema_factory = self.request.registry.getUtility(ISchemaFactory, name=schema_name) schema = schema_factory(None, self.request) validated = schema.deserialize(data['attributes']) name = title_to_name(validated['title'], blacklist=self.context.keys()) new_item = self.context[name] = klass(**validated) response = HTTPCreated() response.body = render('kotti_jsonp', new_item, self.request) return response
def post(self): try: if is_cardio_activity_active( self.request.json_body['activity_id']): raise HTTPBadRequest( json={ 'message': 'There is another cardio_acitivty active' }) except KeyError as e: raise HTTPBadRequest(json={'message': str(e)}) cardio_activity = self.save(CardioActivity()) raise HTTPCreated(json=cardio_activity)
def categoryquestions(request): user = request.user if user is None: raise HTTPForbidden if request.method == 'GET': data = request.params if 'category_id' in data: categoryquestions = CategoryQuestionRecordService.by_category_id(int(data['category_id']), request) elif 'question_id' in data: categoryquestions = CategoryQuestionRecordService.by_question_id(int(data['question_id']), request) return list_to_json(categoryquestions, 'categoryquestions') elif request.method == 'POST': data = json.loads(json.dumps(request.json)) if 'category_id' and 'question_id' in data: categoryquestion = CategoryQuestion(category_id=data['category_id'], question_id=data['question_id']) with transaction.manager: zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager) request.dbsession.add(categoryquestion) transaction.commit() responseCreated = HTTPCreated() responseCreated.body = "categoryquestion created" return responseCreated
def options(request): user = request.user if user is None: raise HTTPForbidden if request.method == 'GET': data = request.params if 'option_id' in data: option = OptionRecordService.by_id(int(data['option_id']), request) return json.dumps(option.as_dict()) if 'question_id' in data: options = OptionRecordService.by_question_id(int(data['question_id']), request) return list_to_json(options, 'options') if 'correct_answer_question_id' in data: options = OptionRecordService.correct_answer_by_question_id(int(data['correct_answer_question_id']), request) return list_to_json(options, 'correctoptions') # Return all options if no parameter specified options = OptionRecordService.all(request) return list_to_json(options) if request.method == 'POST': data = json.loads(json.dumps(request.json)) if 'options' and 'question_id' in data: question_id = data['question_id'] optionsJsonArray = data['options'] for optionJson in optionsJsonArray: option = Option( option=optionJson['option'], isCorrectAnswer=optionJson['isCorrectAnswer'], question_id=question_id, ) with transaction.manager: zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager) request.dbsession.add(option) transaction.commit() responseCreated = HTTPCreated() responseCreated.body = "options created" return responseCreated
def request_account_recovery_token(self, request_data): response = HTTPCreated() token = token_hex(NUMBER_OF_TOKEN_BYTES) email_address = request_data['email_address'] self._prevent_user_enumeration() try: recipient = get_one_user_by_email_address(email_address) self._invalidate_any_current_recovery_token(recipient) self._save_recovery_token(recipient, token) SendGridClient().send_account_recovery_email(email_address, token) except NoResultFound: # To avoid user enumeration we don't indicate failure. pass raise response
def subscribe(request): # Params: # 'subscription' : <subscription name> # 'email' : <email> # 'frequency' : 'daily' or 'immediate' ensure_params(request, ('subscription', 'email', 'frequency')) subscription = request.params['subscription'] frequency = request.params['frequency'] email = request.params['email'] session = DBSession() try: eventType = session.query(EventType).filter(EventType.name==subscription).one() except NoResultFound: raise HTTPBadRequest('No subscription by that name: ' + subscription) subscriber = Subscription(email=email, type_id=eventType.id, frequency=frequency) session.add(subscriber) return HTTPCreated()
def execute_quote(request): """ Execute a quoted process. """ quote_info = get_quote_info(request).json["quote"] quote_bill_info = { "quote": quote_info.get("id"), "price": quote_info.get("price"), "currency": quote_info.get("currency") } job_resp = submit_local_job(request) job_json = job_resp.json job_id = job_json.get("jobID") user_id = str(request.authenticated_userid) store = get_db(request).get_store(StoreBills) bill = store.save_bill(Bill(user=user_id, job=job_id, **quote_bill_info)) job_json.update({"bill": bill.id}) return HTTPCreated(json=job_json)
def new_ticket(request): """ Creates a ticket with or without comment. Returns the new ticket as a serialized dict """ ticket = models.Ticket(articlepkg_id=request.POST['articlepkg_id'], author=request.POST['ticket_author'], title=request.POST['title']) if request.POST.get('message', None): ticket.comments.append( models.Comment(author=request.POST['ticket_author'], message=request.POST['message'])) try: request.db.add(ticket) transaction.commit() except: request.db.rollback() raise return HTTPCreated()
def create(self, **identifiers): document = self.document_cls(doc=self.request.POST) for k, v in self._get_ids_dict(identifiers).iteritems(): document[k] = v try: document.save() except mongokit.StructureError: log.exception( 'StructureError creating %s, POST: %s, ids: %s', self.context.resource, self.request.POST, identifiers, ) raise HTTPBadRequest() ids = [identifiers[name] for name in self.context.resource.ids[:-1]] ids.append(document._id) location = self.request.rest_resource_url(self.context.resource.name, *ids) return HTTPCreated(location=location)
def put_document(request): """Adiciona ou atualiza registro de documento. A atualização do documento é idempotente. A semântica desta view-function está definida conforme a especificação: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6 Em resumo, ``PUT /documents/:doc_id`` com o payload válido de acordo com o schema documentado, e para um ``:doc_id`` inédito, resultará no registro do documento e produzirá uma resposta com o código HTTP 201 Created. Qualquer requisição subsequente para o mesmo recurso produzirá respostas com o código HTTP 204 No Content. """ data_url = request.validated["data"] assets = { asset["asset_id"]: asset["asset_url"] for asset in request.validated.get("assets", []) } try: request.services["register_document"]( id=request.matchdict["document_id"], data_url=data_url, assets=assets) except exceptions.AlreadyExists: try: request.services["register_document_version"]( id=request.matchdict["document_id"], data_url=data_url, assets=assets) except exceptions.VersionAlreadySet as exc: LOGGER.info( 'skipping request to add version to "%s": %s', request.matchdict["document_id"], exc, ) return HTTPNoContent("document updated successfully") else: return HTTPCreated("document created successfully")
def get_job_submission_response(body, headers, error=False): # type: (JSON, AnyHeadersContainer, bool) -> Union[HTTPOk, HTTPCreated] """ Generates the successful response from contents returned by :term:`Job` submission process. If :term:`Job` already finished processing within requested ``Prefer: wait=X`` seconds delay (and if allowed by the :term:`Process` ``jobControlOptions``), return the successful status immediately instead of created status. Otherwise, return the status monitoring location of the created :term:`Job` to be monitored asynchronously. .. seealso:: :func:`weaver.processes.execution.submit_job` :func:`weaver.processes.execution.submit_job_handler` """ # convert headers to pass as list to avoid any duplicate Content-related headers # otherwise auto-added by JSON handling when provided by dict-like structure if hasattr(headers, "items"): headers = list(headers.items()) get_header("Content-Type", headers, pop=True) headers.append(("Content-Type", ContentType.APP_JSON)) status = map_status(body.get("status")) if status in JOB_STATUS_CATEGORIES[StatusCategory.FINISHED]: if error: http_class = HTTPBadRequest http_desc = sd.FailedSyncJobResponse.description else: http_class = HTTPOk http_desc = sd.CompletedJobResponse.description body = sd.CompletedJobStatusSchema().deserialize(body) body["description"] = http_desc return http_class(json=body, headerlist=headers) body["description"] = sd.CreatedLaunchJobResponse.description body = sd.CreatedJobStatusSchema().deserialize(body) return HTTPCreated(json=body, headerlist=headers)