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

Python webapp2.redirect函数代码示例

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

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



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

示例1: post

    def post(self,league_id):
        '''The currently logged in user wants to post a comment on this league'''
        (ct_user, url, url_linktext) = user_setup(self)
        if not ct_user:
            self.response.status = 401 #unauthorized
            return
            
        league_key = ndb.Key(CTLeague, int(league_id))
        league = league_key.get()
        if not league:
            self.response.status = 404
            return
            
        if (self.request.get('action') and self.request.get('action') == 'comment'):
            # check if he is in league
            if ct_user.key in league.members:
                # he wants to post a comment, create a new comment
                comment = CTLeagueComment(author = ct_user.key, contents = self.request.get('contents'))
                comment.put()
                league.comments.append(comment.key)
                league.put()
                #send to the league

                
                if SENDING_MAIL:
                
                    #notify users of new comment:
                    sender_address = "ChunaaviTukka.com Admin <[email protected]>"
                    subject = "New comment posted on your league \"" + league.name + "\" by \""+ ct_user.display_name +"\" at Chunaavi Tukka"
                    body = """
Hi,

The following comment has been posted at your league "%s" by user %s.

"%s"

You can reply to it at http://www.chunaavitukka.com/l/%s/

regards,
The Chunaavi Tukka Team
...putting the guesswork back into politics
www.chunaavitukka.com
""" % (league.name, ct_user.display_name, self.request.get('contents'), league_id)
                    #logging.error(body)
                    for user_key in league.members:
                        mail.send_mail(sender_address, user_key.get().google_user.email(), subject, body)
                        #logging.error(user_key.get().google_user.email())
                
                return webapp2.redirect('/l/' + str(league.key.id()) + '/')
            else:
                self.response.status = 501
                return
            
            
        #TODO transaction?    
        league.members.append(ct_user.key)
        league.put()
        ct_user.leagues.append(league_key)
        ct_user.put()
        return webapp2.redirect('/l/' + str(league.key.id()) + '/')
开发者ID:animeshpathak,项目名称:chunaavitukka,代码行数:60,代码来源:ctmain.py


示例2: get

    def get(self, campaign_id, platform_name):
        """
        Handles incoming clicks for given campaign_id and platform_name.
        If click is valid then user is redirected to url defined in the campaign
        and statistic about this click is saved. All invalid clicks (e.g. for non
        existing campaigns, platforms) users are redirected to http://outfit7.com.
        """
        # cast campaign_id, type checking is done through route definition
        try:
            campaign_id = int(campaign_id)
        except ValueError:
            return webapp2.redirect("http://outfit7.com", permanent=True)

        platform_id = "%d-%s" % (campaign_id, platform_name)
        platform = Platform.get_by_id(platform_id)
        if platform:
            memcache.incr(platform_id, 1, namespace="counters", initial_value=0)
            try:
                deferred.defer(Platform.increment, platform_id, _countdown=TRACKER_COUNTER_UPDATE_INTERVAL_LENGTH,
                               _name="%s-%d" % (platform_id, get_interval_index()))
            except (taskqueue.TaskAlreadyExistsError, taskqueue.TombstonedTaskError), e:
                pass
            # TODO: optimize with async operations
            campaign = Campaign.get_by_id(campaign_id)
            return webapp2.redirect(campaign.link.encode("utf8"))
开发者ID:AdTech1001,项目名称:ClickTracker-1,代码行数:25,代码来源:tracker.py


