Example #1
0
def increase_value(request):
    """increase a value for the user"""

    user_id = int(request.matchdict["user_id"])
    try:
        value = float(request.POST["value"])
    except:
        raise BadRequest("Invalid value provided")

    key = request.matchdict["key"] if request.matchdict.has_key("key") else ""
    variable_name = request.matchdict["variable_name"]

    user = User.get_user(user_id)
    if not user:
        raise NotFound("user not found")

    variable = Variable.get_variable_by_name(variable_name)
    if not variable:
        raise NotFound("variable not found")

    Value.increase_value(variable_name, user, value, key)

    output = get_progress(request, return_object=True)

    for aid in output["achievements"].keys():
        if len(output["achievements"][aid]["new_levels"]) > 0:
            del output["achievements"][aid]["levels"]
            del output["achievements"][aid]["priority"]
            del output["achievements"][aid]["goals"]
        else:
            del output["achievements"][aid]
    return output
Example #2
0
def submit_word(request):
    session = request.session
    params = request.params
    db = request.db
    rooms = db.rooms

    if not 'room_id' in session or not 'word' in params:
        return NotFound()
    room = rooms.find_one({'_id': session['room_id']})
    currUser = room['currUsr']
    if currUser == '':
        currUser = room['inRoom'][0]
    sentence = room['answer']
    sentence += params['word'] + " "
    if len(room['inRoom']) < 2:
        return NotFound()

    nextUser = room['inRoom'][1]
    rooms.update({'_id': room['_id']}, {
        '$pop': {
            'inRoom': -1
        },
        '$push': {
            'inRoom': currUser
        },
        '$set': {
            'answer': sentence,
            'lastUser': currUser,
            'currUser': nextUser
        }
    })
    return {}
Example #3
0
File: admin.py Project: zagy/karl
def statistics_csv_view(request):
    statistics_folder = get_setting(request.context, 'statistics_folder')
    csv_file = request.matchdict.get('csv_file')
    if not csv_file.endswith('.csv'):
        raise NotFound()

    path = os.path.join(statistics_folder, csv_file)
    if not os.path.exists(path):
        raise NotFound()

    return request.get_response(FileApp(path).get)
Example #4
0
 def factory(request):
     if request.matchdict is not None and 'id' in request.matchdict:
         try:
             cid = int(request.matchdict['id'])
         except ValueError:
             raise NotFound()
         context = model.query.filter_by(id=cid).first()
         if context is None:
             raise NotFound()
         return context
     return Root()
Example #5
0
 def get(self, request):
     resource = self.get_resource(request)
     if not resource or not resource.exists:
         return NotFound('Template not found')
     request.response.content_type = 'text/plain'
     request.response.write(resource.read())
     return request.response
Example #6
0
    def __call__(self):
        request = self.request

        with request.connmgr.get_connection() as conn:
            cursor = conn.execute(
                """EXEC sp_%s_Page_s_Slug ?, ?, ?""" % request.pageinfo.DbAreaS,
                request.dboptions.MemberID,
                request.matchdict["slug"],
                request.viewdata.dom.ViewType,
            )

            page = cursor.fetchone()

            cursor.nextset()

            other_langs = cursor.fetchall()

        if not page and not other_langs:
            raise NotFound()

        title = page and page.Title or _("Page not found", request)
        return self._create_response_namespace(
            title,
            title,
            {
                "page": page,
                "other_langs": other_langs,
            },
            no_index=True,
        )
def pull_repository_files(repo, commit_id):
    changed_files = {}
    for name in list_content_types(repo):
        changed_files[name] = []

    try:
        old_commit = repo.commit(commit_id)
        diff = old_commit.diff(repo.head)

        sm = StorageManager(repo)
        for diff_added in diff.iter_change_type('A'):
            add_model_item_to_pull_dict(sm, diff_added.b_blob.path,
                                        changed_files)

        for diff_modified in diff.iter_change_type('M'):
            add_model_item_to_pull_dict(sm, diff_modified.b_blob.path,
                                        changed_files)

        json_diff = []
        for diff_added in diff.iter_change_type('R'):
            json_diff.append(format_diff_R(diff_added))

        for diff_removed in diff.iter_change_type('D'):
            json_diff.append(format_diff_D(diff_removed))

        changed_files["other"] = json_diff
        changed_files["commit"] = repo.head.commit.hexsha
        return changed_files

    except (GitCommandError, BadName):
        raise NotFound("The git index does not exist")
