天天看點

基于hi-nginx的web開發(python篇)——cookie和會話管理

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配置寫下來,就是:

1 server {
 2     listen 8080;
 3     server_name localhost;
 4 
 5         userid                  on;
 6         userid_name             SESSIONID;
 7         userid_domain           localhost;
 8         userid_path             /;
 9         userid_expires          300s;
10 
11         hi_redis_host 127.0.0.1;
12         hi_redis_port 6379;
13 
14     
15     location / {
16         hi_need_cache off;
17         hi_cache_expires 5s;
18 
19         hi_need_session on;
20         hi_session_expires 300s;
21         hi_python_script python/index.py;
22     }
23 }      

需要注意是,應該確定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

1     location / {
2         hi_need_cache off;
3         hi_cache_expires 5s;
4         hi_need_cookies on;
5         hi_need_session on;
6         hi_session_expires 300s;
7         hi_python_script python/index.py;
8     }      

在操作函數中在添加相關操作:

@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模闆引擎,簡直易如反掌。

繼續閱讀