当前位置: 首页>>代码示例>>Python>>正文


Python tg.abort函数代码示例

本文整理汇总了Python中tg.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了abort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _judge_permissions

    def _judge_permissions(self):
        '''Check current users permissions for judging and generate appropriate warnings'''
        if not request.allowance(self.submission):
            abort(403)

        if self.assignment.is_active:
            flash('The assignment is still active, this submission could still be edited by the student.', 'warning')
开发者ID:samsemilia7,项目名称:SAUCE,代码行数:7,代码来源:submissions.py

示例2: csrf_protect

def csrf_protect(remainder, params):
    """
    Perform CSRF protection checks. Performs checks to determine if submitted
    form data matches the token in the cookie. It is assumed that the GET
    request handler successfully set the token for the request and that the
    form was instrumented with a CSRF token field. Use the
    :py:func:`~csrf_token` decorator to do this.

    Generally, the handler does not need to do anything
    CSRF-protection-specific. All it needs is the decorator::

        @csrf_protect
        @expose('myapp.templates.protected_post_handler')
        def protected_post_handler():
            if successful:
                tg.redirect('/someplace')
            return dict(errors="There were some errors")

    """
    req = tg.request._current_obj()

    secret, token_name, path, expires = _get_conf()
    token = req.signed_cookie(token_name, secret=secret)
    if not token:
        tg.abort(403, 'The form you submitted is invalid or has expired')

    form_token = req.args_params.get(token_name)
    if form_token != token.decode(ENCODING):
        tg.response.delete_cookie(token_name, path=path)
        tg.abort(403, 'The form you submitted is invalid or has expired')
开发者ID:amol-,项目名称:tgext.utils,代码行数:30,代码来源:csrf.py

示例3: get_one

    def get_one(self, id, **kw):
        entity = self._prepare_query(**kw).filter(self.model.id == id).first()

        if entity is None:
            abort(404, 'Not found')

        return {'value': self._dictify(entity)}
开发者ID:MarekSalat,项目名称:Trine,代码行数:7,代码来源:ApiController.py

示例4: submit

    def submit(self, *args, **kwargs):
        '''Create new submission for this assignment'''
        if 'manage' not in request.permissions and \
                request.user not in set(self.event.members) | set(self.event.tutorsandteachers):
            abort(403)
        if (not self.assignment.is_active and
                not request.allowance(self.assignment)):
            flash('This assignment is not active, you may not create a submission', 'warning')
            redirect(url(self.assignment.url))

        submission = Submission(
            assignment=self.assignment,
            filename=self.assignment.submission_filename or None,
            source=self.assignment.submission_template or None,
            language=self.assignment.allowed_languages[0] if self.assignment.allowed_languages else None,
            user=request.user,
            created=datetime.now(),
            modified=datetime.now(),
        )
        DBSession.add(submission)
        try:
            DBSession.flush()
        except SQLAlchemyError:
            DBSession.rollback()
            log.warn('Error creating new submission', exc_info=True)
            flash('Error creating new submission', 'error')
            redirect(url(self.assignment.url))
        else:
            redirect(url(submission.url + '/edit'))
开发者ID:Ayutac,项目名称:SAUCE,代码行数:29,代码来源:assignments.py

示例5: new

    def new(self, *args, **kw):
        """Display a page to show a new record."""
        if getattr(self, 'new_form', None) is None:
            abort(404)

        tmpl_context.widget = self.new_form
        return dict(value=kw, model=self.model.__name__)
开发者ID:TurboGears,项目名称:tgext.crud,代码行数:7,代码来源:controller.py