示例3: get

 def get(self):
     action = cgi.escape(self.request.get('action'))
     code = cgi.escape(self.request.get('code'))
     name = cgi.escape(self.request.get('name'))
     year = cgi.escape(self.request.get('year'))
     _credits = self.request.get_all('credit')
     credits = [0, 0, 0, 0, 0]
     
     if(code!="" and name!="" and year!=""):
         i = 0
         for credit in _credits:
             if not credit:
                 credits[i] = 0
             else:
                 credits[i] = int(cgi.escape(credit))
             i += 1
         if(action == "add"):
             Course(parent=ParentKeys.course,
                    code=code,
                    name=name,
                    year=int(year),
                    credits=credits).put()
             return webapp2.redirect('/{0}/{1}'.format(Index.adminUrl,
                                                     Index.manageCourseUrl))
         elif(action == "update"):
             course = Course.query(ancestor=ParentKeys.course)
             course = course.filter(Course.code==code).get()
             course.name = name
             course.year = int(year)
             course.credits = credits
             course.put()
             return webapp2.redirect('/{0}/{1}'.format(Index.adminUrl,
                                                     Index.manageCourseUrl))
         elif(action == "delete"):
             course = Course.query(ancestor=ParentKeys.course)
             course = course.filter(Course.code==code).get()
             cs = CourseSubject.query(ancestor=ParentKeys.courseSubject)
             cs = cs.filter(CourseSubject.courseCode==code)
             for c in cs:
                 c.key.delete()
             course.key.delete()
             return webapp2.redirect('/{0}/{1}'.format(Index.adminUrl,
                                                     Index.manageCourseUrl))
         elif(action == "manage"):
             return webapp2.redirect('/{0}/{1}?code={2}'.format(Index.adminUrl,
                                                     Index.manageCourseSubjectUrl,
                                                     code))
             
             
     courses = Course.query(ancestor=ParentKeys.course)
     templateValues = {
         'title' : Index.title + ' - Admin - Manage Courses',
         'navigator' : Index.adminNavigator,
         'action' : Index.manageCourseUrl,
         'method' : 'get',
         'courses' : courses,
     }
     
     path = os.path.join(os.path.dirname(__file__), 'html/Course.html')
     self.response.out.write(template.render(path, templateValues))
开发者ID:jiushiyuannv,项目名称:AStudentRegisterSystem,代码行数:60,代码来源:main.py


示例4: _handle_post

  def _handle_post(self, request, user):
    """Handles POST requests from the project form.

    Args:
      request: The HTTP request.
      user: The current user.

    Returns:
      A redirect to the redirect URI.
    """

    user_data = UserData.all().filter('user =', user).get()
    new_user_data = {}
    if user_data:
      new_user_data = user_data.user_data

    for data in self._parameters:
      entered_value = request.get(data['name'])
      if not entered_value and data['required']:
        webapp2.redirect(URL_PATH)
      new_user_data[data['name']] = entered_value

    if user_data:
      user_data.user_data = new_user_data
      user_data.save()
    else:
      user_data = UserData(user=user, user_data=new_user_data)
      user_data.put()

    return webapp2.redirect(self._redirect_uri)
开发者ID:briandorsey,项目名称:compute-appengine-demo-suite-python,代码行数:30,代码来源:user_data.py


示例5: get

    def get(self):
        user = users.get_current_user()
        if user:


            greeting = (" <a href=\"%s\">Log out</a>" %
                        ( users.create_logout_url("/login")))
            logoutURL = users.create_logout_url("/login")
            is_logged_in = True
            name = user.nickname()

            userQuery = User.gql("WHERE name='{}'".format(name)).get()
            # self.response.write(userQuery)
            if (userQuery == None):
                e = User(name=user.nickname(),join_date=datetime.datetime.now().date(), email=users.get_current_user().email(),userObject=users.get_current_user())
                e.put()
                return redirect('/selectmajor')
            else:
                return redirect('/dashboard')
        else:
            greeting = ("%s" %
                        users.create_login_url("/login"))
            is_logged_in = False
            logoutURL =  users.create_login_url("/")
            name = "no name"

        output = {
            'name': name,
            'is_logged_in': is_logged_in,
            'greeting': greeting,
            'logoutURL': logoutURL,
            }
        path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
        self.response.write(template.render(path, output))
开发者ID:sampwing,项目名称:cmpe231_project,代码行数:34,代码来源:main.py


示例6: get

	def get(self):
		rss_url = self.request.get('url')
		
		if len(rss_url) == 0 or len(rss_url.strip(' ')) == 0:
			return webapp2.redirect('/')
		
		d = feedparser.parse(rss_url)
		
		if bool(d['entries']) == False:
			return webapp2.redirect('/')
		
		feedLeft = []
		feedRight = []
		i = 0

		for entry in d['entries']:
			if i==0:
				feedLeft.append(entry)
				i = 1
			else:
				feedRight.append(entry)
				i = 0

		template_values = {
			'title'    : 'Feed',
            'feedLeft' : feedLeft,
            'feedRight': feedRight
        }

		path = os.path.join(os.path.dirname(__file__), 'views/feed.html')
		self.response.out.write(template.render(path, template_values))
开发者ID:vshete,项目名称:rss-reader,代码行数:31,代码来源:feed.py


