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


Python url.route_url函数代码示例

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


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

示例1: confirm_login

def confirm_login(request):
    """Renders a login form for a user that needs to login in order to
    authenticate an active OpenID authentication request.
    """
    if 'form.submitted' in request.POST:
        if request.POST.get('csrf_token') != request.session.get_csrf_token():
            raise Forbidden

        login = request.POST.get('login', '')
        password = request.POST.get('password', '')
        user = DBSession().query(User).filter_by(username=login).first()

        if user is not None and user.check_password(password):
            headers = remember(request, user.username)
            return HTTPFound(
                location=route_url('openid_confirm_login_success', request),
                headers=headers)
        else:
            request.session.flash(_(u'Failed to log in, please try again.'))

    options = {
        'title': _(u'Log in to authenticate OpenID request'),
        'login_name': request.params.get('login', ''),
        'action_url': route_url('openid_confirm_login', request),
        #'reset_url': route_url('reset_password', request),
        'csrf_token': request.session.get_csrf_token(),
    }
    return render_to_response('templates/openid_confirm_login.pt', options, request)
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:28,代码来源:oid.py

示例2: register

 def register(self):
     if not Validate.bool(self.settings('allow_local_registration','false')):
         return HTTPFound(location=route_url('menu', self.request))
 
     self.response['email'] = ''
 
     if 'form.submitted' in self.request.params:
         self.response['email'] = Validate.sanatize(self.request.params['email'])
         password = Validate.sanatize(self.request.params['password'])
         repassword = Validate.sanatize(self.request.params['re.password'])
         
         if Users.by({'email':self.response['email']}).first():
             self.response['message'] = "Email already in use"
             return self.template('register.pt')
         if not Validate.email(self.response['email']):
             self.response['message'] = "Not a valid email address"
             return self.template('register.pt')
         if not Validate.password(password):
             self.response['message'] = "Improper password."
             return self.template('register.pt')
         if repassword != password:
             self.response['message'] = "Passwords do not match."
             return self.template('register.pt')
             
         # Below is good
         Users.registerLocalUser(self.response['email'], password)
         return HTTPFound(location=route_url('login', self.request))
         
     return self.template('register.pt')
开发者ID:hietpasd,项目名称:quizsmith,代码行数:29,代码来源:authentication.py

示例3: yadis

def yadis(request):
    """Serves the YADIS XRDS documents to facilitate service discovery."""
    OPENID_AX = 'http://openid.net/srv/ax/1.0'

    if request.matchdict.get('local_id', '').strip():
        session = DBSession()
        account = session.query(User).filter(User.username == request.matchdict['local_id']).first()
        if account is None:
            raise NotFound()

        # User specific XRDS document
        options = {
            'service_types': [discover.OPENID_2_0_TYPE, OPENID_AX, sreg.ns_uri],
            'local_id': identity_url(request, request.matchdict['local_id']),
            'uri': route_url('openid_endpoint', request),
        }
    else:
        # Server XRDS document
        options = {
            'service_types': [discover.OPENID_IDP_2_0_TYPE, OPENID_AX, sreg.ns_uri],
            'uri': route_url('openid_endpoint', request),
        }

    response = render_to_response('templates/openid_yadis.pt', options, request)
    response.content_type = 'application/xrds+xml'

    return response
开发者ID:verkkodemokratiaseura,项目名称:verkkovaali,代码行数:27,代码来源:oid.py

示例4: get_tools

def get_tools(request, client, value=False):
    if value:
        tools_dicts = [{
            "label": "Description",
            "value": client.entity()["description"],
            "url": route_url("entity", request, **request.matchdict),
        }]
    else:
        tools_dicts = [{
            "label": "Description",
            "url": route_url("entity", request, **request.matchdict),
        }]
    for tool_name in TOOLS:
        tool_value = getattr(client, tool_name)()
        if tool_value and tool_value["objects"]:
            if value:
                tools_dicts.append({
                    "label": tool_name,
                    "value": tool_value,
                    "url": route_url(tool_name, request, **request.matchdict),
                })
            else:
                tools_dicts.append({
                        "label": tool_name,
                        "url": route_url(tool_name, request, **request.matchdict),
                    })
    return tools_dicts
开发者ID:CulturePlex,项目名称:mobileyutzu,代码行数:27,代码来源:utils.py

