Sanic-CookieSession - Simple Cookie-based Session for Sanic¶
Sanic-CookieSession implements a client side only, cookie-based session to be used with Sanic. Similar to the built-in session in Flask.
Warning
The session cookie is signed cryptographically to prevent modification, but the content is not encrypted, NEVER store information that need to be kept secret.
Quick Start¶
Installation¶
pip install Sanic-CookieSession
How to use it¶
from sanic import Sanic, response
import sanic_cookiesession
app = Sanic(__name__)
app.config['SESSION_COOKIE_SECRET_KEY'] = 'abcd'
sanic_cookiesession.setup(app)
@app.route('/')
def index(request):
session = request.ctx.session
session.setdefault('c', 0)
session['c'] += 1
return response.text(session['c'])
if __name__ == '__main__':
app.run(debug=True)
That’s it.
For more details, please see documentation.
License¶
BSD New, see LICENSE for details.
Links¶
Configuration¶
Option |
Description |
---|---|
|
Set the domain of cookie. Default to
|
|
Set the |
|
How long the session cookie should be valid,
in seconds. Default is |
|
The name of cookie that stores the session.
Default is |
|
The salt used in addition to the secret key
to sign the session cookie. Can be used as
namespace. Default to |
|
The secret key used to sign the session
cookie, if this is not set,
|
|
Set the |
|
The name of session object in request.
Default is |
API¶
Full Example¶
# -*- coding: utf-8 -*-
from sanic import Sanic, response
import sanic_cookiesession
app = Sanic('test_app')
app.config['SESSION_COOKIE_SECRET_KEY'] = "u can't c me"
app.config['SESSION_COOKIE_SECURE'] = False
sanic_cookiesession.setup(app)
def render(session):
tpl = """<a href="/inc">+</a> {} <a href="/dec">-</a>"""
return response.html(tpl.format(session['counter']))
@app.get('/')
async def index(request):
return render(request.ctx.session)
@app.get('/inc')
async def inc(request):
request.ctx.session['counter'] += 1
return response.redirect('/')
@app.get('/dec')
async def dec(request):
request.ctx.session['counter'] -= 1
return response.redirect('/')
@app.middleware('request')
async def create_counter(request):
request.ctx.session.setdefault('counter', 0)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, debug=True)
Changelog¶
0.3.1
New release for latest Sanic (currently 23.6)
0.2.0
API changed: changed setup function’s name
0.1.0
First public release.