Example #8
0
def relationships_watch_commit(context, request):
    # XXX clean this crap up
    target_username = request.params.get('target_user', None)
    target_user = model.session.query(model.User) \
        .filter_by(name=target_username).one()
    if not target_user:
        raise NotFound()

    watch_form = WatchForm(request.POST)
    if not watch_form.validate():
        # XXX better redirect whatever
        request.session.flash(u"Yo form is jacked", level=u'error')
        return HTTPBadRequest()

    watch = model.session.query(model.UserWatch) \
        .filter_by(user=request.user, other_user=target_user) \
        .first()
    if not watch:
        watch = model.UserWatch(
            user=request.user,
            other_user=target_user,
        )

    watch.watch_upload = watch_form.watch_upload.data
    watch.watch_by = watch_form.watch_by.data
    watch.watch_for = watch_form.watch_for.data
    watch.watch_of = watch_form.watch_of.data

    model.session.add(watch)

    # XXX where should this redirect?
    request.session.flash(u"Saved watch settings for {0}.".format(
        target_user.name),
                          level=u'success')
    return HTTPSeeOther(request.route_url('users.view', user=target_user))
Example #9
0
    def render(self, **kwargs):
        """render the form as html or json"""
        request = self.request
        if request.format != 'html':
            meth = getattr(self, 'render_%s_format' % request.format, None)
            if meth is not None:
                return meth(**kwargs)
            else:
                raise NotFound()

        if request.model_class:
            request.model_class = model_class = I18NModel(
                request.model_class, request)
            request.model_label = model_label = model_class.label
            request.model_plural = model_plural = model_class.plural
        else:
            model_class = request.model_class
            model_label = model_plural = ''
        self.update_resources()
        kwargs.update(main=get_renderer(
            'pyramid_formalchemy:templates/admin/master.pt').implementation(),
                      model_class=model_class,
                      model_name=request.model_name,
                      model_label=model_label,
                      model_plural=model_plural,
                      breadcrumb=self.breadcrumb(**kwargs),
                      actions=request.actions,
                      F_=get_translator()),
        return kwargs
Example #10
0
def proposal_redirect_to_agenda_item(context, request):
    ai = find_interface(context, IAgendaItem)
    if ai:
        query = request.GET
        url = request.resource_url(ai, query=query, anchor=context.uid)
        return HTTPFound(location=url)
    raise NotFound("Couldn't locate Agenda Item from this context.")
Example #11
0
class Model(Base):
    """Context used for model instances"""
    def fa_url(self, *args, **kwargs):
        return self._fa_url(*args[2:], **kwargs)

    def __init__(self, request, name):
        Base.__init__(self, request, name)
        query = request.session_factory.query(request.model_class)
        try:
            request.model_instance = request.query_factory(request,
                                                           query,
                                                           id=name)
        except sqlalchemy_exceptions.SQLAlchemyError, exc:
            if name != 'new':
                log.exception(exc)
            request.session_factory().rollback()
            raise NotFound(request.path)

        if request.model_instance is None:
            raise NotFound(request.path)
        request.model_id = name

        if request.model_instance and hasattr(request.model_instance,
                                              '__acl__'):
            self.__acl__ = request.model_instance.__acl__
Example #12
0
 def render_page(self, section, redirpath, values=None):
     if self.endpath is None:
         return HTTPFound(location=route_url('subsections',
                                             self.request,
                                             action=section,
                                             endpath='/'.join(redirpath)))
     self.c.active_footer_nav = '-'.join(
         [self.request.matchdict.get('action')] + list(self.endpath))
     for ext in ('.mako', '.rst'):
         tmpl_path = ('templates/pages/%s/%s%s' %
                      (section, '/'.join(self.endpath), ext))
         values = values or {}
         if pkg_resources.resource_exists('pylonshq', tmpl_path):
             if ext == '.mako':
                 return render_to_response('pylonshq:%s' % tmpl_path,
                                           values, self.request)
             else:
                 self.c.pagename = ' : '.join([
                     item.replace('-', ' ').title() for item in self.endpath
                 ])
                 content = pkg_resources.resource_string(
                     'pylonshq', tmpl_path)
                 body = publish_parts(content,
                                      writer_name='html')['html_body']
                 values = {'body': body}
                 return render_to_response('pylonshq:templates/rst.mako',
                                           values, self.request)
     raise NotFound()