示例5: render

    def render(self):
        user = User.by_id(self.session,
                          int(self.request.matchdict['user_id']))

        if self.user.has_no_role:
            # can only see own requests
            if user.id != self.user.id:
                return HTTPFound(location=route_url('list_request',
                                                    self.request))

        if self.user.is_manager:
            # can only see own requests and managed user requests
            if ((user.id != self.user.id)
                    and (user.manager_id != self.user.id)):
                return HTTPFound(location=route_url('list_request',
                                                    self.request))

        today = datetime.now()
        year = int(self.request.params.get('year', today.year))

        start = datetime(2014, 5, 1)
        years = [item for item in reversed(range(start.year, today.year + 1))]

        pool_history = User.get_rtt_history(self.session, user, year)

        return {'user': user, 'year': year, 'years': years,
                'pool_history': pool_history}
开发者ID:doyousoft,项目名称:pyvac,代码行数:27,代码来源:request.py

示例6: upload_file

def upload_file(request):
    # ``filename`` contains the name of the file in string format.
    #
    # WARNING: this example does not deal with the fact that IE sends an
    # absolute file *path* as the filename.  This example is naive; it
    # trusts user input.
    provider = request.POST['media-site']
    #provider = request.matchdict.get('provider', 'youtube')
    service = get_service(request, provider)
    if service is None:
        return HTTPFound(route_url('login', request, provider=provider))    
    log.debug('Uploading file: provider=%s' % provider)
    # we have to ASCII-encode the string. if we use the utf-8 encoding the 
    # flickrapi library crashes at file upload.
    filename = request.POST['filepath'].filename.encode('ascii')
    log.debug('filename: ' + filename);
    # 'filepath' contains the actual file data which needs to be
    # stored somewhere.
    input_file = request.POST['filepath'].file
    out_filepath = get_file_from_user(filename, input_file)
    log.debug('Output filepath: %s' % out_filepath)
    # get media metadata.
    pub_metadata = service.create_pub_metadata(request)    
    # upload the media file to the selected media sites.
    service.publish(out_filepath, pub_metadata)
    log.debug('Uploading succeeded.')
    return HTTPFound(route_url('list_media', request, provider=provider))
开发者ID:nouvak,项目名称:kcclass-media-publish,代码行数:27,代码来源:views.py

示例7: accessibility_view

 def accessibility_view(self):
     category = self._secure_get_category(int(self.request.matchdict['id']))
     
     if self.request.params.get('nojs','0') != '1':
         if not self.request.user.needs_accessibility:
             return HTTPFound(location=route_url('category', self.request))
 
     id = self.request.user.current_test
     test = Tests.by(id).first()
     results = TestsResults.by({'tests_id':id}, sort='id asc').all()
 
     if 'form.submit' in self.request.params:
         for key, value in self.request.params.iteritems():
             key_type, sep, rid = key.rpartition(".")
             if key_type == 'question':
                 result = TestsResults.by(rid).first()
                 passed = TestManager.check_answer_byid(result.question_sets_id, int(value))
                 result.correctly_answered = passed
                 if not passed:
                     result.wrong_attempts = test.max_wrong_answer_allowed
                 result.attempted = True
                 result.duration = self._accessibility_duration_calculator(self.request.params['st'], len(results), test.question_time_allowed)
                 final = self._test_calculator(test,results,result)
         transaction.commit()
         return HTTPFound(location=route_url('score', self.request, id=id))
     else:
         self.response['time_started'] = int(time.time())
         self.response['test'] = test
         self.response['results'] = []
         for result in results:
             self.response['results'].append({'question_set': result,
                                              'answer': result.get_answers()})
         return self.template('playing-accessibility.pt')
开发者ID:hietpasd,项目名称:quizsmith,代码行数:33,代码来源:playing.py

