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 模板引擎, 简直易如反掌
来源: http://www.bubuko.com/infodetail-2542429.html