def ensure_unique_slug(parent, slug): '''Makes sure the `slug` is unique as a child of `parent`. If `slug` is not unique, we abort with `httplib.CONFLICT`. ''' parent_id = parent.id if parent is not None else TREE_ROOT if any(Object.query.get_all([slug, parent_id], index='slug_parent')): flask_abort(httplib.CONFLICT, 'Slug "{}" already in use in "{}"'.format(slug, parent_id))
def category(slug): category = static.key("categories", slug) if not category: response = abort("category", "not-found") flask_abort(response) return category
def get_object_by_id(obj_id): assert obj_id != TREE_ROOT assert obj_id != NO_TYPE obj = Object.query.get(obj_id) if obj is None: flask_abort(httplib.NOT_FOUND, 'Could not find object with id={!r}'.format(obj_id)) return obj
def abort(request_format, code, message=None): if request_format == 'json': flask_abort(make_response(json.dumps({'error': message, 'status': 'error'}), code, {'Content-Type': 'application/json'})) else: flask_abort(make_response(message, code))
def franchise(slug): franchise = DescriptorService.get_by_slug("franchise", slug) if not franchise: response = abort("franchise", "not-found") flask_abort(response) return franchise
def parse(self, req=None, strict=False, http_error_code=400): if req is None: req = request namespace = self.namespace_class() req.unparsed_arguments = dict( self.argument_class("").source(req)) if strict else {} errors = {} for arg in self.args: value, found = arg.parse(req, self.bundle_errors) if isinstance(value, ValueError): errors.update(found) found = None if found or arg.store_missing: namespace[arg.dest or arg.name] = value if type(value) is Response: flask_abort(value) if errors: response = abort("general", "missing-field") flask_abort(response) if strict and req.unparsed_arguments: raise exceptions.BadRequest( "Unknown arguments: %s" % ", ".join(req.unparsed_arguments.keys())) return namespace
def uuid(data): expression = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" if not bool(re.search(expression, data)): response = abort("general", "bad-regex") flask_abort(response) return data
def descriptor_service(slug): descriptor = static.key("descriptors", slug) if not descriptor: response = abort("descriptors", "not-found") flask_abort(response) return descriptor
def abort(status_code, body=None, headers={}): """ Content negiate the error response. """ if 'text/html' in request.headers.get("Accept", ""): error_cls = HTTPException else: error_cls = JSONHTTPException #error_cls = JSONHTTPException class_name = error_cls.__name__ bases = [error_cls] attributes = {'code': status_code} #print default_exceptions if status_code in default_exceptions: # Mixin the Werkzeug exception bases.insert(0, default_exceptions[status_code]) error_cls = type(class_name, tuple(bases), attributes) print "BODY", body, error_cls, bases errori=error_cls() if body==None: body={} errori=error_cls(dict(body, code=errori.code, error=errori.name)) #This is just a hack to get the code and the name in currently flask_abort(make_response(errori, status_code, headers))
def account(username): account = UserService.get_by_username(username) if not account: response = abort("account", "not-found") flask_abort(response) return account
def team(slug): team = TeamService.get_by_slug(slug) if not team: response = abort("team", "not-found") flask_abort(response) return team
def status(slug): status = static.key("statuses", slug) if not status: response = abort("status", "not-found") flask_abort(response) return status
def content(slug): content = static.key("content", slug) if not content: response = abort("content", "not-found") flask_abort(response) return content
def genre(slug): genre = static.key("genres", slug) if not genre: response = abort("genre", "not-found") flask_abort(response) return genre
def abort(status_code=None, detail='', headers=None, comment=None): '''Abort the current request immediately by returning an HTTP exception. This is a wrapper for :py:func:`pylons.controllers.util.abort` that adds some CKAN custom behavior, including allowing :py:class:`~ckan.plugins.interfaces.IAuthenticator` plugins to alter the abort response, and showing flash messages in the web interface. ''' if status_code == 403: # Allow IAuthenticator plugins to alter the abort for item in p.PluginImplementations(p.IAuthenticator): result = item.abort(status_code, detail, headers, comment) (status_code, detail, headers, comment) = result if detail and status_code != 503: h.flash_error(detail) if is_flask_request(): flask_abort(status_code, detail) # #1267 Convert detail to plain text, since WebOb 0.9.7.1 (which comes # with Lucid) causes an exception when unicode is received. detail = detail.encode('utf8') return _abort(status_code=status_code, detail=detail, headers=headers, comment=comment)
def email(data): expression = r"[^@]+@[^@]+\.[^@]+" if not bool(re.search(expression, data)): response = abort("general", "bad-regex") flask_abort(response) return data
def get_image_json(namespace, repository, image_id, headers): logger.debug("Checking repo permissions") permission = ReadRepositoryPermission(namespace, repository) repository_ref = registry_model.lookup_repository(namespace, repository, kind_filter="image") if not permission.can() and not (repository_ref is not None and repository_ref.is_public): abort(403) logger.debug("Looking up repo image") legacy_image = registry_model.get_legacy_image(repository_ref, image_id, store, include_blob=True) if legacy_image is None: flask_abort(404) size = legacy_image.blob.compressed_size if size is not None: # Note: X-Docker-Size is optional and we *can* end up with a NULL image_size, # so handle this case rather than failing. headers["X-Docker-Size"] = str(size) response = make_response(legacy_image.v1_metadata_string, 200) response.headers.extend(headers) return response
def state(slug): state = static.key("states", slug) if not state: response = abort("state", "not-found") flask_abort(response) return state
def abort(status_code=None, detail='', headers=None, comment=None): '''Abort the current request immediately by returning an HTTP exception. This is a wrapper for :py:func:`pylons.controllers.util.abort` that adds some CKAN custom behavior, including allowing :py:class:`~ckan.plugins.interfaces.IAuthenticator` plugins to alter the abort response, and showing flash messages in the web interface. ''' if status_code == 403: # Allow IAuthenticator plugins to alter the abort for item in p.PluginImplementations(p.IAuthenticator): result = item.abort(status_code, detail, headers, comment) (status_code, detail, headers, comment) = result if detail and status_code != 503: h.flash_error(detail) # #1267 Convert detail to plain text, since WebOb 0.9.7.1 (which comes # with Lucid) causes an exception when unicode is received. detail = detail.encode('utf8') if is_flask_request(): flask_abort(status_code, detail) return _abort(status_code=status_code, detail=detail, headers=headers, comment=comment)
def show_profile(username): if utils.validate_username(username): fotogal_user = FotogalUser() profile_dict = fotogal_user.get_profile_props(username=username) user_id = profile_dict.get('id', None) session_user_id = session.get('user_id', None) if session_user_id == user_id: profile_owner = True else: profile_owner = False fotogal_images = FotogalImage() imgs_list = fotogal_images.get_user_imgs_list(user_id=user_id) imgs_posted_total = fotogal_images.get_posted_imgs_total(user_id) fotogal_follow = FotogalFollow() following_total = fotogal_follow.get_following_total(user_id) followers_total = fotogal_follow.get_followers_total(user_id) return render_template('profile.html', username=username, profile_owner=profile_owner, profile_dict=profile_dict, imgs_list=imgs_list, imgs_posted_total=imgs_posted_total, following_total=following_total, followers_total=followers_total) flask_abort(400)
def host_preview(host_id): host = User.query.get_or_404(host_id) if not host or host.role not in ['host', 'admin']: flask_abort(403) # If a host accesses their own hostpage if g.user and g.user.id == host_id: return redirect(url_for('user')) return render_template('host_preview.html', hostHref = url_for('user_ep', user_id = host.id))
def image_link(data): # Based on # https://stackoverflow.com/a/51493215/9217774 expression = r"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg)+$" if not bool(re.search(expression, data)): response = abort("general", "not-file-link") flask_abort(response) return data
def abort(status_code, message=None): """ Return response with a certain status code and the json data: {error: message} """ if not message: flask_abort(status_code) else: return make_response(jsonify(error=message), status_code)
def abort(code=500, message=None, **kwargs): try: flask_abort(code) except HTTPException as e: if message: kwargs['message'] = text_type(message) if kwargs: e.data = kwargs raise
def user(): if not g.user: flask_abort(401) elif g.user.role == 'lounger': return render_template('user_new.html') elif g.user.role == 'host': return render_template('host_new.html') elif g.user.role == 'admin': return render_template('admin_new.html')
def abort(status_code, message, extra={}, force_status=False, template=None): if not template: template = "error.tpl" data = {"status": "error", "code": status_code, "errors": [message]} data.update(extra) response = render_response(template, data) if force_status or response.output_format != "html": response.status_code = status_code flask_abort(response)
def decorated_view(*args, **kwargs): if not current_user.is_authenticated or \ not current_user.is_authenticated(): return current_app.login_manager.unauthorized() urole = current_user.get_role() if (roles and (urole not in roles)): flask_abort(403) return fn(*args, **kwargs)
def abort(status_code, message, extra={}, force_status=False, template=None): if not template: template = 'error.tpl' data = {'status': 'error', 'code': status_code, 'errors': [message]} data.update(extra) response = render_response(template, data) if force_status or response.output_format != 'html': response.status_code = status_code flask_abort(response)
def password(data): if type(data) is not str: response = abort("general", "not-found") flask_abort(response) if len(data) < 8 or len(data) > 32: response = abort("general", "password-length") flask_abort(response) return data
def abort(message): """ Abort with 400 response Args: message (str): 错误提示 """ response = jsonify(message) response.status_code = 400 flask_abort(400, response=response)
def method(method): if request.form: #Get the text from the body, so we can deal with it text = request.form['text'] #Deal with the text details = analyser.getStats(method, text) #return the resultant dict return jsonify(details) else: flask_abort(400)
def _require_roles(*role_names): role_names = tuple(role_names) if attempt_auth_token_login(): _check_roles(*role_names) else: try: _check_jwt_roles(*role_names) except JWTError as error: logger.exception(str(error)) flask_abort(httplib.UNAUTHORIZED, str(error))
def get_one_or_none(self, *args, **kwargs): error = kwargs.pop('error', None) if error is None: raise TypeError('This function must get an error parameter') docs = tuple(self.get_all(*args, **kwargs)) if not docs: return None if len(docs) != 1: flask_abort(httplib.INTERNAL_SERVER_ERROR, error) return docs[0]
def all(): if request.form: #Get the text from the body, so we can deal with it text = request.form['text'] #Deal with the text details = analyser.getAllStats(text) #Return the dict return jsonify(details) else: flask_abort(400)
def abort(code, **kwargs): """ Wraps the flask abort function to support adding kwargs to the error """ try: current_app.logger.warn("%s: %s"%(code, kwargs)) flask_abort(code) except HTTPException as e: if len(kwargs): e.data = kwargs raise e
def join_party(self, request=flask_request): # Bootstrap, turn the view function into a 404 after registering. if self.partyline_connected: # This route does not exist at the HTTP level. flask_abort(404) self.invitation_context = _request_ctx_stack.top self.partyline = request.environ.get(WSGIParty.partyline_key) self.app_name = request.environ.get('partyline_handling_app') self.partyline.connect('can_handle_request', self.can_handle_request) self.partyline_connected = True return 'ok'
def post(self): """Create a new publication review.""" try: new_publication_review = PublicationReview(**api.payload) db.session.add(new_publication_review) db.session.commit() return new_publication_review except IntegrityError: return flask_abort(409, "Review has already been created") except ValueError: return flask_abort(400, "Score must be between 1 and 4")
def handle_validation_error(self, error, bundle_errors): error_str = six.text_type(error) error_msg = self.help.format( error_msg=error_str) if self.help else error_str msg = {self.name: error_msg} if current_app.config.get("BUNDLE_ERRORS", False) or bundle_errors: return error, msg response = abort("general", "missing-field") flask_abort(response)
def delete_attribute(self, typeobj): '''Delete a user-defined attribute.''' require_admin() try: attr_slug = request.json['slug'] except LookupError as error: flask_abort(httplib.BAD_REQUEST, 'Missing "{}" parameter'.format(error)) if ('attrs' not in typeobj) or all(attr['slug'] != attr_slug for attr in typeobj.attrs): flask_abort(httplib.NOT_FOUND, 'No such attribute {!r}'.format(attr_slug)) typeobj.attrs = list(attr for attr in typeobj.attrs if attr['slug'] != attr_slug) typeobj.save() return None, httplib.NO_CONTENT
def abort(http_status_code, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. From Flask-Restful. See NOTICE file for license information. """ try: flask_abort(http_status_code) except HTTPException as err: if len(kwargs): err.data = kwargs raise err
def _create_lab(self, slug, display_name): if any(lab['slug'] == slug for lab in self._all_labs()): flask_abort(httplib.CONFLICT, "There's already a lab with this name") lab_type_obj = self._create_lab_type_object(slug) lab = create_object( parent = None, type = lab_type_obj, slug = slug, display_name = display_name, ) lab.save() return lab
def _find_and_invoke_from_type_class(self, type_class, get_action, obj, action_name): http_error = httplib.NOT_FOUND for attr in dir(type_class): action = getattr(type_class, attr) action_info = get_action(action) if action_info is None: continue if action_info['name'] == action_name: http_error = httplib.METHOD_NOT_ALLOWED if action_info['method'] == request.method: return action(obj) flask_abort(http_error, 'Could not find handler for {!r}'.format(action_name))
def _get_server(self, typeobj, slug): lab = get_lab_from_type_object(typeobj) servers = tuple(lab.get_children_with_slug(slug)) if len(servers) == 0: server = create_object(slug=slug, parent=lab, type=typeobj) return server, lab if len(servers) == 1: server = servers[0] if server.type_id != typeobj.id: flask_abort(httplib.INTERNAL_SERVER_ERROR, 'Found server for heartbeat with slug={!r} parent_id={!r} but type_id={!r} (expected type_id={!r})'.format( server.slug, server.parent_id, server.type_id, typeobj.id)) return server, lab flask_abort(httplib.CONFLICT, 'Found more than one server with slug={!r} and lab_id={!r}'.format(slug, lab.id))
def view(): if request.method == 'POST': response = f() if isinstance(response, self.response_class): return response return jsonify(response) elif request.method == 'GET': if accept_json(): return jsonify(desc=desc, directives=directives) else: return render(desc=desc, directives=directives) else: flask_abort(405)
def abort(status_code, message, extra={}, force_status=False, template=None): if not template: template = 'error.tpl' data = { 'status': 'error', 'code': status_code, 'errors': [message] } data.update(extra) response = render_response(template, data) if force_status or response.output_format != 'html': response.status_code = status_code flask_abort(response)
def _abort_range_not_satisfiable(valid_end, upload_uuid): """ Writes a failure response for scenarios where the registry cannot function with the provided range. TODO: Unify this with the V2RegistryException class. """ flask_abort( Response(status=416, headers={ 'Location': _current_request_url(), 'Range': '0-{0}'.format(valid_end), 'Docker-Upload-UUID': upload_uuid }))
def update_status(self, cluster): require_user() if 'status' not in request.json: flask_abort(httplib.BAD_REQUEST, 'Missing status argument') status = request.json['status'] if not isinstance(status, dict) or not (set(status.keys()) <= set(['text', 'progress'])): flask_abort(httplib.BAD_REQUEST, '"status" needs to be an object with "text" and "in_progress" attributes') cluster.status = dict( text = status['text'], in_progress = status.get('in_progress', False), modified_at = now(), modified_by = current_identity.id, ) cluster.save() return cluster.status
def abort(status_code, body=None, headers={}): if "text/html" in request.headers.get("Accept", ""): error_cls = HTTPException else: error_cls = JSONHTTPException class_name = error_cls.__name__ bases = [error_cls] attributes = {"code": status_code} if status_code in default_exceptions: # Mixin the Werkzeug exception bases.insert(0, default_exceptions[status_code]) error_cls = type(class_name, tuple(bases), attributes) flask_abort(make_response(error_cls(body), status_code, headers))
def add_attribute(self, typeobj): '''Add an attribute to this type-object. After this attribute has been added, users can get/set this attribute from all objects of this type. ''' require_admin() try: new_attr = request.json['attr'] except LookupError as error: flask_abort(httplib.BAD_REQUEST, 'Missing "{}" parameter'.format(error)) if 'attrs' in typeobj: if any(attr['slug'] == new_attr['slug'] for attr in typeobj.attrs): flask_abort(httplib.CONFLICT, "There's already an attribute with slug '{}'".format(new_attr['slug'])) typeobj.attrs = typeobj.attrs + [new_attr] else: typeobj.attrs = [new_attr] typeobj.save() return typeobj.as_dict(), httplib.CREATED
def remove_owner(self, cluster): require_user() lab = cluster.get_parent_object() if 'ownerships' not in cluster: return None, httplib.NO_CONTENT if current_identity.role != roles.Admin and all(ownership['owner_id'] != current_identity.id for ownership in cluster.ownerships): flask_abort(httplib.FORBIDDEN, 'You cannot remove ownerships of other users') cluster.ownerships = [] cluster.save() create_event( obj_id = cluster.id, user_id = current_identity.id, interested_ids = [cluster.id, lab.id], title = '**{}** released **{}**'.format(current_identity.display_name, cluster.display_name), ) return None, httplib.NO_CONTENT
def delete_attr(self, obj): '''Remove a user-defined attribute from an object.''' require_user() lab = obj.get_parent_object() typeobj = obj.get_type_object() try: attr_slug = request.json['slug'] except LookupError as error: flask_abort(httplib.BAD_REQUEST, 'Missing "{}" parameter'.format(error)) attr_type = self._get_typeobj_attr(typeobj, attr_slug) if 'attrs' in obj and attr_slug in obj.attrs: obj.attrs = r.literal({slug: value for slug, value in obj.attrs.iteritems() if slug != attr_slug}) obj.save() create_event( obj_id = obj.id, user_id = current_identity.id, interested_ids = [obj.id, lab.id], title = 'Removed the **{}** attribute from **{}**'.format(attr_type['display_name'], obj.display_name), ) return None, httplib.NO_CONTENT
def abort(status_code, body=None, headers={}): """Content negiate the error response. ref: http://flask.pocoo.org/snippets/97/ """ if 'text/html' in request.headers.get("Accept", ""): error_cls = HTTPException else: error_cls = JSONHTTPException class_name = error_cls.__name__ bases = [error_cls] attributes = {'status': status_code} if status_code in default_exceptions: # Mixin the Werkzeug exception bases.insert(0, default_exceptions[status_code]) error_cls = type(class_name, tuple(bases), attributes) flask_abort(make_response(error_cls(body), status_code, headers))
def feed(contact_id): """ An Atom feed of public events for the contact. Only available for contacts who are local to this server. """ data, contact = _profile_base(contact_id, public=True) if not(contact.user and contact.user.activated): flask_abort(404, 'No such user') # Fake "guid" for the user, derived from the ID guid = '{0}-{1}'.format(get_server_name(), contact.user.id) ns = 'http://www.w3.org/2005/Atom' doc = etree.Element("{%s}feed" % ns, nsmap={None: ns}) etree.SubElement(doc, "title").text = 'Pyaspora feed for {0}'.format( data['name'] ) etree.SubElement(doc, "link").text = data['link'] etree.SubElement(doc, "updated").text = data['feed'][0]['created_at'] \ if data['feed'] else contact.user.activated.isoformat() etree.SubElement(doc, "id").text = guid etree.SubElement(doc, "generator").text = 'Pyaspora' author = etree.SubElement(doc, 'author') etree.SubElement(author, "name").text = data['name'] etree.SubElement(author, "uri").text = data['link'] for post in data['feed']: entry = etree.SubElement(doc, 'entry') etree.SubElement(entry, "id").text = \ "{0}-{1}".format(guid, post['id']) etree.SubElement(entry, "title").text = \ post['parts'][0]['body']['text'] etree.SubElement(entry, "updated").text = post['created_at'] etree.SubElement(entry, "content").text = \ "\n\n".join(p['body']['text'] for p in post['parts']) return send_xml(doc)
def add_owner(self, cluster): require_user() lab = cluster.get_type_object() args = self.add_owner_parser.parse_args() new_owner = User.get_by_username(args['username']) if new_owner is None: flask_abort(httplib.BAD_REQUEST, 'Cannot find a user with username={!r}'.format(args['username'])) if 'ownerships' in cluster and cluster['ownerships']: for ownership in cluster['ownerships']: if ownership['owner_id'] == new_owner['id']: return ownership flask_abort(httplib.CONFLICT, 'Cluster is already owned by someone else') cluster.ownerships = [dict(owner_id=new_owner['id'], obtained_at=now())] cluster.save() create_event( obj_id = cluster.id, user_id = current_identity.id, interested_ids = [cluster.id, lab.id], title = ('**{}** took **{}**'.format(new_owner.display_name, cluster.display_name) if new_owner.id == current_identity.id else '**{}** gave **{}** to **{}**'.format(current_identity.display_name, cluster.display_name, new_owner.display_name)), ) return cluster.ownerships, httplib.CREATED