示例8: admin_login

    def admin_login(self, context, request):
        """
        Logs the admin user in.
        """
        login_url = route_url("admin-login", request)
        referrer = request.url
        if referrer == login_url:
            referrer = "/admin/"
        came_from = request.params.get("came_from", referrer)
        message = ""
        # See if the login form was submitted
        if "auth_key" in request.params:
            auth_key = request.params["auth_key"]
            if self.check_admin_auth_key(auth_key):
                headers = remember(request, "admin")
                return HTTPFound(location=came_from, headers=headers)
            message = "Incorrect password."

        # Credentials not submitted or incorrect, render login page
        filename = os.path.join(os.path.dirname(__file__), "admin", "login.html")
        lookup_path = os.path.join(os.path.dirname(__file__), "admin", "include")
        lookup = TemplateLookup(directories=[lookup_path])
        template = Template(filename=filename, lookup=lookup)
        kwargs = {
            "message": message,
            "url": route_url("admin-login", request),
            "came_from": came_from,
            "user": "",
            "loggedin": False,
        }
        body = template.render(**kwargs)
        return Response(body=body)
开发者ID:rmahmood,项目名称:reactor-core,代码行数:32,代码来源:api.py

示例9: final_bet

def final_bet(request):
    player = request.authenticated_userid
    final_tip = Final.get_player_tip(player)
    if final_tip:
        request.session.flash(u'You already entered a final tip.')
        return HTTPFound(location=route_url('view_final_tip', request, player=player))

    final_tip = Final(player)

    form = Form(request, schema=FinalBetSchema, obj=final_tip)
    if 'form.submitted' in request.POST and form.validate():
        # verify, that the tip was entered on time
        if FINAL_DEADLINE < datetime.now():
            return HTTPFound(location=route_url('too_late', request))
        final_tip.d_team1 = form.data['d_team1']
        final_tip.d_team2 = form.data['d_team2']
        final_tip.d_score1 = form.data['d_score1']
        final_tip.d_score2 = form.data['d_score2']
        DBSession.add(final_tip)
        return HTTPFound(location=route_url('view_final_tip', request, player=player))

    teams = [(team.d_id,team.d_name) for team in Team.get_all()]

    return { 'tip': final_tip,
             'form': FormRenderer(form),
             'teams': teams,
             'navigation': navigation_view(request) }
开发者ID:mblunier,项目名称:betgame,代码行数:27,代码来源:views.py

示例10: login

def login(request):
    logged_in = authenticated_userid(request)
    if logged_in:
        return HTTPFound(location=route_url("home", request))
    session = DBSession()
    schema = schemas.Login()
    result = {"_csrf_": request.session.get_csrf_token()}
    errors = []
    if request.POST:
        if not validate_csrf(request):
            return HTTPUnauthorized("Not authorized")
        try:
            form_result = schema.to_python(request.params)
            user = (
                session.query(User)
                .filter(and_(User.email == form_result["email"], User.password == func.sha1(form_result["password"])))
                .first()
            )
            if user:
                headers = remember_me_header(request, user.email)
                return HTTPFound(location=route_url("home", request), headers=headers)
            else:
                errors.append("form")
        except validators.Invalid, e:
            errors = e.error_dict
开发者ID:benzheren,项目名称:carvewith.us,代码行数:25,代码来源:views.py

示例11: save_address

def save_address(request):
    username = request.params["username"]
    try:
        login(username, request.params["password"])
    except:
        request.session.flash("Error: Invalid Fedora Credentials")
        return HTTPFound(route_url("accept", request))

    app = DBSession.query(Application).filter_by(username=username).first()
    if not app:
        request.session.flash("Error: You did not submit an application.")
        return HTTPFound(route_url("accept", request))
    if not app.approved:
        request.session.flash("Error: Your application has not been approved.")
        return HTTPFound(route_url("accept", request))
    app.address = request.params["address"]

    mailer = get_mailer(request)
    admins = request.registry.settings["admin_email"].split()
    sender = request.registry.settings["email_from"]
    body = (
        "Real Name: %s\nUsername: %s\nCountry: %s\n Hardware: %s\n" + "Shield: %s\nDate Submitted: %s\nAddress: %s"
    ) % (app.realname, app.username, app.country, app.hardware, app.shield, app.date, app.address)
    message = Message(
        subject="[Fedora Summer of Open Hardware] Address " "submitted for %s" % username,
        sender=sender,
        recipients=admins,
        body=body,
    )
    DBSession.commit()
    mailer.send_immediately(message, fail_silently=False)
    request.session.flash("Your address has been submitted.")
    return HTTPFound(request.application_url)
开发者ID:ralphbean,项目名称:fedora-openhw2012,代码行数:33,代码来源:views.py

示例12: page_view

