• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python url.route_url函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: tag_articles

def tag_articles(request):
    _ = request.translate
    tag = request.matchdict['tag']

    page_size = int(get_config('elements_on_page'))
    start_page = 0
    if 'start' in request.GET:
        try:
            start_page = int(request.GET['start'])
        except ValueError:
            start_page = 0

    user = request.user
    dbsession = DBSession()
    q = dbsession.query(Article).join(Tag).options(joinedload('tags')).options(joinedload('user')).order_by(Article.published.desc())
    if not user.has_role('editor'):
        q = q.filter(Article.is_draft==False)

    c = {}
    c['articles'] = q.filter(Tag.tag == tag)[(start_page * page_size):(start_page+1) * page_size + 1]

    c['prev_page'] = None
    if len(c['articles']) > page_size:
        c['prev_page'] = route_url('blog_tag_articles', request, tag=tag, _query=[('start', start_page+1)])
        c['articles'].pop()

    c['next_page'] = None
    if start_page > 0:
        c['next_page'] = route_url('blog_tag_articles', request, tag=tag, _query=[('start', start_page-1)])

    c['page_title'] = _(u'Articles labeled with tag “{0}”'.format(tag))

    return c
开发者ID:sigsergv,项目名称:pyrone,代码行数:33,代码来源:blog.py


示例17: user_chirps

def user_chirps(request):
    dbsession = DBSession()
    userid = authenticated_userid(request)
    user = dbsession.query(User).filter_by(userid=userid).first()
    matchdict = request.matchdict
    other_userid = matchdict.get('userid')
    other_user = dbsession.query(User).filter_by(userid=other_userid).first()
    url = route_url('users', request, userid=other_userid)
    if other_user is None:
        return HTTPNotFound(location=url)
    chirps = dbsession.query(Chirp).filter(Chirp.author==other_user)
    chirps = chirps.order_by(Chirp.timestamp.desc()).limit(30)
    follows = dbsession.query(Follower).filter(Follower.follower==other_user.id)
    follows = follows.order_by(Follower.follows.asc()).limit(10)
    followers = dbsession.query(Follower).filter(Follower.follows==other_user.id)
    followers = followers.order_by(Follower.follower.asc()).limit(10)
    followed = dbsession.query(Follower).filter(Follower.follower==user.id)
    followed = followed.filter(Follower.follows==other_user.id).first()
    follow_url = route_url('follow', request, userid=other_userid)
    unfollow_url = route_url('unfollow', request, userid=other_userid)
    return {'app_url': request.application_url,
            'static_url': request.static_url,
            'userid': userid,
            'chirps': chirps,
            'user_chirps': True,
            'user': other_user,
            'original_user': user,
            'elapsed': get_elapsed,
            'follows': follows,
            'followers': followers,
            'followed': followed,
            'follow_url': follow_url,
            'unfollow_url': unfollow_url
        }
开发者ID:cguardia,项目名称:Pyramid-Tutorial,代码行数:34,代码来源:views.py


示例18: edit_blog_post

def edit_blog_post(request):
    session = DBSession()
    matchdict = request.matchdict
    post = session.query(Post).filter(Post.id == matchdict["post_id"]).one()

    if 'submitted' in request.params:
        fs = FieldSet(post, data=request.params)
        # TODO
        # Not sure why this is necessary...shouldn't I just be able to pass the session to FieldSet and have it sync?
        post.title = fs.title.value
        post.content = fs.content.value
        post.modified_time = time.time()
        session.add(post)

        return HTTPFound(location = route_url("view_blog_post", request, post_id = post.id))

    if 'delete' in request.params:
        session.delete(post)

        return HTTPFound(location = route_url("edit_blog", request))


    edit_blog_post_url = route_url("edit_blog_post", request, post_id = post.id)
    fs = FieldSet(post)
    fs.configure(options=[fs.content.textarea(size=(45, 10))], exclude = [fs["modified_time"], fs["created_time"], fs["user"]])
    form = fs.render()
    return dict(form = form, title = post.title, edit_blog_post_url = edit_blog_post_url)
开发者ID:zeitkunst,项目名称:FluidNexusWebsite,代码行数:27,代码来源:views.py


示例19: edit_page

def edit_page(request):
    """Edit a given page."""
    session = DBSession()
    matchdict = request.matchdict
    page = session.query(Page).join(User).filter(Page.id == matchdict["page_id"]).order_by(desc(Page.modified_time)).one()

    if 'submitted' in request.params:
        fs = FieldSet(page, data=request.params)
        # TODO
        # add validation
        # Not sure why this is necessary...shouldn't I just be able to pass the session to FieldSet and have it sync?
        page.title = fs.title.value
        page.content = fs.content.value
        page.modified_time = time.time()
        page.location = fs.location.value
        session.add(page)
        return HTTPFound(location = route_url("view_page", request, page_location = page.location))

    elif 'delete' in request.params:
        session.delete(page)
        return HTTPFound(location = route_url("edit_pages", request))



    edit_blog_post_url = route_url("edit_page", request, page_id = page.id)
    fs = FieldSet(page)
    fs.configure(options=[fs.content.textarea(size=(45, 10))], exclude = [fs["modified_time"], fs["created_time"], fs["user"]])
    form = fs.render()

    # TODO
    # Figure out how to delete using checkboxes
    return dict(title = "Edit '%s'" % page.title, save_name = save_name, delete_name = delete_name, form = form)
开发者ID:zeitkunst,项目名称:FluidNexusWebsite,代码行数:32,代码来源:views.py


示例20: save_new_user

def save_new_user(request):
    login = request.POST['login']
    email = request.POST['email']

    if len(login) == 0 or len(email) == 0:
        return Response('Bad input', content_type='text/plain', status_int=500)

    try:
        exists = DBSession.query(User).filter(or_(User.login == login,
                                                  User.email == email)).count()
        if exists > 0:
            existing_user = DBSession.query(User).filter(User.login == login).first()
            return HTTPFound(location=route_url('show_user', request, id=existing_user.id))

        user = User(login, email)
        user.first_name = request.POST['first_name']
        user.last_name = request.POST['last_name']
        user.user_name = request.POST['user_name']
        user.password = request.POST['password']
        user.gender = request.POST['gender']
        user.created_date = datetime.datetime.now()
        user.last_login_date = datetime.datetime.now()

        DBSession.add(user)
        DBSession.flush()
        return HTTPFound(location=route_url('show_user', request, id=user.id))
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
开发者ID:swordXfish,项目名称:lookwider,代码行数:28,代码来源:security.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python url.static_url函数代码示例发布时间:2022-05-27
下一篇:
Python url.route_path函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap