예제 #1
0
파일: models.py 프로젝트: warehaus/warehaus
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))
예제 #2
0
def category(slug):
    category = static.key("categories", slug)
    if not category:
        response = abort("category", "not-found")
        flask_abort(response)

    return category
예제 #3
0
파일: models.py 프로젝트: warehaus/warehaus
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
예제 #4
0
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))
예제 #5
0
def franchise(slug):
    franchise = DescriptorService.get_by_slug("franchise", slug)
    if not franchise:
        response = abort("franchise", "not-found")
        flask_abort(response)

    return franchise
예제 #6
0
    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
예제 #7
0
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
예제 #8
0
def descriptor_service(slug):
    descriptor = static.key("descriptors", slug)
    if not descriptor:
        response = abort("descriptors", "not-found")
        flask_abort(response)

    return descriptor
예제 #9
0
파일: errors.py 프로젝트: adsabs/adsgut
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))
예제 #10
0
def account(username):
    account = UserService.get_by_username(username)
    if not account:
        response = abort("account", "not-found")
        flask_abort(response)

    return account
예제 #11
0
def team(slug):
    team = TeamService.get_by_slug(slug)
    if not team:
        response = abort("team", "not-found")
        flask_abort(response)

    return team
예제 #12
0
def status(slug):
    status = static.key("statuses", slug)
    if not status:
        response = abort("status", "not-found")
        flask_abort(response)

    return status
예제 #13
0
def content(slug):
    content = static.key("content", slug)
    if not content:
        response = abort("content", "not-found")
        flask_abort(response)

    return content
예제 #14
0
def genre(slug):
    genre = static.key("genres", slug)
    if not genre:
        response = abort("genre", "not-found")
        flask_abort(response)

    return genre
예제 #15
0
파일: base.py 프로젝트: mattcen/ckan
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)
예제 #16
0
def email(data):
    expression = r"[^@]+@[^@]+\.[^@]+"
    if not bool(re.search(expression, data)):
        response = abort("general", "bad-regex")
        flask_abort(response)

    return data
예제 #17
0
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
예제 #18
0
def state(slug):
    state = static.key("states", slug)
    if not state:
        response = abort("state", "not-found")
        flask_abort(response)

    return state
예제 #19
0
파일: base.py 프로젝트: berlinonline/ckan
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)
예제 #20
0
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)
예제 #21
0
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))
예제 #22
0
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)
예제 #24
0
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
예제 #25
0
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')
예제 #26
0
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)
예제 #27
0
        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)
예제 #28
0
파일: core.py 프로젝트: ubc/acj-versus
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
예제 #29
0
파일: rendering.py 프로젝트: meZee/pyaspora
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)
예제 #30
0
        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)
예제 #31
0
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
예제 #32
0
파일: app.py 프로젝트: ncuhome/fighting
def abort(message):
    """
    Abort with 400 response

    Args:
        message (str): 错误提示
    """
    response = jsonify(message)
    response.status_code = 400
    flask_abort(400, response=response)
예제 #33
0
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)
예제 #34
0
파일: roles.py 프로젝트: warehaus/warehaus
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))
예제 #35
0
파일: models.py 프로젝트: warehaus/warehaus
 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]
예제 #36
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)
예제 #37
0
파일: api.py 프로젝트: gromgull/palisade
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
예제 #38
0
 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")
예제 #40
0
 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'
예제 #41
0
    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)
예제 #42
0
 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
예제 #43
0
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
예제 #44
0
 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
예제 #45
0
 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))
예제 #46
0
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
예제 #47
0
 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))
예제 #48
0
파일: app.py 프로젝트: ncuhome/fighting
 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)
예제 #49
0
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)
예제 #50
0
파일: blob.py 프로젝트: xzwupeng/quay
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
                 }))
예제 #51
0
 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
예제 #52
0
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))
예제 #53
0
 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
예제 #54
0
 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
예제 #55
0
 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
예제 #56
0
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))
예제 #57
0
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)
예제 #58
0
 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