def page_view(request):
    page_id = request.matchdict['page_id']
    page = request.context.page
    if not page:
        ## TODO: setup notfound view
        raise NotFound("No such page {0}".format(page_id))
    logged_in = authenticated_userid(request)
    api = get_template('ravel:templates/main.pt')
    commentschema = Comment()
    commentform = Form(commentschema,
                       action=route_url('comment_add', 
                                        request,
                                        page_id=page_id),
                       buttons=('submit',),
                       use_ajax=True)
    commentform['comment'].widget = widget.TextAreaWidget(rows=10, cols=60)
    print page.get('comments', None)
    return {
        'api' : api,
        'description' : page['description'],
        'edit_url' :  route_url('page_edit', request, page_id=page_id),
        'logged_in' : logged_in,
        'title' : page['title'],
        'body' : page['body'],
        'commentform' : commentform.render(),
        'comments' : page.get('comments', None)
        }
开发者ID:GunioRobot,项目名称:ravel,代码行数:27,代码来源:page.py

示例13: feedback

def feedback(project, request):
    session = DBSession()

    item_id = request.matchdict.get('item_id',None)
    items = project.get_items_for_user(request.user)
    pending_items = [i for i in items if not i.submitted]
    completed_items = [i for i in items if i.submitted]

    if item_id:
        item = project.get_item_for_user(request.user, item_id)
    elif pending_items:
        item = pending_items[0]
    else:
        item = None

    if item is not None:
        item = project.get_item(item.id)
        feedback = session.query(FeedbackRecord).filter(FeedbackRecord.user==request.user).filter(FeedbackRecord.item==item).first()
    else:
        feedback = None

    item_controller = FormController(project.item_form)
    feedback_controller = FormController(project.feedback_form)

    if request.method == 'POST' and item:
        feedback_controller.validate_from_request(request)

        if feedback_controller.errors:
            request.session.flash('There was a problem with your feedback', 'errors')
        else:
            if not feedback:
                feedback = FeedbackRecord(project, request.user, item)
                session.add(feedback)
    
            feedback.update_submitted()
            feedback_controller.populate_record_from_request(feedback, request)
    
            request.session.flash('Feedback on %s submitted' % item.title, 'messages')
    
            # Once feedback is submitted, load the next
            # record from the top of the list
    
            if request.params.get('submit','') == 'save_and_next':
                return HTTPFound(
                    location=route_url('project:feedback', request, project_id=project.id)
                )
            else:
                return HTTPFound(
                    location=route_url('project:feedback:item', request, project_id=project.id, item_id=item.id)
                )

    return dict(
        pending_items=pending_items,
        completed_items=completed_items,
        item=item,
        item_values=item_controller.render_values(request, item),
        form_widgets=feedback_controller.render_widgets(request, feedback),
        project=project,
        responsive_layout=True,
    )
开发者ID:trip42,项目名称:CommitteeSpot,代码行数:60,代码来源:feedback.py

示例14: record_first

def record_first(project, request):
    if project.items:
        return HTTPFound(
            location=route_url("project:record", request, project_id=project.id, record_id=project.items[0].id)
        )
    else:
        return HTTPFound(location=route_url("project:record:add", request, project_id=project.id))
开发者ID:trip42,项目名称:CommitteeSpot,代码行数:7,代码来源:records.py

示例15: activate

def activate(request):
    """
    """
    user_id = request.matchdict.get('user_id')
    user = AuthUser.get_by_id(user_id)
    submitted_hmac = request.matchdict.get('hmac')
    current_time = time.time()
    time_key = int(base64.b64decode(submitted_hmac[10:]))
    if current_time < time_key:
        hmac_key = hmac.new('%s:%s:%d' % (str(user.id), \
                            apex_settings('auth_secret'), time_key), \
                            user.email).hexdigest()[0:10]
        if hmac_key == submitted_hmac[0:10]:
            user.active = 'Y'
            DBSession.merge(user)
            DBSession.flush()
            flash(_('Account activated. Please log in.'))
            activated_route = apex_settings('activated_route')
            if not activated_route:
                activated_route = 'apex_login'
            return HTTPFound(location=route_url(activated_route, request))

    flash(_('Invalid request, please try again'))
    return HTTPFound(location=route_url(apex_settings('came_from_route'), \
                                        request))
开发者ID:akirisolutions-zz,项目名称:apex,代码行数:25,代码来源:views.py


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