我想问一下如何使用SimpleCookie(),这是Python3中cookie管理处理的标准?
simple_cookie = cookies.SimpleCookie()
simple_cookie['SESSION'] = session_val
好的,首先获取导入
from datetime import datetime, timedelta
import pytz
from http import cookies
eastern = pytz.timezone('US/Eastern') # use your current timezone
接下来,初始化cookie的Python3代码,从当前时区到GMT的日期时间,以及域
def convert_datetime_est_to_utc(date_time_dt):
expires = date_time_dt.replace(tzinfo=eastern).astimezone(pytz.utc)
return expires.strftime('%a, %d %b %Y %H:%M:%S GMT') # GMT/UTC
domain = os.environ['HTTP_HOST'].lower()
domain = domain.replace('www.', '')
now = datetime.now()
date_time_dt = now + timedelta(days=2) # a cookie that lasts for 2 days
simple_cookie = cookies.SimpleCookie()
simple_cookie['SESSION'] = session_val # should be a random string that is distinct for each user of a website
simple_cookie['SESSION']['expires'] = convert_datetime_est_to_utc(date_time_dt)
simple_cookie['SESSION']['path'] = '/'
simple_cookie['SESSION']['comment'] = 'This is the website description'
simple_cookie['SESSION']['domain'] = f""".{domain}"""
simple_cookie['SESSION']['max-age'] = str(60*60*24*2)
simple_cookie['SESSION']['secure'] = True
simple_cookie['SESSION']['samesite'] = 'None'
最后输出cookie
simple_cookie.output()
例如,向Python3 cgi输出unicode文本并输出会话cookie
def enc_print(string='', encoding='utf8'):
sys.stdout.buffer.write(string.encode(encoding) + b'n') # for unicode output Python cgi
enc_print( simple_cookie.output() )
enc_print("Content-Type:text/html;charset=utf-8;")
enc_print()
enc_print(html)
最后注意,我使用PostgreSQL SELECT uuid_generate_v1()和SELECT uuid_generate_v4()语句生成我的session_val,例如,uuid_session = uuid_v1 + '_' + uuid_v4,然后在数据库中检查它是不同的,但你可以使用Python3 random也
import random
def password(length=11):
#chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + '!@#$%^&*()+'
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
pwd = ''.join(random.choice(chars) for x in range(length))
return pwd[:length]
print( password(50) )