示例7: check_login_before

 def check_login_before(request,  *args, **kwargs):
     if not users.get_current_user():
         # If handler has no login_url specified invoke a 403 error
         try:
             webapp2.redirect(users.create_login_url(request.uri).replace("use_json","x"), abort=True)
         except (AttributeError, KeyError), e:
             webapp2.abort(403)
开发者ID:Web5design,项目名称:CommonConsensus,代码行数:7,代码来源:webapp2_flask.py


示例8: post

 def post(self):
     #Check referer to prevent CSRF
     #if self.request.referer != "http://www.kylevermeer.com/blog/create_new":
     #    return webapp2.redirect('/about')
     title = self.request.get("title") 
     author = self.request.get("author")
     body = self.request.get("body")
     password = self.request.get("password")
     
     #Check password
     if password != "betsy says post":
         return webapp2.redirect('/blog')
         
     
     blog_post_number_query = BlogPost.all(keys_only=True)
     num_blog_posts = blog_post_number_query.count()
     new_blog_post_num = str(num_blog_posts+1)
     new_key_name = "BlogPost" + new_blog_post_num
     
     #Find last blog post to set up linked list
     last_blog_post = BlogPost.get_by_key_name("BlogPost"+str(num_blog_posts))
     new_blog_post = BlogPost(author=author,title=title,body=body, key_name= new_key_name)
     
     #If this is first blog post
     if last_blog_post is None:
         new_blog_post.next = None
     else :
         last_blog_post.previous = new_blog_post.key()
         last_blog_post.put()
         new_blog_post.next = last_blog_post.key()
     new_blog_post.previous = None
     new_blog_post.put()
     self.response.out.write("")
     return webapp2.redirect('/blog')
开发者ID:KyleV35,项目名称:KyleVermeer.com,代码行数:34,代码来源:kyle.py


示例9: _handle_post

  def _handle_post(self, request, user):
    """Handles POST requests from the project form.

    Args:
      request: The HTTP request.
      user: The current user.

    Returns:
      A redirect to the redirect URI.
    """

    user_data = UserData.all().filter('user =', user).get()
    new_user_data = {}
    if user_data:
      new_user_data = user_data.user_data

    for data in self._parameters:
      entered_value = request.get(data['name'])
      if not entered_value and data['required']:
        webapp2.redirect(URL_PATH)
      if data['type'] == 'list':
        # Convert string to list by spliting on commas and stripping whitespace.
        entered_value = [v.strip() for v in entered_value.split(',')]
      new_user_data[data['name']] = entered_value

    if user_data:
      user_data.user_data = new_user_data
      user_data.save()
    else:
      user_data = UserData(user=user, user_data=new_user_data)
      user_data.put()

    return webapp2.redirect(self._redirect_uri)
开发者ID:saadnabs,项目名称:compute-appengine-demo-suite-python,代码行数:33,代码来源:user_data.py


示例10: check_data

    def check_data(request_handler, *args, **kwargs):
      """Checks for required data and redirects to form if not present..

      Args:
        request_handler: The app engine request handler method.
        *args: Any request arguments.
        **kwargs: Any request parameters.

      Returns:
        Callable function.
      """
      user = users.get_current_user()
      if not user:
        return webapp2.redirect(
            users.create_login_url(request_handler.request.uri))

      user_data = UserData.all().filter('user =', user).get()
      if user_data:
        self.stored_user_data = user_data.user_data

      for parameter in self._parameters:
        if parameter['required']:
          if not (user_data and user_data.user_data.get(parameter['name'])):
            return webapp2.redirect(self.url_path)

      try:
        return method(request_handler, *args, **kwargs)
      finally:
        self.stored_user_data = {}
开发者ID:saadnabs,项目名称:compute-appengine-demo-suite-python,代码行数:29,代码来源:user_data.py


示例11: get

	def get(self, shorturl):
		urls = db.Query(Urls)
		#urls = db.Query(Urls, projection=('shorturl','url'))
		urls.filter('shorturl =',shorturl)
		result = urls.get()
		if result is None:
			return webapp2.redirect('/')
		return webapp2.redirect(str(result.url))
开发者ID:tilenkranjc,项目名称:redirector,代码行数:8,代码来源:views.py