示例6: get_delete

    def get_delete(self, *args, **kw):
        '''This is the code that creates a confirm_delete page

        The delete operation will be simulated to be able to display all related
        objects that would be deleted too.
        '''
        if not self.allow_delete:
            abort(403)
        pks = self.provider.get_primary_fields(self.model)
        kw, d = {}, {}
        for i, pk in enumerate(pks):
            kw[pk] = args[i]
        for i, arg in enumerate(args):
            d[pks[i]] = arg

        obj = self.provider.delete(self.model, d)
        deps = u'<dl>'
        for k, g in groupby(sorted(o for o in DBSession.deleted if o != obj), lambda x: type(x)):
            deps += u'<dt>' + unicode(k.__name__) + u's' + u'</dt>'
            deps += u'<dd>' + u', '.join(sorted(unicode(o) for o in g)) + u'</dd>'
        deps += u'</dl>'

        transaction.doom()

        #obj = self.edit_filler.__provider__.get_obj(self.model, params=kw, fields=self.edit_filler.__fields__)
        pklist = u'/'.join(map(lambda x: unicode(getattr(obj, x)), pks))

        return dict(obj=obj,
            model=self.model.__name__,
            deps=deps,
            pk_count=len(pks), pklist=pklist)
开发者ID:Ayutac,项目名称:SAUCE,代码行数:31,代码来源:base.py

示例7: __init__

    def __init__(self, *args, **kw):
        # /event/url/submissions
        self.event = kw.get('event', None)
        # /event/url/lesson/id/submissions
        self.lesson = kw.get('lesson', None)
        # /event/url/sheet/id/assignment/id/submissions
        self.assignment = kw.get('assignment', None)
        # /event/url/sheet/id/submissions
        self.sheet = kw.get('sheet', None)
        if self.event:
            pass
        elif self.lesson:
            self.event = self.lesson.event
        elif self.assignment:
            self.event = self.assignment.sheet.event
        elif self.sheet:
            self.event = self.sheet.event
        else:
            log.warn('SubmissionController without any filter')
            flash('You can not view Submissions without any constraint.', 'error')
            abort(400)

        # Allow access for event teacher and lesson teacher
        self.allow_only = Any(
            has('teachers', self.event),
            has('tutors', self.lesson),
#             has_teacher(self.event),
#             has_teachers(self.event),
#             has_teacher(self.lesson),
            has_permission('manage'),
            msg=u'You have no permission to manage this Lesson'
        )

        self.table = SubmissionTable(DBSession)
        self.table_filler = SubmissionTableFiller(DBSession, lesson=self.lesson)
开发者ID:samsemilia7,项目名称:SAUCE,代码行数:35,代码来源:lessons.py

示例8: _default

    def _default(self, page=None, *args, **kw):

        page_slug = dict(slug=page)
        hooks.notify('flatpages.before_override_template', args=(page_slug, self))

        page = model.FlatPage.by_slug(page_slug['slug'])

        if page is None:
            abort(404, 'Page not found')


        permission = page.required_permission
        if permission and permission != 'public':
            if permission == 'not_anonymous':
                predicate = predicates.not_anonymous()
            else:
                predicate = predicates.has_permission(permission)

            if not predicate.is_met(request.environ):
                abort(403, 'Forbidden')

        try:
            userid = request.identity['user'].user_id
        except:
            userid = None

        override_template(RootController._default, page.template)

        hooks.notify('flatpages.after_override_template', (page, self))
        return dict(page=page,
                    tg_cache={'expire': self.CACHE_EXPIRE,
                              'key': '%s-%s-%s' % (page.slug, page.updated_at, userid)})
开发者ID:amol-,项目名称:tgapp-flatpages,代码行数:32,代码来源:root.py

示例9: _before

 def _before(self, *args, **kw):
     try:
         TIMRestPathContextSetup.current_user()
         TIMRestPathContextSetup.current_workspace()
         TIMRestPathContextSetup.current_folder()
     except NoResultFound:
         abort(404)
开发者ID:buxx,项目名称:tracim,代码行数:7,代码来源:__init__.py

示例10: share

    def share(self, slug=None, product=None, *args, **kw):
        product = app_globals.shop.product.get(slug=slug, _id=product)
        if product is None:
            abort(404, 'Product not found')

        return dict(product=product, buy_form=get_buy_product_form(),
                    action=plug_url('stroller2', '/product/add_to_cart'),
                    active=self._product_is_active(product))
开发者ID:gasbasd,项目名称:tgapp-stroller2,代码行数:8,代码来源:product.py

