DEV Community

Cover image for Bottle
Anton Shcherbatov
Anton Shcherbatov

Posted on

Bottle

Bottle is a really small python-based framework. The whole its code takes 1 file with ~4000 rows. Meanwhile, Bottle is pretty self-sufficient - it supports:

  • wsgi-server
  • routing
  • authorization
  • plugins
  • own templates language
  • a lot of extensions (mostly one-paged too)
  • custom error pages
  • and much more!

I was excited trying to write my blog using Bottle. The first issue I faced - you can login, but you can't logout :D

Bottle supports basic auth mechanism, so you can do something like:

def auth_callback(user, password):
    return user == password  # or any check you want

@bottle.auth_basic(auth_callback)
def edit_post(db, post_id):
    ....
Enter fullscreen mode Exit fullscreen mode

But there is no way to logout. The only workaround I found is to return 401 status as a response. It allows to force logout the user. It's not quite correct, because user doesn't expect to get 401Error on logout, but this is why it's called workaround.

To make the solution to look more pretty I also customized 401 Error page, by adding an html-template with link to login.

def logout():
    return bottle.abort(401)

@app.error(401)
def error_401(error):
    return bottle.template("errors/401")

app.route("/logout/", ["GET"], logout)
Enter fullscreen mode Exit fullscreen mode

As alternative, there is an extension for bottle, called bottle-login, which has been archived few years ago.

GitHub logo klen / bottle-login

Implement users' sessions in Bottle framework

Bottle Login

Bottle Login -- Implement users' sessions in Bottle web framework.

Build Status Coverals http://img.shields.io/pypi/v/bottle-login.svg?style=flat-square http://img.shields.io/pypi/dm/bottle-login.svg?style=flat-square Donate

Requirements

  • python >= 2.6

Installation

Bottle Login should be installed using pip:

pip install bottle-login

Usage

from bottle import Bottle, request, redirect
from bottle_login import LoginPlugin

app = Bottle()
app.config['SECRET_KEY'] = 'secret'

login = app.install(LoginPlugin())

@login.load_user
def load_user_by_id(user_id):
    # Load user by id here


# Some application views

@app.route('/')
def index():
    current_user = login.get_user()
    return current_user.name

@app.route('/signout')
def signout():
    # Implement logout
    login.logout_user()
    return redirect('/')

@app.route('/signin')
def signin():
    # Implement login (you can check passwords here or etc)
    user_id = int(request.GET.get('user_id'))
    login.login_user(user_id)
    return redirect('/')

Bug tracker

If you have any suggestions, bug reports or annoyances please report them to the issue tracker at https://github.com/klen/bottle-login/issues

Contributing

Development of Bottle Login happens at: https://github.com/klen/bottle-login

Contributors

  • klen (Kirill Klenov)

License

Licensed under a BSD license.




Top comments (0)