def _checkId(self, id, allow_dup=0): PortalFolderBase.inheritedAttribute('_checkId')(self, id, allow_dup) if allow_dup: return # FIXME: needed to allow index_html for join code if id == 'index_html': return # Another exception: Must allow "syndication_information" to enable # Syndication... if id == 'syndication_information': return # This code prevents people other than the portal manager from # overriding skinned names and tools. if not getSecurityManager().checkPermission(ManagePortal, self): ob = self while ob is not None and not getattr(ob, '_isPortalRoot', False): ob = aq_parent( aq_inner(ob) ) if ob is not None: # If the portal root has a non-contentish object by this name, # don't allow an override. if (hasattr(ob, id) and id not in ob.contentIds() and # Allow root doted prefixed object name overrides not id.startswith('.')): raise BadRequest('The id "%s" is reserved.' % id) # Don't allow ids used by Method Aliases. ti = self.getTypeInfo() if ti and ti.queryMethodID(id, context=self): raise BadRequest('The id "%s" is reserved.' % id)
def manage_addTypeInformation(self, add_meta_type, id=None, typeinfo_name=None, RESPONSE=None): """ Create a TypeInformation in self. """ fti = None if typeinfo_name: info = self.listDefaultTypeInformation() # Nasty orkaround to stay backwards-compatible # This workaround will disappear in CMF 1.7 if typeinfo_name.endswith(')'): # This is a new-style name. Proceed normally. for (name, ft) in info: if name == typeinfo_name: fti = ft break else: # Attempt to work around the old way # This attempt harbors the problem that the first match on # meta_type will be used. There could potentially be more # than one TypeInformation sharing the same meta_type. warn('Please switch to the new format for typeinfo names ' '\"product_id: type_id (meta_type)\", the old ' 'spelling will disappear in CMF 1.7', DeprecationWarning, stacklevel=2) ti_prod, ti_mt = [x.strip() for x in typeinfo_name.split(':')] for name, ft in info: if ( name.startswith(ti_prod) and name.endswith('(%s)' % ti_mt) ): fti = ft break if fti is None: raise BadRequest('%s not found.' % typeinfo_name) if not id: id = fti.get('id', None) if not id: raise BadRequest('An id is required.') for mt in Products.meta_types: if mt['name'] == add_meta_type: klass = mt['instance'] break else: raise ValueError, ( 'Meta type %s is not a type class.' % add_meta_type) id = str(id) if fti is not None: fti = fti.copy() if fti.has_key('id'): del fti['id'] ob = klass(id, **fti) else: ob = klass(id) self._setObject(id, ob) if RESPONSE is not None: RESPONSE.redirect('%s/manage_main' % self.absolute_url())
def users_create(): data = request.get_json() if not "username" in data or data["username"] == "": raise BadRequest('A username must be provided') if not "password" in data or data["password"] == "": raise BadRequest('A password must be provided') if not db.users.find_one({ "username": data["username"] }) is None: raise BadRequest('Username provided already exists') db.users.insert_one({"username": data["username"], "password": data["password"]}) return Response(status=200, mimetype="application/json")
def decorated_function(*args, **kwargs): if request.authorization.username == "": raise BadRequest('Username must not be null') if request.authorization.password == "": raise BadRequest('Password must not be null') user = db.users.find_one({ "username": request.authorization.username }) if user is None: raise BadRequest('No user associated with the provided username') if user["password"] != request.authorization.password: raise BadRequest('Password is incorrect') return f(*args, **kwargs)
def setPassword(self, password, domains=None): '''Allows the authenticated member to set his/her own password. ''' registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise BadRequest(failMessage) member.setSecurityProfile(password=password, domains=domains) else: raise BadRequest('Not logged in.')
def _checkId(self, id, allow_dup=0): PortalFolderBase.inheritedAttribute('_checkId')(self, id, allow_dup) if allow_dup: return # FIXME: needed to allow index_html for join code if id == 'index_html': return # Another exception: Must allow "syndication_information" to enable # Syndication... if id == 'syndication_information': return # IDs starting with '@@' are reserved for views. if id[:2] == '@@': raise BadRequest('The id "%s" is invalid because it begins with ' '"@@".' % id) # This code prevents people other than the portal manager from # overriding skinned names and tools. if not getSecurityManager().checkPermission(ManagePortal, self): ob = aq_inner(self) while ob is not None: if ISiteRoot.providedBy(ob): break # BBB if getattr(ob, '_isPortalRoot', False): warn( "The '_isPortalRoot' marker attribute for site " "roots is deprecated and will be removed in " "CMF 2.3; please mark the root object with " "'ISiteRoot' instead.", DeprecationWarning, stacklevel=2) break ob = aq_parent(ob) if ob is not None: # If the portal root has a non-contentish object by this name, # don't allow an override. if (hasattr(ob, id) and id not in ob.contentIds() and # Allow root doted prefixed object name overrides not id.startswith('.')): raise BadRequest('The id "%s" is reserved.' % id) # Don't allow ids used by Method Aliases. ti = self.getTypeInfo() if ti and ti.queryMethodID(id, context=self): raise BadRequest('The id "%s" is reserved.' % id)
def setPassword(self, password, domains=None, REQUEST=None): '''Allows the authenticated member to set his/her own password. ''' # XXX: this method violates the rules for tools/utilities: # it depends on a non-utility tool registration = getToolByName(self, 'portal_registration', None) if not self.isAnonymousUser(): member = self.getAuthenticatedMember() if registration: failMessage = registration.testPasswordValidity(password) if failMessage is not None: raise BadRequest(failMessage) member.setSecurityProfile(password=password, domains=domains) else: raise BadRequest('Not logged in.')
def _initProperties(self, node, mode): self.context.i18n_domain = node.getAttribute('i18n:domain') for child in node.childNodes: if child.nodeName != 'property': continue obj = self.context prop_id = str(child.getAttribute('name')) prop_map = obj.propdict().get(prop_id, None) if prop_map is None: if child.hasAttribute('type'): val = child.getAttribute('select_variable') obj._setProperty(prop_id, val, child.getAttribute('type')) prop_map = obj.propdict().get(prop_id, None) else: raise ValueError('undefined property \'%s\'' % prop_id) if not 'w' in prop_map.get('mode', 'wd'): raise BadRequest('%s cannot be changed' % prop_id) elements = [] for sub in child.childNodes: if sub.nodeName == 'element': elements.append(sub.getAttribute('value')) if elements or prop_map.get('type') == 'multiple selection': prop_value = tuple(elements) or () elif prop_map.get('type') == 'boolean': prop_value = self._getNodeTextBoolean(child) else: # if we pass a *string* to _updateProperty, all other values # are converted to the right type prop_value = self._getNodeText(child) obj._updateProperty(prop_id, prop_value)
def initProperty(self, obj, p_info): prop_id = p_info['id'] prop_map = obj.propdict().get(prop_id, None) if prop_map is None: type = p_info.get('type', None) if type: val = p_info.get('select_variable', '') obj._setProperty(prop_id, val, type) prop_map = obj.propdict().get(prop_id, None) else: raise ValueError('undefined property \'%s\'' % prop_id) if not 'w' in prop_map.get('mode', 'wd'): raise BadRequest('%s cannot be changed' % prop_id) if prop_map.get('type') == 'multiple selection': prop_value = p_info['elements'] or () else: # if we pass a *string* to _updateProperty, all other values # are converted to the right type prop_value = p_info['elements'] or str(p_info['value']) obj._updateProperty(prop_id, prop_value)
def initProperty(self, obj, p_info): warn( 'CMFSetup.utils including ImportConfiguratorBase is deprecated. ' 'Please use NodeAdapterBase from GenericSetup.utils instead.', DeprecationWarning) prop_id = p_info['id'] prop_map = obj.propdict().get(prop_id, None) if prop_map is None: type = p_info.get('type', None) if type: val = p_info.get('select_variable', '') obj._setProperty(prop_id, val, type) prop_map = obj.propdict().get(prop_id, None) else: raise ValueError('undefined property \'%s\'' % prop_id) if not 'w' in prop_map.get('mode', 'wd'): raise BadRequest('%s cannot be changed' % prop_id) if prop_map.get('type') == 'multiple selection': prop_value = p_info['elements'] or () elif prop_map.get('type') == 'boolean': # Make sure '0' is imported as False prop_value = str(p_info['value']) if prop_value == '0': prop_value = '' else: # if we pass a *string* to _updateProperty, all other values # are converted to the right type prop_value = p_info['elements'] or str(p_info['value']) obj._updateProperty(prop_id, prop_value)
def _checkId(self, id, allow_dup=0): PortalFolder.inheritedAttribute('_checkId')(self, id, allow_dup) if allow_dup: return # FIXME: needed to allow index_html for join code if id == 'index_html': return # Another exception: Must allow "syndication_information" to enable # Syndication... if id == 'syndication_information': return # This code prevents people other than the portal manager from # overriding skinned names and tools. if not getSecurityManager().checkPermission(ManagePortal, self): ob = self while ob is not None and not getattr(ob, '_isPortalRoot', False): ob = aq_parent(aq_inner(ob)) if ob is not None: # If the portal root has a non-contentish object by this name, # don't allow an override. if hasattr(ob, id) and id not in ob.contentIds(): raise BadRequest('The id "%s" is reserved.' % id)
def scad_api(): datastring = request.data.decode().strip() try: data = json.loads(datastring) except ValueError: error = BadRequest( 'Invalid JSON given in request: {data}'.format(data=datastring)) LOG.info('BadRequest received with following data: {data}'.format( data=request.data)) return make_response(jsonify(error.to_dict()), error.status_code) return jsonify( classifier.match_authors(data['pub_1'], data['ai_1'], data['pub_2'], data['ai_2'], params=data['params']))
def _initProperties(self, node): obj = self.context if node.hasAttribute('i18n:domain'): i18n_domain = str(node.getAttribute('i18n:domain')) obj._updateProperty('i18n_domain', i18n_domain) for child in node.childNodes: if child.nodeName != 'property': continue prop_id = str(child.getAttribute('name')) prop_map = obj.propdict().get(prop_id, None) if prop_map is None: if child.hasAttribute('type'): val = str(child.getAttribute('select_variable')) prop_type = str(child.getAttribute('type')) obj._setProperty(prop_id, val, prop_type) prop_map = obj.propdict().get(prop_id, None) else: raise ValueError("undefined property '%s'" % prop_id) if not 'w' in prop_map.get('mode', 'wd'): raise BadRequest('%s cannot be changed' % prop_id) new_elements = [] remove_elements = [] for sub in child.childNodes: if sub.nodeName == 'element': value = sub.getAttribute('value').encode(self._encoding) if self._convertToBoolean( sub.getAttribute('remove') or 'False'): remove_elements.append(value) if value in new_elements: new_elements.remove(value) else: new_elements.append(value) if value in remove_elements: remove_elements.remove(value) if new_elements or prop_map.get('type') == 'multiple selection': prop_value = tuple(new_elements) or () elif prop_map.get('type') == 'boolean': prop_value = self._convertToBoolean(self._getNodeText(child)) else: # if we pass a *string* to _updateProperty, all other values # are converted to the right type prop_value = self._getNodeText(child).encode(self._encoding) if not self._convertToBoolean( child.getAttribute('purge') or 'True'): # If the purge attribute is False, merge sequences prop = obj.getProperty(prop_id) if isinstance(prop, (tuple, list)): prop_value = (tuple([ p for p in prop if p not in prop_value and p not in remove_elements ]) + tuple(prop_value)) obj._updateProperty(prop_id, prop_value)
def on_exhausted(self): """This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. """ if self.silent: return '' from exceptions import BadRequest raise BadRequest('input stream exhausted')
async def insert_object(conn, obj, values): try: result = await conn.execute( insert(obj).values(**values).returning(*obj.__table__.columns)) record = await result.first() except Exception as e: raise BadRequest(str(e)) return record
def image_result(): if request.args.get('imageId') == "" or request.args.get('imageId') == None: raise BadRequest('imageId must be supplied in the request') image = db.images.find_one({"id": request.args.get('imageId')}) if image == None: raise BadRequest('The supplied imageId ' + request.args.get('imageId') + ' could not be found') image_status = ImageStatus(int(image["status"])) response_message = "" if image_status == ImageStatus.RUNNING: return Response(response="Image is still being processed", status=200, mimetype="application/json") if image_status == ImageStatus.CANCELED: return Response(response="Failed to process image, please re-upload to try again", status=200, mimetype="application/json") else: response_pickled = jsonpickle.encode({"fakeChance": image["fakeChance"]}) return Response(response=response_pickled, status=200, mimetype="application/json")
def partial_update(self, request, key=None): try: obj = key.get() obj.update(self.get_body()) obj.put() self.post_save(obj, created=False) return JsonResponse(data=self.get_serializer()(obj).data) except Exception as err: raise BadRequest(str(err))
def setProperties(self, properties=None, **kw): '''Allows the authenticated member to set his/her own properties. Accepts either keyword arguments or a mapping for the "properties" argument. ''' if properties is None: properties = kw membership = getToolByName(self, 'portal_membership') registration = getToolByName(self, 'portal_registration', None) if not membership.isAnonymousUser(): member = membership.getAuthenticatedMember() if registration: failMessage = registration.testPropertiesValidity(properties, member) if failMessage is not None: raise BadRequest(failMessage) member.setMemberProperties(properties) else: raise BadRequest('Not logged in.')
async def delete_object_by_id(conn, obj, pk): try: result = await conn.execute( delete(obj).where(obj.id == pk).returning(*obj.__table__.columns)) record = await result.first() except CompileError as e: raise BadRequest(str(e)) if not record: raise RecordNotFound(f'{obj.__name__} with id={pk} is not found') return record
def post(self, id): user_id = get_jwt_identity() data = request.get_json() action = data.get('action') if action == self.JOIN_ACTION: return self.course_service.assign_user_to_course(user_id, course_id=id) elif action == self.LEAVE_ACTION: return self.course_service.remove_user_from_course(user_id, course_id=id) else: raise BadRequest("'{}' action is not valid".format(action))
async def update_object_by_user_id(conn, obj, user_id, values): try: result = await conn.execute( update(obj).values(**values).where( obj.user_id == user_id).returning(*obj.__table__.columns)) record = await result.first() except CompileError as e: raise BadRequest(str(e)) if not record: raise RecordNotFound( f'{obj.__name__} with user_id={user_id} is not found') return record
def createShortenedUrl(): """ Endpoint that accepts a URL and an optional slug and return a shortened version """ data = request.get_json(force=True) # checking the validity of the request body if not validateRequestBody(data): raise BadRequest('Request payload is malformed') # validate the provided slug is not in use if 'slug' in data: slug = data['slug'] if ShortenedUrl.query.get(slug) != None: raise BadRequest('Slug is not unique') else: slug = uuid.uuid4().hex[:6].lower() # validate the generated slug is not in use while ShortenedUrl.query.get(slug) != None: slug = uuid.uuid4().hex[:6].lower() url = data['url'] response = Response() returnObj = { 'url': url, 'slug': slug, 'shortened_url': '{}r/{}'.format(request.url_root, slug) } response.headers['location'] = '/r/{}'.format(slug) response.headers['Content-Type'] = 'application/json' response.status_code = 201 response.data = json.dumps(returnObj) # create object and write to db shortenedUrl = ShortenedUrl(slug=slug, url=url) db.session.add(shortenedUrl) db.session.commit() return response
def manage_addTypeInformation(self, add_meta_type, id=None, typeinfo_name=None, RESPONSE=None): """ Create a TypeInformation in self. """ fti = None if typeinfo_name: info = self.listDefaultTypeInformation() for (name, ft) in info: if name == typeinfo_name: fti = ft break if fti is None: raise BadRequest('%s not found.' % typeinfo_name) if not id: id = fti.get('id', None) if not id: raise BadRequest('An id is required.') for mt in typeClasses: if mt['name'] == add_meta_type: klass = mt['class'] break else: raise ValueError, ('Meta type %s is not a type class.' % add_meta_type) id = str(id) if fti is not None: fti = fti.copy() if fti.has_key('id'): del fti['id'] ob = klass(id, **fti) else: ob = klass(id) self._setObject(id, ob) if RESPONSE is not None: RESPONSE.redirect('%s/manage_main' % self.absolute_url())
def modify_student(id): if (not request.json.get('first_name')) or ( not request.json.get('last_name')): raise BadRequest('first_name and last_name required.', 400) try: student = Student.query.get(id) fname = request.json['first_name'] lname = request.json['last_name'] student.first_name = fname student.last_name = lname db.session.commit() except sqlalchemy.orm.exc.UnmappedInstanceError: raise NotFoundError('UnmappedInstanceError occured', 404)
def trade_stock( quantity, direction, exchange=TEST_EXCHANGE, stock=TEST_STOCK, price=None, order_type=MARKET_ORDER, ): ''' :param quantity: the number of shares to buy or sell :param direction: either ``'buy'`` or ``'sell'`` :param exchange: a string with the exchange name (case sesitive). \ Defaults to :py:data:`TEST_EXCHANGE`. :param stock: a string with the stock name (case sensitive) which must be traded in the \ exchange. Defaults to :py:data:`TEST_STOCK`. :param price: The price to buy at. Defaults to ``None``. If none or unspecified, the order \ becomes a market order. :param order_type: The type of order. Should be one of :py:data:`MARKET_ORDER`, \ :py:data:`LIMIT_ORDER`, :py:data:`FILL_OR_KILL_ORDER`, :py:data:`IMMEDIATE_OR_CANCEL`. \ Defaults to :py:data:`MARKET_ORDER` :rtype: :py:class:`Order` :return: The deserialized json response as a schematics object Executes a buy or sell order and returns the result. ''' if price is None: order_type = MARKET_ORDER price = 0 else: price = int(price * 100) sc, json = _make_request( path='/venues/{}/stocks/{}/orders'.format(exchange, stock), type_='post', data={ 'account': config.get('account'), 'venue': exchange, 'stock': stock, 'price': price, 'qty': quantity, 'direction': direction, 'orderType': order_type, }, ) if sc != 200: raise BadRequest(sc, json) return Order(json, strict=False)
def add_student(): if (not request.json.get('first_name')) or ( not request.json.get('last_name')): raise BadRequest('first_name and last_name required.', 400) fname = request.json['first_name'] lname = request.json['last_name'] new_student = Student(fname, lname) db.session.add(new_student) db.session.commit() return student_schema.jsonify(new_student)
def post(self): user_id = get_jwt_identity() data = request.get_json() pr_id = data.get('id') action = data.get('action') if self.user_service.check_admin(user_id): if action == self.ACCEPT_ACTION: return self.problem_service.accept_publish_request(pr_id) elif action == self.DECLINE_ACTION: return self.problem_service.decline_publish_request(pr_id) else: raise BadRequest("'{}' action is not valid".format(action)) else: raise Unauthorized("User with id {} is not admin".format(user_id))
def get_orderbook(exchange=TEST_EXCHANGE, stock=TEST_STOCK): ''' :param exchange: a string with the exchange name (case sesitive). \ Defaults to :py:data:`TEST_EXCHANGE`. :param stock: a string with the stock name (case sensitive) which must be traded in the \ exchange. Defaults to :py:data:`TEST_STOCK`. :rtype: :py:class:`Orderbook` :return: The deserialized json response as a schematics object Retrieves the orderbook for a given stock on an exchange. ''' sc, json = _make_request('/venues/{}/stocks/{}'.format(exchange, stock)) if sc == 404: raise BadRequest(sc, json) return Orderbook(json, strict=False)
def _checkId(self, id, allow_dup=0): PortalFolder.inheritedAttribute('_checkId')(self, id, allow_dup) # This method prevents people other than the portal manager # from overriding skinned names. if not allow_dup: if not getSecurityManager().checkPermission(ManagePortal, self): ob = self while ob is not None and not getattr(ob, '_isPortalRoot', 0): ob = aq_parent(aq_inner(ob)) if ob is not None: # If the portal root has an object by this name, # don't allow an override. # FIXME: needed to allow index_html for join code if hasattr(ob, id) and id != 'index_html': raise BadRequest('The id "%s" is reserved.' % id)
def get_quote(exchange=TEST_EXCHANGE, stock=TEST_STOCK): ''' :param exchange: a string with the exchange name (case sesitive). \ Defaults to :py:data:`TEST_EXCHANGE`. :param stock: a string with the stock name (case sensitive) which must be traded in the \ exchange. Defaults to :py:data:`TEST_STOCK`. :rtype: :py:class:`Quote` :return: The deserialized json response as a schematics object Gets a quote of the latest known order for a given stock on an exchange. ''' sc, json = _make_request('/venues/{}/stocks/{}/quote'.format( exchange, stock)) if sc == 404: raise BadRequest(sc, json) return Quote(json)