基于hi-nginx的web开发(python篇)——cookie和会话管理

时间:2023-03-08 17:43:01

hi-nginx通过redis管理会话。

要开启管理,需要做三件事。

第一件开启userid:

        userid                  on;
userid_name SESSIONID;
userid_domain localhost;
userid_path /;
userid_expires 300s;

这个功能是nginx内建的,可以直接使用。需要注意的是,hi-nginx只认识SESSIONID的userid_name。

第二件是配置redis服务器:

        hi_redis_host 127.0.0.1;
hi_redis_port 6379;

当然,你应该先安装redis并确保它运行。

第三件是在location段开启会话管理:

    location  /  {
hi_need_session on;
hi_session_expires 300s;
hi_python_script python/index.py;
}

整个nginx配置写下来,就是:

 server {
listen 8080;
server_name localhost; userid on;
userid_name SESSIONID;
userid_domain localhost;
userid_path /;
userid_expires 300s; hi_redis_host 127.0.0.1;
hi_redis_port 6379; location / {
hi_need_cache off;
hi_cache_expires 5s; hi_need_session on;
hi_session_expires 300s;
hi_python_script python/index.py;
}
}

需要注意是,应该确保hi_session_expires和userid_expires的值保持一致。

配置写完后,记得reload或者restart nginx。

接下来就是使用会话管理的api了。

说来太简单,都不好意思写出来,用req.has_session,req.get_session和res.session即可:

@app.route('^/session/?$',['GET'])
def session(req,res,param):
k='test'
v=0
if req.has_session(k):
v=int(req.get_session(k))
res.session(k,str(v+1))
else:
res.session(k,str(v))
res.content('{}={}'.format(k,v))
res.status(200)

那么,cookie怎么办?人们使用cookie的一大用途建立会话机制。上文已经把会话管理的使用说清楚了。所以使用hi.py框架时不需要特别留意cookie的管理。当然,如果你想自己管理cookie,hi-nginx也提供req.has_cookie和req.get_cookie两个只读api。如果要写api,可以使用res.header来写。比如:

在location段中添加hi_need_cookies on

     location / {
hi_need_cache off;
hi_cache_expires 5s;
hi_need_cookies on;
hi_need_session on;
hi_session_expires 300s;
hi_python_script python/index.py;
}

在操作函数中在添加相关操作:

@app.route('^/session/?$',['GET'])
def session(req,res,param):
k='test'
v=0
if req.has_session(k):
v=int(req.get_session(k))
res.session(k,str(v+1))
else:
res.session(k,str(v))
cv=v
if req.has_cookie(k):
cv=int(req.get_cookie(k))
res.header('Set-Cookie','{}={};Path={};Domain={}'.format(k,cv+1,'/','localhost'))
else:
res.header('Set-Cookie','{}={};Path={};Domain={}'.format(k,cv,'/','localhost'))
res.content('session:{0}={1},cookie:{0}={2}'.format(k,v,cv))
res.status(200)

如上所见,在hi.py中操控和管理cookie和会话是非常方便的,用来写个登陆或者购物车什么的,配合hi.py的jinja2模板引擎,简直易如反掌。