def GETorHEAD(self, req, stats_type): """Handler for HTTP GET/HEAD requests.""" start_time = time.time() partition, nodes = self.app.account_ring.get_nodes(self.account_name) shuffle(nodes) resp = self.GETorHEAD_base(req, _('Account'), partition, nodes, req.path_info.rstrip('/'), len(nodes)) if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate: if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH) self.app.logger.timing_since( '%s.timing' % (stats_type,), start_time) return resp headers = {'X-Timestamp': normalize_timestamp(time.time()), 'X-Trans-Id': self.trans_id, 'Connection': 'close'} resp = self.make_requests( Request.blank('/v1/' + self.account_name), self.app.account_ring, partition, 'PUT', '/' + self.account_name, [headers] * len(nodes)) if not is_success(resp.status_int): self.app.logger.warning('Could not autocreate account %r' % self.account_name) return resp resp = self.GETorHEAD_base(req, _('Account'), partition, nodes, req.path_info.rstrip('/'), len(nodes)) self.app.logger.timing_since('%s.timing' % (stats_type,), start_time) return resp
def GETorHEAD(self, req): """Handler for HTTP GET/HEAD requests.""" partition, nodes = self.app.account_ring.get_nodes(self.account_name) shuffle(nodes) resp = self.GETorHEAD_base(req, _("Account"), partition, nodes, req.path_info.rstrip("/"), len(nodes)) if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate: if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = "Account name length of %d longer than %d" % ( len(self.account_name), MAX_ACCOUNT_NAME_LENGTH, ) return resp headers = { "X-Timestamp": normalize_timestamp(time.time()), "X-Trans-Id": self.trans_id, "Connection": "close", } resp = self.make_requests( Request.blank("/v1/" + self.account_name), self.app.account_ring, partition, "PUT", "/" + self.account_name, [headers] * len(nodes), ) if not is_success(resp.status_int): self.app.logger.warning("Could not autocreate account %r" % self.account_name) return resp resp = self.GETorHEAD_base(req, _("Account"), partition, nodes, req.path_info.rstrip("/"), len(nodes)) return resp
def PUT(self, req): """HTTP PUT request handler.""" start_time = time.time() if not self.app.allow_account_management: self.app.logger.timing_since('PUT.timing', start_time) return HTTPMethodNotAllowed(request=req) error_response = check_metadata(req, 'account') if error_response: self.app.logger.increment('errors') return error_response if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH) self.app.logger.increment('errors') return resp account_partition, accounts = \ self.app.account_ring.get_nodes(self.account_name) headers = {'X-Timestamp': normalize_timestamp(time.time()), 'x-trans-id': self.trans_id, 'Connection': 'close'} self.transfer_headers(req.headers, headers) if self.app.memcache: self.app.memcache.delete('account%s' % req.path_info.rstrip('/')) resp = self.make_requests(req, self.app.account_ring, account_partition, 'PUT', req.path_info, [headers] * len(accounts)) self.app.logger.timing_since('PUT.timing', start_time) return resp
def POST(self, req): """HTTP POST request handler.""" error_response = check_metadata(req, "account") if error_response: return error_response account_partition, accounts = self.app.account_ring.get_nodes(self.account_name) headers = {"X-Timestamp": normalize_timestamp(time.time()), "X-Trans-Id": self.trans_id, "Connection": "close"} self.transfer_headers(req.headers, headers) if self.app.memcache: self.app.memcache.delete("account%s" % req.path_info.rstrip("/")) resp = self.make_requests( req, self.app.account_ring, account_partition, "POST", req.path_info, [headers] * len(accounts) ) if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate: if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = "Account name length of %d longer than %d" % ( len(self.account_name), MAX_ACCOUNT_NAME_LENGTH, ) return resp resp = self.make_requests( Request.blank("/v1/" + self.account_name), self.app.account_ring, account_partition, "PUT", "/" + self.account_name, [headers] * len(accounts), ) if not is_success(resp.status_int): self.app.logger.warning("Could not autocreate account %r" % self.account_name) return resp return resp
def POST(self, req): """HTTP POST request handler.""" start_time = time.time() error_response = check_metadata(req, 'account') if error_response: self.app.logger.increment('errors') return error_response account_partition, accounts = \ self.app.account_ring.get_nodes(self.account_name) headers = {'X-Timestamp': normalize_timestamp(time.time()), 'X-Trans-Id': self.trans_id, 'Connection': 'close'} self.transfer_headers(req.headers, headers) if self.app.memcache: self.app.memcache.delete('account%s' % req.path_info.rstrip('/')) resp = self.make_requests(req, self.app.account_ring, account_partition, 'POST', req.path_info, [headers] * len(accounts)) if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate: if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Account name length of %d longer than %d' % \ (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH) self.app.logger.increment('errors') return resp resp = self.make_requests( Request.blank('/v1/' + self.account_name), self.app.account_ring, account_partition, 'PUT', '/' + self.account_name, [headers] * len(accounts)) if not is_success(resp.status_int): self.app.logger.warning('Could not autocreate account %r' % self.account_name) return resp self.app.logger.timing_since('POST.timing', start_time) return resp
def __init__(self, error_name): HTTPBadRequest.__init__(self) self.error_data = { 'reason': error_name, 'explanation': error_list[error_name], } self.explanation = error_list[error_name]
def HEAD(self, request): """Handle HTTP HEAD requests for the Swift Object Server.""" try: device, partition, account, container, obj = \ split_path(unquote(request.path), 5, 5, True) except ValueError, err: resp = HTTPBadRequest(request=request) resp.content_type = 'text/plain' resp.body = str(err) return resp
def HEAD(self, request): """Handle HTTP HEAD requests for the Swift Object Server.""" start_time = time.time() try: device, partition, account, container, obj = split_path(unquote(request.path), 5, 5, True) validate_device_partition(device, partition) except ValueError, err: self.logger.increment("HEAD.errors") resp = HTTPBadRequest(request=request) resp.content_type = "text/plain" resp.body = str(err) return resp
def PUT(self, req): """HTTP PUT request handler.""" start_time = time.time() error_response = \ self.clean_acls(req) or check_metadata(req, 'container') if error_response: self.app.logger.increment('errors') return error_response if len(self.container_name) > MAX_CONTAINER_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = 'Container name length of %d longer than %d' % \ (len(self.container_name), MAX_CONTAINER_NAME_LENGTH) self.app.logger.increment('errors') return resp account_partition, accounts, container_count = \ self.account_info(self.account_name, autocreate=self.app.account_autocreate) if self.app.max_containers_per_account > 0 and \ container_count >= self.app.max_containers_per_account and \ self.account_name not in self.app.max_containers_whitelist: resp = HTTPForbidden(request=req) resp.body = 'Reached container limit of %s' % \ self.app.max_containers_per_account return resp if not accounts: self.app.logger.timing_since('PUT.timing', start_time) return HTTPNotFound(request=req) container_partition, containers = self.app.container_ring.get_nodes( self.account_name, self.container_name) headers = [] for account in accounts: nheaders = {'X-Timestamp': normalize_timestamp(time.time()), 'x-trans-id': self.trans_id, 'X-Account-Host': '%(ip)s:%(port)s' % account, 'X-Account-Partition': account_partition, 'X-Account-Device': account['device'], 'Connection': 'close'} self.transfer_headers(req.headers, nheaders) headers.append(nheaders) if self.app.memcache: cache_key = get_container_memcache_key(self.account_name, self.container_name) self.app.memcache.delete(cache_key) resp = self.make_requests(req, self.app.container_ring, container_partition, 'PUT', req.path_info, headers) self.app.logger.timing_since('PUT.timing', start_time) return resp
def GET_scopes(self, scope_str): """Retrieve descriptions of reddit's OAuth2 scopes. If no scopes are given, information on all scopes are returned. Invalid scope(s) will result in a 400 error with body that indicates the invalid scope(s). """ scopes = OAuth2Scope(scope_str or self.THREE_SIXTY) if scope_str and not scopes.is_valid(): invalid = [s for s in scopes.scopes if s not in scopes.scope_info] error = {"error": "invalid_scopes", "invalid_scopes": invalid} http_err = HTTPBadRequest() http_err.error_data = error abort(http_err) return self.api_wrapper({k: v for k, v in scopes.details() if k})
def PUT(self, req): """HTTP PUT request handler.""" if not self.app.allow_account_management: return HTTPMethodNotAllowed(request=req) error_response = check_metadata(req, "account") if error_response: return error_response if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH: resp = HTTPBadRequest(request=req) resp.body = "Account name length of %d longer than %d" % (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH) return resp account_partition, accounts = self.app.account_ring.get_nodes(self.account_name) headers = {"X-Timestamp": normalize_timestamp(time.time()), "x-trans-id": self.trans_id, "Connection": "close"} self.transfer_headers(req.headers, headers) if self.app.memcache: self.app.memcache.delete("account%s" % req.path_info.rstrip("/")) resp = self.make_requests( req, self.app.account_ring, account_partition, "PUT", req.path_info, [headers] * len(accounts) ) return resp
def handle_upgrade(self): """Completes the upgrade request sent by the browser Sends the headers required to set up to websocket connection back to the browser and then hands off to :meth:`handle_websocket`. See [websocket_protocol]_ :returns: :exc:`webob.exc.HTTPBadRequest` if handshake fails """ try: handshake_reply = websocket_handshake(self.request.headers) except HandShakeFailed: _, val, _ = sys.exc_info() response = HTTPBadRequest(headers=dict(Connection='Close')) response.body = 'Upgrade negotiation failed:\n\t%s\n%s' % \ (val, self.request.headers) return response sock = self.environ['eventlet.input'].get_socket() sock.sendall(handshake_reply) return self.handle_websocket(WebSocket(self.sock, self.environ))
def _activate(self, req, image_id, location, location_metadata=None, from_state=None): """ Sets the image status to `active` and the image's location attribute. :param req: The WSGI/Webob Request object :param image_id: Opaque image identifier :param location: Location of where Glance stored this image :param location_metadata: a dictionary of storage specific information """ image_meta = {} image_meta['location'] = location image_meta['status'] = 'active' if location_metadata: image_meta['location_data'] = [{ 'url': location, 'metadata': location_metadata }] try: s = from_state image_meta_data = registry.update_image_metadata(req.context, image_id, image_meta, from_state=s) self.notifier.info("image.activate", redact_loc(image_meta_data)) self.notifier.info("image.update", redact_loc(image_meta_data)) return image_meta_data except exception.Duplicate: with excutils.save_and_reraise_exception(): # Delete image data since it has been supersceded by another # upload and re-raise. LOG.debug( _("duplicate operation - deleting image data for " " %(id)s (location:%(location)s)") % { 'id': image_id, 'location': image_meta['location'] }) upload_utils.initiate_deletion(req, image_meta['location'], image_id, CONF.delayed_delete) except exception.Invalid as e: msg = _("Failed to activate image. Got error: %(e)s") % {'e': e} LOG.debug(msg) raise HTTPBadRequest(explanation=msg, request=req, content_type="text/plain")
def _reserve(self, req, image_meta): """ Adds the image metadata to the registry and assigns an image identifier if one is not supplied in the request headers. Sets the image's status to `queued`. :param req: The WSGI/Webob Request object :param id: The opaque image identifier :param image_meta: The image metadata :raises HTTPConflict if image already exists :raises HTTPBadRequest if image metadata is not valid """ location = self._external_source(image_meta, req) image_meta['status'] = ('active' if image_meta.get('size') == 0 else 'queued') if location: store = get_store_from_location(location) # check the store exists before we hit the registry, but we # don't actually care what it is at this point self.get_store_or_400(req, store) # retrieve the image size from remote store (if not provided) image_meta['size'] = self._get_size(req.context, image_meta, location) else: # Ensure that the size attribute is set to zero for directly # uploadable images (if not provided). The size will be set # to a non-zero value during upload image_meta['size'] = image_meta.get('size', 0) try: image_meta = registry.add_image_metadata(req.context, image_meta) self.notifier.info("image.create", redact_loc(image_meta)) return image_meta except exception.Duplicate: msg = (_("An image with identifier %s already exists") % image_meta['id']) LOG.debug(msg) raise HTTPConflict(explanation=msg, request=req, content_type="text/plain") except exception.Invalid, e: msg = (_("Failed to reserve image. Got error: %(e)s") % locals()) for line in msg.split('\n'): LOG.debug(line) raise HTTPBadRequest(explanation=msg, request=req, content_type="text/plain")
def submit_draft(self: Proposition, request): external_draft_info = self.external_fields.get("external_draft", {}) importer_name = external_draft_info.get("importer") import_info = external_draft_info.get("import_info") if external_draft_info: if not importer_name: raise HTTPBadRequest( "should import from external system but importer name is missing" ) if not import_info: raise HTTPBadRequest( "should import from external system but import info is missing" ) # pre-fill new proposition form from a URL returning data formatted as `from_format` # 'for supported formats, see 'PROPOSITION_IMPORT_HANDLERS' importer_config = getattr(request.app.settings.importer, importer_name) if importer_config is None: raise ValueError("unsupported proposition source: " + importer_name) import_schema = importer_config['schema'] import_handler = PROPOSITION_IMPORT_HANDLERS.get(import_schema) if import_handler is None: raise ValueError("unsupported proposition import schema: " + import_schema) form_data = import_handler(importer_config, import_info) else: form_data = {} form = PropositionSubmitDraftForm(request, request.link(self, 'submit_draft_post')) return PropositionSubmitDraftCell(self, request, form, form_data).show()
def mkdir(self): """ Create a remote file """ cred = _get_credentials() try: if request.method == 'POST': if request.content_type == 'application/json': unencoded_body = request.body else: unencoded_body = urllib.unquote_plus(request.body) else: raise HTTPBadRequest('Unsupported method %s' % request.method) mkdir_dict = json.loads(unencoded_body) m = Gfal2Wrapper(cred, _mkdir_impl) try: return m(mkdir_dict) except Gfal2Error, e: _http_error_from_gfal2_error(e) except ValueError, e: raise HTTPBadRequest('Invalid value within the request: %s' % str(e))
def _validate_source(source, req): """ External sources (as specified via the location or copy-from headers) are supported only over non-local store types, i.e. S3, Swift, HTTP. Note the absence of file:// for security reasons, see LP bug #942118. If the above constraint is violated, we reject with 400 "Bad Request". """ if source: for scheme in ['s3', 'swift', 'http']: if source.lower().startswith(scheme): return source msg = _("External sourcing not supported for store %s") % source logger.error(msg) raise HTTPBadRequest(msg, request=req, content_type="text/plain")
def __call__(self, req): if req.content_type != 'application/json': return HTTPBadRequest(message='Only application/json was suppored') action_args = req.environ['wsgiorg.routing_args'][1] method = getattr(self, action_args['action']) action_args.pop('action') action_args.pop('controller') try: resp = method(req, **action_args) except TypeError: action_args['body'] = req.body resp = method(req, **action_args) return resp
def push_draft(self: Proposition, request: Request): """XXX: Supports only Discourse for now. A generalized approach like for proposition importers would be nice. """ if 'push_draft' not in request.POST: raise HTTPBadRequest() exporter_name = self.ballot.area.department.exporter_settings.get( 'exporter_name') if exporter_name is None: raise HTTPBadRequest() exporter_config = {**getattr(request.app.settings.exporter, exporter_name)} external_content_template = customizable_text( request, 'push_draft_external_template') portal_content_template = customizable_text(request, 'push_draft_portal_template') self_link = request.link(self) push_draft_to_discourse(exporter_config, external_content_template, portal_content_template, self, self_link) return redirect(self_link)
def HEAD(self, req): """Handle HTTP HEAD request.""" # TODO(refactor): The account server used to provide a 'account and # container existence check all-in-one' call by doing a HEAD with a # container path. However, container existence is now checked with the # container servers directly so this is no longer needed. We should # refactor out the container existence check here and retest # everything. try: drive, part, account, container = split_path(unquote(req.path), 3, 4) except ValueError, err: return HTTPBadRequest(body=str(err), content_type='text/plain', request=req)
def _validate_auth_url(self, env, start_response, auth_url): """Validate auth_url to ensure it can be used.""" if not auth_url: resp = HTTPBadRequest( _('Request missing required header ' 'X-Auth-Url')) return resp(env, start_response) allowed = cfg.CONF.auth_password.allowed_auth_uris if auth_url not in allowed: resp = HTTPUnauthorized( _('Header X-Auth-Url "%s" not an allowed ' 'endpoint') % auth_url) return resp(env, start_response) return None
def handle_upgrade(self): """Completes the upgrade request sent by the browser Sends the headers required to set up to websocket connection back to the browser and then hands off to :meth:`handle_websocket`. See: http://en.wikipedia.org/wiki/Web_Sockets#WebSocket_Protocol_Handshake """ if not (self.environ.get('HTTP_CONNECTION') == 'Upgrade' and self.environ.get('HTTP_UPGRADE') == 'WebSocket'): response = HTTPBadRequest(headers=dict(Connection='Close')) response.body = 'Bad:\n%s' % pformat(self.environ) return response sock = self.environ['eventlet.input'].get_socket() handshake_reply = ("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "WebSocket-Origin: %s\r\n" "WebSocket-Location: ws://%s%s\r\n\r\n" % ( self.request.host_url, self.request.host, self.request.path_info)) sock.sendall(handshake_reply) websocket = WebSocket(self.sock, self.environ) return self.handle_websocket(websocket)
def create(self, req, lock): try: timestamp = req.params['timestamp'] except KeyError: raise HTTPBadRequest("Most specify timestamp") if '.' in self.id: raise HTTPPreconditionFailed("backup id cannot contain '.'") try: snapshot = self.helper.volumes.create_snapshot( self.volume_id, self.id, timestamp) except NotFound, e: raise HTTPNotFound(str(e))
def REPLICATE(self, req): """ Handle HTTP REPLICATE request (json-encoded RPC calls for replication.) """ start_time = time.time() try: post_args = split_path(unquote(req.path), 3) drive, partition, hash = post_args validate_device_partition(drive, partition) except ValueError, err: self.logger.increment('REPLICATE.errors') return HTTPBadRequest(body=str(err), content_type='text/plain', request=req)
def update(self, notification_id): try: no = Notification.get(notification_id) owner = all(un.user_id == request.authuser.user_id for un in no.notifications_to_users) if h.HasPermissionAny('hg.admin')() or owner: # deletes only notification2user NotificationModel().mark_read(request.authuser.user_id, no) Session().commit() return 'ok' except Exception: Session().rollback() log.error(traceback.format_exc()) raise HTTPBadRequest()
def __call__(self, env, start_response): if env['REQUEST_METHOD'] == 'GET' or env['REQUEST_METHOD'] == 'HEAD': if self.status == 200: if 'HTTP_RANGE' in env: resp = Response(body=self.object_body, conditional_response=True) return resp(env, start_response) start_response(Response().status, self.response_headers.items()) if env['REQUEST_METHOD'] == 'GET': return self.object_body elif self.status == 401: start_response(HTTPUnauthorized().status, []) elif self.status == 404: start_response(HTTPNotFound().status, []) else: start_response(HTTPBadRequest().status, []) elif env['REQUEST_METHOD'] == 'PUT': if self.status == 201: start_response(HTTPCreated().status, [('etag', self.response_headers['etag'])]) elif self.status == 401: start_response(HTTPUnauthorized().status, []) elif self.status == 404: start_response(HTTPNotFound().status, []) else: start_response(HTTPBadRequest().status, []) elif env['REQUEST_METHOD'] == 'DELETE': if self.status == 204: start_response(HTTPNoContent().status, []) elif self.status == 401: start_response(HTTPUnauthorized().status, []) elif self.status == 404: start_response(HTTPNotFound().status, []) else: start_response(HTTPBadRequest().status, []) return []
def _deserialize(self, request): result = {} try: result['image_meta'] = utils.get_image_meta_from_headers(request) except exception.Invalid: image_size_str = request.headers['x-image-meta-size'] msg = _("Incoming image size of %s was not convertible to " "an integer.") % image_size_str raise HTTPBadRequest(explanation=msg, request=request) image_meta = result['image_meta'] image_meta = validate_image_meta(request, image_meta) if request.content_length: image_size = request.content_length elif 'size' in image_meta: image_size = image_meta['size'] else: image_size = None data = request.body_file if self.has_body(request) else None if image_size is None and data is not None: data = utils.LimitingReader(data, CONF.image_size_cap) #NOTE(bcwaldon): this is a hack to make sure the downstream code # gets the correct image data request.body_file = data elif image_size > CONF.image_size_cap: max_image_size = CONF.image_size_cap msg = _("Denying attempt to upload image larger than %d bytes.") LOG.warn(msg % max_image_size) raise HTTPBadRequest(explanation=msg % max_image_size, request=request) result['image_data'] = data return result
def login(ctx, request): try: payload = request.json() mail = payload['mail'] password = payload['password'] except Exception as e: raise HTTPBadRequest(e) user = User.query.filter(User.email == mail).first_or_404('user {} not exist'.format(mail)) if bcrypt.hashpw(password.encode(), user.password.encode()) == user.password.encode(): key = ctx.config.get_string('auth.key') exp = datetime.datetime.utcnow() + datetime.timedelta(hours=ctx.config.get_int('auth.exp')) token = jwt.encode({'user': user.id, 'exp': exp}, key, 'HS512').decode() return jsonify(code=200, token=token) raise HTTPUnauthorized()
def create(self, request, appstruct): area = request.q(SubjectArea).get(appstruct['area_id']) if appstruct['area_id'] else None voting_phase = request.q(VotingPhase).get(appstruct['voting_id']) if appstruct['voting_id'] else None department_id = None if area and voting_phase: if area.department_id != voting_phase.department_id: return HTTPBadRequest("area doesn't belong to the same department as the voting phase") department_id = area.department_id elif area: department_id = area.department_id elif voting_phase: department_id = voting_phase.department_id if department_id and not request.identity.has_global_admin_permissions: department_allowed = [d for d in request.current_user.managed_departments if d.id == department_id] if not department_allowed: return HTTPBadRequest("department not allowed") ballot = Ballot(**appstruct) request.db_session.add(ballot) request.db_session.flush() return redirect(request.link(ballot))
def content_range(request): """ Helper for parsing Content-Range header in request. WebOb support parsing of Content-Range header, but do not expose this header in webob.Request. """ try: header = request.headers["content-range"] except KeyError: return webob.byterange.ContentRange(None, None, None) content_range = webob.byterange.ContentRange.parse(header) if content_range is None: raise HTTPBadRequest("Invalid content-range: %r" % header) return content_range
def create_voting(self, request): if self.status != VotingStatus.SCHEDULED: raise HTTPBadRequest("Voting phase must be in scheduled state") voting_module_name = request.POST.get("create_voting") try: module_config = prepare_module_config(request.app, self.department, voting_module_name) except InvalidVotingModule as e: raise HTTPBadRequest(e.args[0]) with start_action(action_type="create_vvvote_election_config", module_config=module_config): election_config = voting_phase_to_vvvote_election_config(module_config, self).to_json() with start_action(action_type="create_election_in_vvvote", election_config=election_config) as action: config_url = create_election_in_vvvote(module_config, election_config) self.voting_module_data[voting_module_name] = {"config_url": config_url} action.add_success_fields(config_url=config_url) _ = request.i18n.gettext request.flash(_("voting_created_msg", voting_module=voting_module_name), "success") return redirect(request.link(self))
def register(ctx, request): try: payload = request.json() nickname = payload['nickname'] mail = payload['mail'] password = payload['password'] except KeyError as e: raise HTTPBadRequest('{} is required'.format(e)) except Exception as e: raise HTTPBadRequest(e) user = User.query.filter(or_(User.nickname == nickname, User.email == mail)).first() if user is not None: return jsonify(node=400, message='user exist') catalog = Catalog(name='default') user = User(nickname=nickname, catalogs=[catalog], email=mail, password=bcrypt.hashpw(password.encode(), bcrypt.gensalt())) db.session.add(user) try: db.session.commit() return jsonify(code=200) except Exception as e: logging.error(e) db.session.rollback() raise HTTPInternalServerError(e)
def REPLICATE(self, request): """ Handle REPLICATE requests for the Swift Object Server. This is used by the object replicator to get hashes for directories. """ start_time = time.time() try: device, partition, suffix = split_path(unquote(request.path), 2, 3, True) validate_device_partition(device, partition) except ValueError, e: self.logger.increment('REPLICATE.errors') return HTTPBadRequest(body=str(e), request=request, content_type='text/plain')
def _check_param_nonull_and_valid(values_set, keys_set, valids_set={}): """ Check operation params is not null and valid. :param values_set: Params set. :param keys_set: Params will be checked. :param valids_set: :return: """ for k in keys_set: v = values_set.get(k, None) if isinstance(v, type(True)) and v is None: errmsg = (_("Segment %s can't be None." % k)) raise HTTPBadRequest(explanation=errmsg) elif not isinstance(v, type(True)) and not v: errmsg = (_("Segment %s can't be None." % k)) raise HTTPBadRequest(explanation=errmsg) for (k, v) in valids_set.items(): # if values_set.get(k, None) and values_set[k] not in v: if values_set.get(k, None) and -1 == v.find(values_set[k]): errmsg = (_("Segment %s is out of valid range." % k)) raise HTTPBadRequest(explanation=errmsg)
def __call__(self, request): if config['proxy']: scheme = config.get('scheme', 'http') netloc = config['netloc'] print 'Proxying to %s' % netloc response = proxy(request, scheme, netloc) _DATA[str(request)] = response _DATA.sync() return response req = str(request) if req not in _DATA: raise HTTPBadRequest() return _DATA[req]
def validate_image_meta(req, values): name = values.get('name') disk_format = values.get('disk_format') container_format = values.get('container_format') if 'disk_format' in values: if disk_format not in CONF.image_format.disk_formats: msg = _("Invalid disk format '%s' for image.") % disk_format raise HTTPBadRequest(explanation=msg, request=req) if 'container_format' in values: if container_format not in CONF.image_format.container_formats: msg = _("Invalid container format '%s' " "for image.") % container_format raise HTTPBadRequest(explanation=msg, request=req) if name and len(name) > 255: msg = _('Image name too long: %d') % len(name) raise HTTPBadRequest(explanation=msg, request=req) amazon_formats = ('aki', 'ari', 'ami') if disk_format in amazon_formats or container_format in amazon_formats: if disk_format is None: values['disk_format'] = container_format elif container_format is None: values['container_format'] = disk_format elif container_format != disk_format: msg = (_("Invalid mix of disk and container formats. " "When setting a disk or container format to " "one of 'aki', 'ari', or 'ami', the container " "and disk formats must match.")) raise HTTPBadRequest(explanation=msg, request=req) return values
def __call__(self, env, start_response): req = Request(env) if self.check_character(req): return HTTPBadRequest( request=req, body=( "Object/Container name contains forbidden chars from %s" % self.forbidden_chars))(env, start_response) elif self.check_length(req): return HTTPBadRequest( request=req, body=( "Object/Container name longer than the allowed maximum %s" % self.maximum_length))(env, start_response) elif self.check_regexp(req): return HTTPBadRequest( request=req, body=("Object/Container name contains a forbidden substring " "from regular expression %s" % self.forbidden_regexp))( env, start_response) else: # Pass on to downstream WSGI component return self.app(env, start_response)
def check_template_config_format(template): def check_service_format(services): """ "service": { "compute": {"force_type": "service"}, "glance": {"force_type": "none"} } """ for service_name, service_value in services.items(): if service_name not in daisy_cmn.service_map.keys(): raise HTTPBadRequest("service '%s' not in service table" % service_name) if 'force_type' not in service_value \ or service_value['force_type'] not in ['service', 'node', 'none']: raise HTTPBadRequest("No force_type or error force_type value" " in service") def check_data_type(config): if config['data_type'] not in [ 'int', 'string', 'list', 'boolean', 'float', 'ipaddr', 'password' ]: raise HTTPBadRequest("data_type '%s' in '%s' not support" % (config['data_type'], config['name'])) if not template: raise HTTPBadRequest('Template config is null!') for value in template.values(): for item in CONFIG_ITEMS: if not value.get(item): raise HTTPBadRequest('No service or config file found in ' 'template config!') check_data_type(value) check_service_format(value['service'])
def post(self): if users.get_current_user() is None: raise HTTPUnauthorized( "You must be logged in to create a new election.") params = ProcessParams(request=self.request, optional_params=["start_ts", "end_ts"], required_params=["title", "candidates"]) if (not isinstance(params["candidates"], list) or len(params["candidates"]) < 2): raise HTTPBadRequest("At least two candidates are required.") # NOTE: Cross-group transcations requires using the high-replication # datastore. Add the --high_replication command line flag to # dev_appserver.py in the development environment. db.run_in_transaction_options(db.create_transaction_options(xg=True), self.CreateElectionAndCandidates, params)
def _deserialize(self, request): result = {} try: result['image_meta'] = utils.get_image_meta_from_headers(request) except exception.Invalid: image_size_str = request.headers['x-image-meta-size'] msg = _("Incoming image size of %s was not convertible to " "an integer.") % image_size_str raise HTTPBadRequest(msg, request=request) image_meta = result['image_meta'] if 'size' in image_meta: incoming_image_size = image_meta['size'] if incoming_image_size > IMAGE_SIZE_CAP: max_image_size = IMAGE_SIZE_CAP msg = _("Denying attempt to upload image larger than " "%(max_image_size)d. Supplied image size was " "%(incoming_image_size)d") % locals() logger.warn(msg) raise HTTPBadRequest(msg, request=request) data = request.body_file if self.has_body(request) else None result['image_data'] = data return result
def create_response_for_bad_httpmethod_for_url(self, req): self.logger.debug( "Bad request: HTTP method %s is not valid for this URL" % req.method.upper()) error = UnprocessableEntityException( "HTTP Method %s is not processable by this resource" % req.method.upper()) content_type, detail = self.get_error_body(req, error) return HTTPBadRequest(body=detail, content_type=content_type, request=req)
def patch(self, ticket_id): # TODO: restart expire timer if not ticket_id: raise HTTPBadRequest("Ticket id is required") try: patch = self.request.json except ValueError as e: raise HTTPBadRequest("Invalid patch: %s" % e) try: timeout = patch["timeout"] except KeyError: raise HTTPBadRequest("Missing timeout key") try: timeout = int(timeout) except ValueError as e: raise HTTPBadRequest("Invalid timeout value: %s" % e) try: ticket = tickets.get(ticket_id) except KeyError: raise HTTPNotFound("No such ticket: %s" % ticket_id) ticket["expires"] = int(util.monotonic_time()) + timeout self.log.info("Extending ticket %s, new expiration in %d", ticket_id, ticket["expires"]) return response()
def toggle_following(self): user_id = request.POST.get('follows_user_id') if user_id: try: self.scm_model.toggle_following_user(user_id, request.authuser.user_id) Session().commit() return 'ok' except Exception: log.error(traceback.format_exc()) raise HTTPBadRequest() repo_id = request.POST.get('follows_repository_id') if repo_id: try: self.scm_model.toggle_following_repo(repo_id, request.authuser.user_id) Session().commit() return 'ok' except Exception: log.error(traceback.format_exc()) raise HTTPBadRequest() raise HTTPBadRequest()
def __init__(self, error): HTTPBadRequest.__init__(self) self.error_data = { 'reason': error, 'explanation': error_list[error], }
def __call__(self, environ, start_response): # SQLAlchemy boilerplate code to connect to db and connect models to db objects engine = create_engine(engine_string) Session = sessionmaker(bind=engine) session = Session() req = Request(environ) if req.method != 'POST': resp = HTTPBadRequest('This page can only be accesses via POST') return resp(environ, start_response) else: firstname = req.POST['firstname'] lastname = req.POST['lastname'] subj = Subject(firstname=firstname, lastname=lastname) to_add = {} for k in ('amerind', 'afram', 'pacif', 'asian', 'white', 'unknown', 'ur_student', 'hearing_normal', 'more_expts'): if req.POST.has_key(k): to_add[k] = True for k in ('sex', 'ethnicity', 'other_race', 'gradyear', 'hearing_problems', 'vision_normal', 'vision_other'): if req.POST.has_key(k): if req.POST[k] not in (None, '', u''): to_add[k] = req.POST[k] if req.POST.has_key('age'): if req.POST['age'] not in (None, ''): to_add['age'] = int(req.POST['age']) if req.POST['entrydate'] not in (None, '', u''): to_add['entrydate'] = parser.parse(req.POST['entrydate']).date() else: to_add['entrydate'] = date.today() subj.from_dict(to_add) try: session.add(subj) session.commit() except IntegrityError as e: resp = HTTPBadRequest(e) return resp(environ, start_response) if req.POST.has_key('phone'): if req.POST['phone'] not in (None, '', u''): p = Phone(subject = subj, number = req.POST['phone']) session.add(p) session.commit() if req.POST.has_key('email'): if req.POST['email'] not in (None, '', u''): em = Email(subject = subj, address = req.POST['email']) session.add(em) session.commit() from pprint import pformat #output = pformat(subj.to_dict(deep={'phone': {}, 'email': {}})) env = Environment(loader=FileSystemLoader(os.path.join(basepath,'templates'))) template = env.get_template('subject_list.html') template = template.render(subjects = [subj.to_dict(deep={'phone': {}, 'email': {}}),]) resp = Response() resp.content_type='text/html' resp.unicode_body = template #resp.content_type='text/plain' #resp.body = output return resp(environ, start_response)
def __init__(self, error_name): HTTPBadRequest.__init__(self) self.error_data = {"reason": error_name, "explanation": error_list[error_name]}
def __call__(self, environ, start_response): req = Request(environ) env = Environment(loader=FileSystemLoader('.')) amz_dict = {'workerId' : '', 'assignmentId' : '', 'hitId' : ''} templ, part, listid, template, resp = [None for x in range(5)] required_keys = ['workerId', 'assignmentId', 'hitId', 'part'] key_error_msg = 'Missing parameter: {0}. Required keys: {1}' try: amz_dict['workerId'] = req.params['workerId'] amz_dict['assignmentId'] = req.params['assignmentId'] amz_dict['hitId'] = req.params['hitId'] part = int(req.params['part']) except KeyError as e: resp = HTTPBadRequest(key_error_msg.format(e, required_keys)) return resp(environ, start_response) if amz_dict['assignmentId'] == 'ASSIGNMENT_ID_NOT_AVAILABLE': template = env.get_template('preview.html') template = template.render(part = part) else: worker = check_worker_exists(amz_dict['workerId']) if worker: forbidden_msg = '<p style="font-weight: bold; font-size: x-large;">{0}</p>' if part in (2,3): try: sess = SessionState.query.filter_by(worker=worker).one() if part == 2: if not sess.sess1complete: resp = HTTPForbidden(forbidden_msg.format('You must do part 1 before part 2!')) else: sess.sess2complete = True sess.sess2timestamp = datetime.now() session.commit() # important! w/o this it won't save them if part == 3: if not sess.sess2complete: resp = HTTPForbidden(body_template=forbidden_msg.format('You must do part 2 before part 3!')) if not worker.trialgroup.now: start_time = sess.sess2timestamp + timedelta(days=2) if datetime.now() < start_time: resp = HTTPForbidden(forbidden_msg('You must wait at least 2 days before doing part 3!')) if not resp: sess.sess3complete = True sess.sess4timestamp = datetime.now() session.commit() # important! w/o this it won't save them except NoResultFound: resp = HTTPForbidden(forbidden_msg.format('Attempting to do part {0} without having done part 1!'.format(part))) else: if part == 1: worker = Worker(workerid = amz_dict['workerId'], trialgroup = random_lowest_list()) SessionState(sess1complete = True, worker = worker) session.commit() # important! w/o this it won't save them else: # If part is anything but 1 and there's no worker defined, # then something is horribly wrong resp = HTTPForbidden(forbidden_msg.format('Attempting to do part {0} without having done part 1!'.format(part))) if not resp: sesslist = {1 : worker.trialgroup.sess1list, 2 : worker.trialgroup.sess2list, 3 : worker.trialgroup.sess3list}[part] if part in (1,3): template = env.get_template('flash_experiment.html') else: template = env.get_template('spr_experiment.html') template = template.render(part = part, list = sesslist, now=worker.trialgroup.now, amz_dict = amz_dict) if template and not resp: resp = Response() resp.content_type='application/xhtml+xml' resp.unicode_body = template return resp(environ, start_response)