我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用web.seeother()。
def POST(self): form = myform() if not form.validates(): return render.formtest(form) else: # form.d.boe and form['boe'].value are equivalent ways of # extracting the validated arguments from the form. global question global answer global chat_history global after_question question = form['??'].value after_question = stopwords.eliminate_stop_words(question) answer = robot.chat(after_question) chat_history.append(question) chat_history.append(answer) if answer is "": raise web.seeother('/add') web.header('Content-Type','text/html; charset=utf-8', unique=True) # let the browser use the utf-8 encoding form['??'].set_value('') return render.answer(answer,chat_history, form) # return "Grrreat success! boe: %s, bax: %s, area: %s" % (form.d.boe, form['bax'].value, form['moe'].value)
def GET(self): log.debug('connect.GET') user = current_user() if user: log.debug('user is {0}'.format(user)) st = smartthings.SmartThings() params = web.input() log.debug('params is {0}'.format(params)) if 'code' in params: # We just logged into SmartThings and got an OAuth code. user['token'] = st.token(params) user[SHORT_KEY] = new_shortcode( collection=users.collection, keyname=SHORT_KEY, ) users.register(**user) # not totally sure why need ** result_url = '/data/{0}'.format(user[SHORT_KEY]) raise web.seeother(result_url) else: # We are about to redirect to SmartThings to authorize. raise web.seeother(st.auth_url()) else: log.error('/connect was accessed without a user session.') raise web.seeother('/error')
def POST(self): # one round end, so we enter game page in init status, stop user return back if Game.one_round_end: raise web.seeother('/game') if Game.service.next_turn(): DBHelper.update_record(Game.service.current_player,Game.service.sum_turns,strftime("%Y-%m-%d %H:%M:%S", localtime(time()))) messages = ["Player %s has won the game in %d turns. CONGRATULATIONS!" % (Game.service.current_player.name,Game.service.sum_turns)] if DBHelper.record_is_broken(Game.service.sum_turns): plus = 'You Just Broken A Record! Have A Look!' messages.append(plus) # Current game finish Game.one_round_end = True return render.gameover(messages=messages) else: current_player = Game.service.current_player messages = Game.service.messages return render.game(current_player=current_player,messages=messages)
def POST(self): if not 'user' in session or session.user is None: f = register_form() return render.login(f) i = web.input(id=None, description=None) cluster_id = i.id if cluster_id is None: return render.error("No cluster id specified.") if not cluster_id.isdigit(): return render.error("Invalid number.") cluster_id = int(cluster_id) desc = i.description vars = {"id":cluster_id} db = open_db() db.update('clusters', vars=vars, where="id = $id", description=desc) raise web.seeother("/view_cluster?id=%d" % cluster_id) #-----------------------------------------------------------------------
def GET(self): time.sleep(sleep_time) # json raise web.seeother('/static/queryGroupInfo.json')
def GET(self): time.sleep(sleep_time) # base64 json raise web.seeother('/static/queryGroupList_64.json')
def GET(self): # this is used to "setup" the session with starting values session.room = map.START web.seeother("/game")
def POST(self): form = web.input(action=None) # there is a bug here, can you fix it? if session.room and form.action: session.room = session.room.go(form.action) web.seeother("/game")
def GET(self): raise web.seeother('/static/index.html')
def GET(self, name=None): """ This function processes the GET requests from the site """ if name: print(name) data = web.input() print(data) if session.get('loggedin', None): f = plantsForm() return self.render.index(f, getTable) else: web.seeother('login')
def POST(self): """ Called when the user enters login data """ f = loginForm() if f.validates(): session.loggedin = True data = web.input() if connection.create_connection( data['Host'], data['User'], data['Password'], data['Database']) == 0: return web.seeother('/') else: return self.render.login(f) else: return self.render.login(f)
def GET(self): session.kill() web.seeother('/login')
def login(): """ Logs the user in by manipulating their session. Raises: web.seeother: Raises the '/app' endpoint to the client. """ session.logged_in = True raise web.seeother('/app')
def GET(self): """ Logs the user out by manipulating their session. Raises: web.seeother: Raises the '/' endpoint to the client. """ session.logged_in = False raise web.seeother('/')
def loggedIn(): """ Checks whether the user's session is logged in. Returns: True for logged in, or raises the / endpoint if not logged in. Raises: web.seeother: Raises the '/' endpoint if not logged in. """ if session.get('logged_in', False): return True else: raise web.seeother('/')
def GET(self): return web.seeother('static/index.html')
def POST(self): raise web.seeother('/')
def POST(self): form = formA() self.new_question = question if not form.validates(): return render.add(question, form) else: new_answer = form['Answer'].value web.header('Content-Type','text/html; charset=utf-8', unique=True) print self.new_question global after_question robot.addAnswer(after_question, new_answer) raise web.seeother('/')
def POST(self): x = web.input(myfile={}) filedir = '.\\File' # change this to the directory you want to store the file in. if 'myfile' in x: # to check if the file-object is created filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones. filename=filepath.split('\\')[-1] # splits the and chooses the last part (the filename with extension) fout = open(filedir +'\\'+ filename,'wb') # creates the file where the uploaded file should be stored fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file. fout.close() # closes the file, upload complete. filename = filedir+"\\"+filename if 'doc' or 'pdf' in filename[-4:]: printer(filename) # else if 'pdf'in filename[-4:]: TODO finish pdf printing # doc_print(filename,printer='arco') raise web.seeother('/upload')
def POST(self): log.debug('register.POST') params = web.input() username = params["username"] password = params["password"] user = users.register( username=username, password=users.pswd(password, username), ) users.login(user) log.debug('user is {0}'.format(user)) raise web.seeother('/')
def POST(self): log.debug('login.POST') params = web.input() user = users.authenticate( params["username"], params["password"], ) if user: log.debug('user is {0}'.format(user)) users.login(user) raise web.seeother('/') else: log.error('login failed, so user not set') raise web.seeother('/error')
def GET(self): log.debug('logout.GET') users.logout() # runs session.kill() raise web.seeother('/')
def GET(self, shortcode): log.debug('data.GET') user = users.collection.find_one({SHORT_KEY: shortcode}) if user: log.debug('shortcode {0} matches user {1}'.format(shortcode, user)) else: log.debug('no user found matching shortcode') raise web.seeother('/error') return render.data(processor.results(user["token"]))
def POST(self): mfeed.publish('<p>%s</p>' % web.input().text + (" " * 2048)) web.seeother('/')
def test_redirect(self): urls = ( "/(.*)", "blog" ) class blog: def GET(self, path): if path == 'foo': raise web.seeother('/login', absolute=True) else: raise web.seeother('/bar') app_blog = web.application(urls, locals()) urls = ( "/blog", app_blog, "/(.*)", "index" ) class index: def GET(self, path): return "hello " + path app = web.application(urls, locals()) response = app.request('/blog/foo') self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/login') response = app.request('/blog/foo', env={'SCRIPT_NAME': '/x'}) self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/x/login') response = app.request('/blog/foo2') self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/blog/bar') response = app.request('/blog/foo2', env={'SCRIPT_NAME': '/x'}) self.assertEquals(response.headers['Location'], 'http://0.0.0.0:8080/x/blog/bar')
def GET(self): i = web.input(url='/') raise web.seeother(i.url)
def redirectTo( page, **kwargs ): dest = '/%s?%s' % ( page, urllib.urlencode( kwargs ) ) raise web.seeother( dest )
def POST(self): form = web.input(player_name="Nobody") # need session.player_names = [] for name in form.player_name.split(','): session.player_names.append(name) raise web.seeother('/game')
def POST(self): i = web.input(username="", password="") if i.username == "" or i.password == "": return render.error("Invalid username or password") elif i.username != CN_USER or sha1(i.password).hexdigest() != CN_PASS: return render.error("Invalid username or password") session.user = i.username return web.seeother("/") #-----------------------------------------------------------------------
def GET(self): session.user = None del session.user return web.seeother("/") #-----------------------------------------------------------------------
def __init__(self, url, absolute=False): status = '303 See Other' newloc = url home = web.ctx.environ['HTTP_ORIGIN'] newloc = urlparse.urljoin(home, url) logger.info('seeother: %s', newloc) headers = { 'Content-Type': 'text/html', 'Location': newloc } web.webapi.HTTPError.__init__(self, status, headers, "") pass
def GET(self, account): """ get account information for given account name. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 404 Not Found 500 InternalError :param Rucio-Account: Account identifier. :param Rucio-Auth-Token: as an 32 character hex string. :returns: JSON dict containing informations about the requested user. """ header('Content-Type', 'application/json') if account == 'whoami': # Redirect to the account uri frontend = ctx.env.get('HTTP_X_REQUESTED_HOST') if frontend: raise redirect(frontend + "/accounts/%s" % (ctx.env.get('issuer'))) raise seeother(ctx.env.get('issuer')) acc = None try: acc = get_account_info(account) except AccountNotFound, e: raise generate_http_error(404, 'AccountNotFound', e.args[0][0]) except AccessDenied, e: raise generate_http_error(401, 'AccessDenied', e.args[0][0]) except RucioException, e: raise generate_http_error(500, e.__class__.__name__, e.args[0][0]) except Exception, e: print format_exc() raise InternalError(e) dict = acc.to_dict() for key, value in dict.items(): if isinstance(value, datetime): dict[key] = value.strftime('%Y-%m-%dT%H:%M:%S') del dict['_sa_instance_state'] return render_json(**dict)
def GET(self, app = None): usestale = True # Until dedicated main homepage is done if not app: app = random.choice(valid_modes) app = models.app_aliases.get(app, app) query = web.input() user = query.get("user") # TODO: Won't be much use in the big restructuring, for now try to extract app from path appfrom = query.get("from", '')[len(markup.virtual_root):].strip('/').split('/')[0] if appfrom not in valid_modes: appfrom = valid_modes[0] profile = profile_search(user) if profile: raise web.seeother(markup.generate_root_url("user/" + str(profile[0]["id64"]), appfrom)) ckey = "scrender" showcase = models.cache.get(ckey) showcase_cell = None try: if not showcase: sitems = models.schema(scope = app).processed_items.values() if len(sitems) > 0: showcase = random.choice(sitems) showcase["app"] = app # May want to add an option for showcase expiration to config later models.cache.set(ckey, showcase, time=60) app = showcase.get("app", app) showcase_cell = markup.generate_item_cell(app, showcase, user=showcase.get("user")) except Exception as E: pass markup.init_theme(app) web.ctx.notopsearch = True # Last packs packs = models.recent_inventories(scope = app) return template.index(app, (packs or []), showcase_cell)