Skip to content

Instantly share code, notes, and snippets.

@k4ml
Last active April 29, 2021 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k4ml/4470758 to your computer and use it in GitHub Desktop.
Save k4ml/4470758 to your computer and use it in GitHub Desktop.
Example of Bottle app with Django style request object as first parameter to request function handler and login_required decorator.
"""
Bottle (and also Flask) seem to favor global request object that when called within
a request function handler, will return request data that specific to the current request.
This is convenience since it free you from having to pass request object from function to
function as you would have in Django. Maybe I'm too used with Django approach but having request
object explicitly passed to your function allow me to correctly think how to structure my app.
It's not just one time when designing a solution, I come to dead end because I try to access request
data not from request context. It easy to fall into that because the request object available in the
global namespace.
I have only test this under cgi environment but not really sure if it's ok to modify the request
object (like attaching user attribute to the request) in multithreaded wsgi environment.
"""
import sys
import os
from hashlib import md5
import bottle
class RequestPlugin(object):
def apply(self, callback, context):
def wrapper(*args, **kwargs):
request = bottle.request
response = callback(request, *args, **kwargs)
return response
return wrapper
requestplugin = RequestPlugin()
app = bottle.Bottle()
app.install(requestplugin)
def is_logged_in(request):
host = request.headers['Host']
cookie_name = 'SESS%s' % md5(host).hexdigest()
sid = request.cookies[cookie_name]
rs = engine.execute("SELECT * FROM sessions WHERE sid = %(sid)s", sid=sid)
if rs.rowcount > 0:
row = rs.fetchone()
if row[0] > 0:
return True
return False
def login_required(func):
def wrapper(*args, **kwargs):
request = bottle.request
request.user = None
if is_logged_in(request):
request.user = True
body = func(request, *args, **kwargs)
return body
return bottle.redirect('/')
return wrapper
@app.route('/customer/', apply=[login_required])
def customer(request):
return spos.customer.main(request, bottle.jinja2_template)
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment