Python bottle.request 模块,get_cookie() 实例源码

我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用bottle.request.get_cookie()

项目:bottle_beginner    作者:denzow    | 项目源码 | 文件源码
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)
项目:bottle_beginner    作者:denzow    | 项目源码 | 文件源码
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")
项目:pyfan    作者:raptorz    | 项目源码 | 文件源码
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("/")
项目:indiwebmanager    作者:knro    | 项目源码 | 文件源码
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
###############################################################################
项目:indiwebmanager    作者:knro    | 项目源码 | 文件源码
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
###############################################################################
项目:BREIZHCTF2K16    作者:Ganapati    | 项目源码 | 文件源码
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>'
项目:ssland    作者:laobubu    | 项目源码 | 文件源码
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.
项目:modernpython    作者:rhettinger    | 项目源码 | 文件源码
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
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
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)
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
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
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
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
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
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
项目:python-exercise    作者:geniustesda    | 项目源码 | 文件源码
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"
项目:Pardus-Bulut    作者:ferhatacikalin    | 项目源码 | 文件源码
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))
项目:anom-py    作者:Bogdanp    | 项目源码 | 文件源码
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]
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
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
项目:python_web    作者:lzhaoyang    | 项目源码 | 文件源码
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"
项目:ray    作者:felipevolpone    | 项目源码 | 文件源码
def _get_logged_user():
    token = bottle_req.get_cookie(_COOKIE_NAME)
    if not token:
        return None
    return application.get_authentication().unpack_jwt(token)
项目:bottle-py    作者:today-open    | 项目源码 | 文件源码
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
项目:Mmrz-Sync    作者:zhanglintc    | 项目源码 | 文件源码
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
项目:bottle_beginner    作者:denzow    | 项目源码 | 文件源码
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"
        })