示例11: edit

    def edit(self, *args, **kw):
        user = handler.user.get_user_in_session(request)

        # get circle id
        if request.method == 'GET':
            sequence_id = args[0]
        else :
            sequence_id = kw.get('cid')

        sequence_id=int(sequence_id)
        sequence = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
        if not sequence:
            abort(404, 'Sequence with id %s not found' % sequence_id)

        if not sequence.public:
            add_user_widget = form.AddUser(action=url('/sequences/edit/%s' % sequence_id)).req()

            if request.method == 'POST':
                # add an user
                mail = kw.get('mail')
                try:
                    add_user_widget.validate({'cid' : sequence_id, 'mail' : mail})
                except twc.ValidationError as e:
                    users = ', '.join(['%s' % u.email for u in sequence.users])
                    default_tracks = ', '.join(['%s' % t.name for t in sequence.default_tracks])
                    kw['cid'] = sequence_id
                    users = sequence.users
                    for u in users:
                        u.__dict__['sid'] = sequence_id
                    widget = e.widget
                    widget.value = kw
                    return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=default_tracks, au_error=True, seq_id=sequence_id)

                to_add = DBSession.query(User).filter(User.email == mail).first()
                if to_add is None:
                    to_add = handler.user.create_tmp_user(mail)
                sequence.users.append(to_add)
                DBSession.flush()

            kw['cid'] = sequence_id
            add_user_widget.value = kw

        else:
            add_user_widget = None

        users = sequence.users
        for u in users:
            u.__dict__['sid'] = sequence_id

        tracks = sequence.default_tracks
        for t in tracks:
            t.__dict__['sid'] = sequence_id

        add_user = util.to_datagrid(datagrid.sequence_user_grid, users, "Users", len(users)>0)

        def_tracks = util.to_datagrid(datagrid.sequence_default_tracks, tracks, "Default tracks", len(tracks)>0)

        return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=def_tracks, au_error=False, seq_id=sequence_id)
开发者ID:bbcf,项目名称:pygdv,代码行数:58,代码来源:sequence.py

示例12: postflight

    def postflight(self, runtype=None, mac=None, name=None, serial=None, manifest=None, base64bz2report=None):
        """Log postflight."""
        
        # Decode report
        # FIXME: there has to be a better way to submit a binary blob
        try:
            base64bz2report = base64bz2report.replace(" ", "+")
            bz2report = base64.b64decode(base64bz2report)
            report = bz2.decompress(bz2report)
        except BaseException as e:
            print "Can't decode report from %s (%s): %s" % (request.environ['REMOTE_ADDR'], mac, str(e))
            abort(403)
        
        # Parse plist with plistlib, as Objective-C objects can't be pickled.
        try:
            plist = plistlib.readPlistFromString(report)
        except BaseException as e:
            print "Received invalid plist from %s (%s): %s" % (request.environ['REMOTE_ADDR'], mac, str(e))
            abort(403)
        #plist, format, error = \
        #    NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(
        #        buffer(report),
        #        NSPropertyListMutableContainers,
        #        None,
        #        None
        #    )
        #if error:
        #    print "error:", error
        #    abort(401)
        
        # Create client if needed.
        client = Client.by_serial(serial)
        if not client:
            print "postflight running without preflight for %s" % mac
            client = Client()
            client.serial = serial
            DBSession.add(client)
        
        # Update client attributes.
        client.runtype = runtype
        if name:
            client.name = name
        else:
            client.name = "<NO NAME>"

        # Get manifest id from plist
        client.mac = mac
        client.manifest = manifest
        client.runstate = u"done"
        client.timestamp = datetime.now()
        client.remote_ip = unicode(request.environ['REMOTE_ADDR'])
        # Save report, updating activity, errors, warnings, and console_user.
        client.update_report(plist)
                
        DBSession.flush()
        
        return "postflight logged for %s\n" % name
开发者ID:asurasunil,项目名称:MunkiReport,代码行数:57,代码来源:update.py

示例13: report_plist

 def report_plist(self, serial=None):
     """View a munki report."""
     client=Client.by_serial(unicode(serial))
     if not client:
         abort(404)
     
     # Work with a copy of the client report so we can modify it without
     # causing a database update.
     report = dict(client.report_plist)
     return plistlib.writePlistToString(report)
