我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用bottle.request.get_cookie()。
def chat_room(): """ ????????? :return: """ # cookie??????request???? username = request.get_cookie("username") # cookie??????????????????? if not username: return redirect("/") # ????????????????????? talk_list = get_talk() return template("chat_room", username=username, talk_list=talk_list)
def talk(): """ ???????????????????????? :return: """ # ????????????get????getunicode??? chat_data = request.POST.getunicode("chat") # ????cookie???? username = request.get_cookie("username") # ?????? talk_time = datetime.now() # ???? save_talk(talk_time, username, chat_data) return redirect("/chat_room")
def get_callback(): request_token = json.loads(request.get_cookie("request_token")) response.set_cookie("request_token", "", path="/") access_token = get_access_token(config['CLIENT_KEY'], config['CLIENT_SECRET'], request_token, config.get('FANFOU_HTTPS', True)) if not access_token or isinstance(access_token, ValueError): return index_template(u"Invalid request token") with open(get_fullname("config.json"), "r+") as f: access_config = json.loads(f.read()) access_config['ACCESS_TOKEN'] = access_token['oauth_token'] access_config['ACCESS_SECRET'] = access_token['oauth_token_secret'] f.seek(0) f.truncate() f.write(json.dumps(access_config)) config.update(access_config) redirect("/")
def main_form(): """Main page""" global saved_profile drivers = collection.get_families() if not saved_profile: saved_profile = request.get_cookie('indiserver_profile') or 'Simulators' profiles = db.get_profiles() return template(os.path.join(views_path, 'form.tpl'), profiles=profiles, drivers=drivers, saved_profile=saved_profile) ############################################################################### # Profile endpoints ###############################################################################
def stop_server(): """Stop INDI Server""" indi_server.stop() global active_profile active_profile = "" # If there is saved_profile already let's try to reset it global saved_profile if saved_profile: saved_profile = request.get_cookie("indiserver_profile") or "Simulators" ############################################################################### # Driver endpoints ###############################################################################
def page(data=None): IV = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) json_data = json.dumps({'username': 'Guest', 'flag': FLAG}) data = cipher(json_data, KEY, IV) if request.get_cookie("secret_data"): secret_data = request.get_cookie("secret_data") try: try: if "libwww-perl" in request.headers.get('User-Agent'): # Anti Padbuster simple response.set_header('Set-Cookie', 'secret_data=%s' % data) return "Attack detected." plain = uncipher(secret_data, KEY) data = json.loads(plain) print data return "Hello %s." % data['username'] except PaddingError: response.set_header('Set-Cookie', 'secret_data=%s' % data) return "Padding error." except: response.set_header('Set-Cookie', 'secret_data=%s' % data) return "Secret value error." else: response.set_header('Set-Cookie', 'secret_data=%s' % data) return '<a href="/">Enter website</a>'
def require_login(func): def func_wrapper(*args, **kwargs): global current_user, is_admin uid_str = request.get_cookie('ssl_uid') password = request.get_cookie('ssl_pw') logined = uid_str and password if logined: current_user = user.get_by_id(int(uid_str)) logined = current_user and current_user.salted_password == password is_admin = logined and current_user.id == config.USER_ADMIN if not logined: response.set_cookie('ssl_uid', '', expires=0) response.set_cookie('ssl_pw', '', expires=0) return redirect('/login') return func(*args, **kwargs) return func_wrapper # decorator that used for user json APIs. Decorated function shall return a dict.
def get_logged_in_user(): token = request.get_cookie('token', secret=secret) if token is not None: return logged_in_users.get(token) return None
def welcome(): if request.params.get('req_thing') == "version_info": return version_info() username = request.get_cookie('username') password = request.get_cookie('password') password = urllib.unquote(password) if password else None if verify_login(username, password): redirect('/memorize') else: return dict(universal_ROUTE_dict)
def mmrz(): username = request.get_cookie('username') password = request.get_cookie('password') password = urllib.unquote(password) if password else None if not verify_login(username, password): redirect('/') # need_https = "localhost" not in request.url need_https = False return_dict = dict(universal_ROUTE_dict) return_dict.update(dict(need_https=need_https)) return return_dict
def setting(): username = request.get_cookie('username') password = request.get_cookie('password') password = urllib.unquote(password) if password else None if not verify_login(username, password): redirect('/') dbMgr = MmrzSyncDBManager("USERS") users = dbMgr.read_USERS_DB_DICT() dbMgr.closeDB() return_dict = dict(universal_ROUTE_dict) return_dict.update({"username": username, "mailAddr": "" if users[username]["mailAddr"] == None else users[username]["mailAddr"]}) return return_dict
def dictionary(): username = request.get_cookie('username') password = request.get_cookie('password') password = urllib.unquote(password) if password else None key_word = request.params.get('key_word', "???") verified = verify_login(username, password) defines = query_hujiang(key_word) return_dict = dict(universal_ROUTE_dict) return_dict.update(dict(defines=defines, verified=verified, key_word=key_word)) return return_dict
def hello_again(): if request.get_cookie("visited"): return "Welcome back! Nice to see you again" else: response.set_cookie("visited", "yes") return "Hello there! Nice to meet you"
def test_cookie_dict(self): """ Environ: Cookie dict """ t = dict() t['a=a'] = {'a': 'a'} t['a=a; b=b'] = {'a': 'a', 'b':'b'} t['a=a; a=b'] = {'a': 'b'} for k, v in t.items(): request = BaseRequest({'HTTP_COOKIE': k}) for n in v: self.assertEqual(v[n], request.cookies[n]) self.assertEqual(v[n], request.get_cookie(n))
def user_required(*permissions): def decorator(fn): def wrapper(*args, **kwargs): session_id = request.get_cookie("sid") if not session_id: return redirect("/login") session = Session.get(session_id) if not session: return redirect("/login") user = session.user.get() if user is None: return redirect("/login") for permission in permissions: if permission not in user.permissions: return abort(403) return fn(user, *args, **kwargs) return wrapper return decorator # [END user-required] # [START create-session]
def get_pagination_limit(new_limit): """Defines the right pagination limit and sets cookies accordingly. @params new_limit: new pagination limit """ default_limit = 50 limit_cookie = request.get_cookie("pagination_limit") logging.info("Got cookie: {0}".format(limit_cookie)) cookie_expires = time.mktime((datetime.now() + timedelta(days=365)).timetuple()) if new_limit <= 0: if limit_cookie: try: limit = int(limit_cookie) logging.info("Using limit from cookie: {0}".format(limit)) response.set_cookie("pagination_limit", str(limit), path="/", expires=cookie_expires) except Exception as e: logging.error("Cookie: {0}, exception: {1}".format(limit_cookie, e)) limit = default_limit else: limit = default_limit logging.info("Using default limit: {0}".format(limit)) else: limit = new_limit logging.info("Setting new limit: {0}".format(limit)) response.set_cookie("pagination_limit", str(limit), path="/", expires=cookie_expires) return limit
def _get_logged_user(): token = bottle_req.get_cookie(_COOKIE_NAME) if not token: return None return application.get_authentication().unpack_jwt(token)
def auth(fn): def _decorator(*ag, **kw): if (request.get_cookie('session-key') is not None) and (kw['db'].query(Secret).filter_by(id=1).first().hash == request.get_cookie('session-key')): return fn(*ag, **kw) #error else: return json.dumps({'data': 'not auth.'}) _decorator.__name__ = fn.__name__ return _decorator
def individual(): username = request.get_cookie('username') password = request.get_cookie('password') password = urllib.unquote(password) if password else None if not verify_login(username, password): redirect('/') user_folder = "./WORDBOOK/{0}/".format(username) user_pkl = "{0}/data.pkl".format(user_folder) if not os.path.exists(user_folder): os.mkdir(user_folder) if not os.path.exists(user_pkl): pklMgr = PickleManager(username) pklMgr.load_pkl() pklMgr.set_book_name("--") pklMgr.set_total_lines("--") pklMgr.set_last_import_time() pklMgr.set_last_import_time_int() pklMgr.dump_pkl() fr = open("./WORDBOOK/{0}/data.pkl".format(username), "rb") pkl = pickle.load(fr) fr.close() if not pkl["book_name"] == "--": fr = open("./WORDBOOK/{0}/{1}".format(username, pkl["book_name"]), "rb") content = fr.read() fr.close() lq = len(filter(lambda x: x not in ['', '\r', '\n', '\r\n'], content.split("\n"))) pkl["remained_words"] = lq pkl["import_rate"] = (1 - round(float(lq) / float(pkl["total_lines"]), 4)) * 100 days, hours, mins, secs = split_remindTime(int(time.time()) - pkl.get("last_import_time_int", 0)) pkl["time_elapsed"] = "{0}?{1}?{2}?".format(days, hours, mins) else: pkl["book_name"] = "--" pkl["total_lines"] = "--" pkl["last_import_time"] = "--" pkl["last_import_time_int"] = "--" pkl["remained_words"] = "--" pkl["import_rate"] = "--" pkl["time_elapsed"] = "--" return_dict = dict(universal_ROUTE_dict) return_dict.update(pkl) return return_dict
def talk_api(): """ ?????????API GET -> ??????? POST -> ??????? json eg. [ { talk_time:2016-09-17 15:00:49.937402 username:sayamada chat_data:???? } : }, { talk_time:2016-09-17 15:58:03.200027 username:sayamada chat_data:????? }, { talk_time:2016-09-17 15:58:12.289631 username:sayamada chat_data:?????? } ] :return: """ if request.method == "GET": talk_list = get_talk() return json.dumps(talk_list) elif request.method == "POST": # ????????????get????getunicode??? chat_data = request.POST.getunicode("chat") # ????cookie???? username = request.get_cookie("username") # ?????? talk_time = datetime.now() # ???? save_talk(talk_time, username, chat_data) return json.dumps({ "status": "success" })