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("/")
python类set_cookie()的实例源码
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 do_login():
username = request.forms.get('username')
password = get_salted_password()
current_user = user.get_by_username(username)
logined = current_user and current_user.salted_password == password
if logined:
response.set_cookie('ssl_uid', str(current_user.id))
response.set_cookie('ssl_pw', password)
return redirect('/')
return template('login',
username=username,
message='User not found.' if not current_user else 'Password is incorrect.',
salt=config.USER_SALT
)
def check_credentials():
user = request.forms.get('user', '')
password = request.forms.get('password', '')
if not pubsub.check_user(user, password):
return show_main_page()
token = secrets.token_bytes(32)
logged_in_users.setdefault(token, user)
response.set_cookie('token', token, max_age=60, secret=secret)
return show_main_page(user)
def enter():
"""
??????????
????????cookie??????????????????????
:return:
"""
# POST??????
username = request.POST.get("username")
print("POST username is ", username)
# cookie????
response.set_cookie("username", username)
return redirect("/chat_room")
def get_():
auth, data = get_authorization(config['CLIENT_KEY'], config['CLIENT_SECRET'],
config.get('ACCESS_TOKEN'), config.get('ACCESS_SECRET'),
"http://{host}:{port}/callback".format(host=config['web_addr'],
port=config['web_port']),
config.get('FANFOU_HTTPS', True))
if auth:
return index_template(u"Login ok.<br/>User: {}.<br/><a href='/logout'>Logout</a>.".format(data['screen_name']))
else:
if not data or isinstance(data, Exception):
return str(data)
else:
response.set_cookie("request_token", json.dumps(data['token']), path="/")
redirect(data['url'])
def update_profile(name):
"""Update profile info (port & autostart)"""
response.set_cookie("indiserver_profile", name,
None, max_age=3600000, path='/')
data = request.json
port = data.get('port', args.indi_port)
autostart = bool(data.get('autostart', 0))
db.update_profile(name, port, autostart)
def start_server(profile):
"""Start INDI server for a specific profile"""
global saved_profile
saved_profile = profile
global active_profile
active_profile = profile
response.set_cookie("indiserver_profile", profile,
None, max_age=3600000, path='/')
start_profile(profile)
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_mount_wsgi(self):
@self.subapp.route('/cookie')
def test_cookie():
response.set_cookie('a', 'a')
response.set_cookie('b', 'b')
self.app.mount('/test', self.subapp)
c = self.urlopen('/test/cookie')['header']['Set-Cookie']
self.assertEqual(['a=a', 'b=b'], list(sorted(c.split(', '))))
def create_session(user):
session = Session.create(user)
response.set_cookie("sid", session.key.str_id)
# [END 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 logout():
response.set_cookie('ssl_uid', '', expires=0)
response.set_cookie('ssl_pw', '', expires=0)
return redirect('/login')
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 counter():
count = int( request.cookies.get('counter', '0') )
count += 1
response.set_cookie('counter', str(count))
return 'You visited this page %d times' % count
def _handle_ping_status():
cookie_name, user_token = increase_cookie_timestamp()
bottle_resp.set_cookie(cookie_name, user_token.decode('utf-8'))
def login_admin(db):
psw = request.forms.get("password")
salt = request.forms.get("salt")
s = db.query(Secret).filter_by(id=1).first().hash
if check_secret(psw, salt, s):
response.set_cookie("session-key", s, path='/', max_age=72000)
return json.dumps({'data': 'ok'})
else:
return json.dumps({'data': 'can not auth.'})