开发者ID:asurasunil,项目名称:MunkiReport,代码行数:10,代码来源:view.py

示例14: index

    def index(self, *args, **kwargs):
        try:
            server = oauth2.Server()
            server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
            req = oauth2.Request.from_request(
                request.method, request.url, request.headers, request.params, request.query_string
            )
            params = server.verify_request(req, oauth2.Consumer(self.key, self.secret), None)
        except:
            log.debug("LTI Tool Provider OAuth Error", exc_info=True)
            flash("LTI Tool Provider OAuth Error", "error")
            abort(403)
        else:
            log.debug(params)

        user_name = (
            params.get("tool_consumer_info_product_family_code", "external")
            + "_"
            + params.get("tool_consumer_instance_guid", "external")
            + "_"
            + params.get("user_id")
        )

        user = User.query.filter_by(user_name=user_name).first()
        if not user:
            log.info("New user %s", user_name)
            user = User(
                user_name=user_name,
                display_name=params.get("lis_person_name_full"),
                email_address=params.get("lis_person_contact_email_primary"),
            )
            DBSession.add(user)

        submission = Submission.query.filter(Submission.assignment == self.assignment, Submission.user == user).first()
        if not submission:
            submission = Submission(
                assignment=self.assignment,
                filename=self.assignment.submission_filename or None,
                source=self.assignment.submission_template or None,
                language=self.assignment.allowed_languages[0],
                user=user,
                created=datetime.now(),
                modified=datetime.now(),
            )
            DBSession.add(submission)

            DBSession.flush()

        session["lti"] = True
        session["params"] = params
        session["user"] = user.id
        session["submission"] = submission.id
        session.save()

        redirect("/lti/%d/edit" % self.assignment.id)
开发者ID:moschlar,项目名称:SAUCE,代码行数:55,代码来源:lti.py

示例15: get_all

    def get_all(self, *args, **kw):
        """Return all records.
           Pagination is done by offset/limit in the filler method.
           Returns an HTML page with the records if not json.
        """
        if self.pagination:
            paginator = request.paginators['value_list']
            paginator.paginate_items_per_page = self.pagination['items_per_page']
        else:
            paginator = request.paginators['value_list']
            paginator.paginate_items_per_page = -1
            paginator.paginate_page = 0

        if tg.request.response_type == 'application/json':
            adapt_params_for_pagination(kw, self.pagination_enabled)
            try:
                count, values = self.table_filler._do_get_provider_count_and_objs(**kw)
            except Exception as e:
                log.exception('Failed to retrieve table data')
                abort(400, detail=unicode_text(e))
            values = self._dictify(values, length=count)
            if self.pagination_enabled:
                values = SmartPaginationCollection(values, count)
            return dict(value_list=values)

        if not getattr(self.table.__class__, '__retrieves_own_value__', False):
            kw.pop('substring_filters', None)
            if self.substring_filters is True:
                substring_filters = list(set(kw.keys()) - set(['limit', 'offset', 'order_by', 'desc']))
            else:
                substring_filters = self.substring_filters

            adapt_params_for_pagination(kw, self.pagination_enabled)
            try:
                values = self.table_filler.get_value(substring_filters=substring_filters, **kw)
            except Exception as e:
                log.exception('Failed to retrieve table data')
                flash('Unable to retrieve data (Filter "%s": %s)' % (request.query_string, e), 'warn')
                # Reset all variables to sane defaults
                kw = {}
                values = []
                self.table_filler.__count__ = 0
            if self.pagination_enabled:
                values = SmartPaginationCollection(values, self.table_filler.__count__)
        else:
            values = []

        tmpl_context.widget = self.table
        search_fields = self._get_search_fields(kw)
        current_search = self._get_current_search(search_fields)
        return dict(model=self.model.__name__, value_list=values,
                    mount_point=self._mount_point(),
                    headers=search_fields,  # Just for backwards compatibility
                    search_fields=search_fields, current_search=current_search)
开发者ID:TurboGears,项目名称:tgext.crud,代码行数:54,代码来源:controller.py


注:本文中的tg.abort函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。