Example #13
0
def preview_wikipage_view(context, request, WikiPage=WikiPage, tz=None):
    version_num = int(request.params['version_num'])
    repo = find_repo(context)
    for version in repo.history(context.docid):
        if version.version_num == version_num:
            break
    else:
        raise NotFound("No such version: %d" % version_num)

    page = WikiPage()
    page.__parent__ = context.__parent__
    page.revert(version)

    is_front_page = (context.__name__ == 'front_page')
    if is_front_page:
        community = find_interface(context, ICommunity)
        page_title = '%s Community Wiki Page' % community.title
    else:
        page_title = page.title

    profiles = find_profiles(context)
    author = profiles[version.user]

    # Extra paranoia, probably not strictly necessary.  I just want to make
    # extra special sure that the temp WikiPage object we create above
    # doesn't accidentally get attached to the persistent object graph.
    transaction.doom()

    return {
        'date': format_local_date(version.archive_time, tz),
        'author': author.title,
        'title': page_title,
        'body': page.cook(request),
    }
Example #14
0
    def activities(self):
        """
        Get activities for current user.

        By default activities are getted only for current day.
        Different date range can be queried using `from` and `to`
        arguments in the request.

        Returns a List of Activity.

        """
        if not self.is_valid_object:
            raise NotFound()

        try:
            (from_date, to_date) = self.get_filter_from_to()
        except (TypeError, ValueError):
            return error_response(_('Invalid date format'))

        # When no dates are given use current date as default
        if not from_date and not to_date:
            from_date = datetime.date.today()
            to_date = from_date + datetime.timedelta(days=1)

        query = Activity.query()
        query = query.filter(Activity.user_id == self.pk_value)
        if from_date:
            query = query.filter(Activity.start >= from_date)
        if to_date:
            query = query.filter(Activity.start < to_date)

        return query.all()
Example #15
0
def discussion_redirect_to_agenda_item(context, request):
    root = find_root(context)
    ai = find_interface(context, IAgendaItem)
    if ai:
        path = resource_path(ai)

        query = dict(
            path=path,
            content_type='DiscussionPost',
            sort_index='created',
            reverse=True,
            limit=5,  #FIXME: this should be globaly configurable?
        )
        docids = root.catalog.search(**query)[1]

        # set to True if requested post is after the display limit
        after_limit = False

        get_metadata = root.catalog.document_map.get_metadata
        for docid in docids:
            brain = get_metadata(docid)
            if brain['uid'] == context.uid:
                after_limit = True
                break

        # post was not found among the displayed posts
        query = request.GET
        if not after_limit:
            query['discussions'] = 'all'
            url = request.resource_url(ai, query=query, anchor=context.uid)
        else:
            url = request.resource_url(ai, query=query, anchor=context.uid)
        return HTTPFound(location=url)

    raise NotFound("Couldn't locate Agenda Item from this context.")
Example #16
0
 def edit_article(self):
     article = db_session.query(Article).filter_by(id=self.request.matchdict['id'])
     user_id = self.request.POST.get('user_id')
     if user_id is None or user_id <= 0:
         NotFound()
     article.update({**self.request.POST})
     db_session.commit()
     return {'id': self.request.matchdict['id']}
Example #17
0
    def _get_related_name(self):
        related_name = super(ModelResource, self)._get_related_name()
        # Check that related name is in fact a relationship
        if related_name:
            if related_name not in self.relationships:
                raise NotFound()

        return related_name
Example #18
0
def get_model_definition(request):
    """Retrieves a model definition.
    """
    modelname = request.matchdict['modelname']
    results = db_model_definition(request.db)[modelname]
    for result in results:
        return result.value
    raise NotFound("Unknown model %s" % modelname)