示例12: get

 def get(self, name):
     link = get_link(name)
     if link: #TODO check why params no wok 
         taskqueue.add(url='/admin/stats/%s' % name, params={}) # even if link not exist?
         return webapp2.redirect(str(link.uri))
     else:
         #TODO LMGTFY do Google I feel lucky on *name* redirect there instead
         return webapp2.redirect('/')
开发者ID:hollerith,项目名称:zapit,代码行数:8,代码来源:main.py


示例13: post

 def post(self):
     package = self.request.get("package")
     method, package = package.rsplit("-", 1)
     try:
         url = packages[method]["urls"][package]
         return webapp2.redirect(url)
     except KeyError:
         return webapp2.redirect(self.request.referer)
开发者ID:guardian,项目名称:subscriptions-old,代码行数:8,代码来源:subscription.py


示例14: auth

 def auth(self):
     id = self.session.get('user')
     if id and id != None:
         user = User.get_by_id(id)
         if not user:
             return webapp2.redirect('/', False, True)
     else:
         return webapp2.redirect('/', False, True)
开发者ID:srijib,项目名称:rideshare-2,代码行数:8,代码来源:base_handler.py


示例15: get

 def get(self):
   """Renders index.html."""
   if self.request.headers['Host'] == 'apprtc.net':
     webapp2.redirect('https://www.apprtc.net', permanent=True)
   # Parse out parameters from request.
   params = get_room_parameters(self.request, None, None, None)
   # room_id/room_link will not be included in the returned parameters
   # so the client will show the landing page for room selection.
   self.write_response('index_template.html', params)
开发者ID:boucherv,项目名称:apprtc,代码行数:9,代码来源:apprtc.py


示例16: get

 def get(self):
     auth = get_auth(self.request)
     user = auth.get_user_by_session()
     if user is not None:
         return webapp2.redirect("/")
     api = get_brave_api()
     success = self.request.host_url + '/loginok'
     failure = self.request.host_url + '/login'
     result = api.core.authorize(success=success, failure=failure)
     return webapp2.redirect(result.location)
开发者ID:eve-val,项目名称:contract-watcher,代码行数:10,代码来源:main.py


示例17: invalid_user_handler

def invalid_user_handler(sender, exception, request, response):
    # if the request was via GET then pass the url to the login handler. If it was POST
    # then we need to drop it - POST requests shouldn't be forwarded.
    if request.method == 'GET':
        continue_url = request.path_qs
    else:
        continue_url = ''

    redirect_url = webapp2.uri_for(request.handler_config['routes']['login'], continue_url=continue_url)
    webapp2.redirect(uri=redirect_url, request=request, response=response)
开发者ID:LighthouseUK,项目名称:koala-quick-start,代码行数:10,代码来源:frontend.py


示例18: post

    def post(self):
	user = users.get_current_user()
	if user:
		n = Notes(author=user.user_id(),
				title=self.request.get('title'),
				text=self.request.get('text'),
				priority=self.request.get('priority'),
				status=self.request.get('status'))
		n.put()
		return webapp2.redirect('/home')
	else:
		return webapp2.redirect('/')
开发者ID:Ratha-s,项目名称:myrepo,代码行数:12,代码来源:views.py


示例19: checkIfRedirect

def checkIfRedirect(self):
  parsed_args = ''
  if self.request.headers['Host'] in constants.REDIRECT_DOMAINS:
    for argument in self.request.arguments():
      parameter = '=' + self.request.get(argument)
      if parsed_args == '':
        parsed_args += '?'
      else:
        parsed_args += '&'
      parsed_args += argument + parameter
    redirect_url = constants.REDIRECT_URL + self.request.path + parsed_args
    webapp2.redirect(redirect_url, permanent=True, abort=True)
开发者ID:ming7310,项目名称:apprtc,代码行数:12,代码来源:apprtc.py


示例20: success

 def success(self):
     """Success return"""
     jsonReply = self.request.get("json-reply")
     if jsonReply:
         self.response.set_status(200)
         self.response.headers["Content-Type"] = "application/json"
         self.response.headers.add_header(
             "Access-Control-Allow-Origin", "*"
         )
         self.response.out.write(json.dumps({"message": "success"}))
     else:
         successUrl = str(self.request.get("success-url"))
         webapp2.redirect(self.getUrl(successUrl), response=self.response)
开发者ID:GDGVienna,项目名称:cfp-manager,代码行数:13,代码来源:proposal.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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