Example #19
0
def uid_factory(request):
    if request.matchdict is not None and 'uid' in request.matchdict:
        context = models.TalkPreference.query.filter_by(
            uid=request.matchdict['uid']).first()
        if context is None:
            raise NotFound()
        return context
    return object()
Example #20
0
 def add_article(self):
     article = Article(**self.request.POST)
     user_id = self.request.POST.get('user_id')
     if user_id is None or user_id <= 0:
         NotFound()
     db_session.add(article)
     db_session.commit()
     return {'id': article.id, 'id_user': user_id}
Example #21
0
def get(request):
    """Retrieves."""
    key = request.matchdict['key']

    if key not in todos.keys():
        raise NotFound("Unknown key '%s'." % (key))

    return {key: todos[key]}
Example #22
0
def GetOrder(request):
    print "serving request context:", request.context.__name__
    order = DBSession.query(Order).filter_by(
        id=request.context.__name__).first()
    if (order is None):
        return NotFound("No matching order found!")
    else:
        return {'order': order, 'logged_in': request.authenticated_userid}
Example #23
0
def download_datafile(request):
    name = request.matchdict['equip']
    date = request.matchdict['date']
    time = request.matchdict['time']

    dbsession = DBSession()
    try:
        dbsession.query(EquipmentModel).filter_by(name=name).one()
    except NoResultFound:
        return NotFound("Unknown equipment name")

    filename = '{0}_{1}_{2}.h5'.format(name, date, time)
    file_path = os.path.join(data_path, name, filename)

    if not os.path.exists(file_path):
        return NotFound("No file for this equipment on the given date")

    return _make_response(file_path)
Example #24
0
 def test_traverser_raises_notfound_instance(self):
     from pyramid.exceptions import NotFound
     environ = self._makeEnviron()
     context = DummyContext()
     self._registerTraverserFactory(context, raise_error=NotFound('foo'))
     router = self._makeOne()
     start_response = DummyStartResponse()
     why = exc_raised(NotFound, router, environ, start_response)
     self.failUnless('foo' in why[0], why)
 def __init__(self, request, name):
     Base.__init__(self, request, name)
     query = request.session_factory.query(request.model_class)
     try:
         request.model_instance = request.query_factory(request, query, id=name)
     except sqlalchemy_exceptions.SQLAlchemyError, exc:
         log.exception(exc)
         request.session_factory().rollback()
         raise NotFound(request.path)
Example #26
0
 def factory(request):
     # This yields the "context", which should be the row object
     try:
         return contextualize(
             model.session.query(sqla_column.parententity).filter(
                 sqla_column == request.matchdict[match_key]).one())
     except NoResultFound:
         # 404!
         raise NotFound()
Example #27
0
def get_progress(request):
    """get all relevant data concerning the user's progress"""
    user_id = int(request.matchdict["user_id"])

    user = User.get_user(user_id)
    if not user:
        raise NotFound("user not found")

    return _get_progress(user, force_generation=False)[0]
Example #28
0
def hashed_uid_factory(request):
    if request.matchdict is not None and 'hash' in request.matchdict:
        context = models.TalkPreference.query.filter(
            func.encode(
                func.digest(func.text(models.TalkPreference.uid), 'sha256'),
                'hex') == request.matchdict['hash']).first()
        if context is None:
            raise NotFound()
        return context
    return object()
Example #29
0
def view_easteregg(request):
    pwd_hash = request.matchdict['hash']
    try:
        log.debug('got %s', pwd_hash)

        path = os.path.join(egg_dir, eastereggs[pwd_hash])
        return FileResponse(path, content_type='text/html')

    except (KeyError, FileNotFoundError):
        raise NotFound()
Example #30
0
def layouts_redirect_view(people, request):
    """
    Redirects requests for tabs in old people directory to tabs in the new
    people directory.  Tabs in old people directory were referred to as
    "layouts".
    """
    tab = request.subpath[0]
    if tab not in people:
        raise NotFound()
    section = people[tab]
    return HTTPFound(location=resource_url(section, request))