LoginSignup
3
3

More than 3 years have passed since last update.

PythonのBottleを使ってログイン・ログアウトの処理を作ってみた。

Posted at

※本記事は個人用のメモです。

ちょっと作ってみたくなったので調べてみた。
参考にさせていただいたのは以下のページ

https://qiita.com/Gen6/items/c153d562e757d88aa5c1
https://stackoverflow.com/questions/35588873/how-to-logout-in-python-bottle
http://www.denzow.me/entry/2017/12/09/103828
https://qiita.com/yoskmr/items/8d35b6c7a15cfa275dfc

コード

こんな感じになった。ほとんど参考ページのスクリプトを流用させていただいた。感謝。

login.py
#!/user/bin/env python
# -*- coding: utf-8 -*-

from bottle import route, run, template, request, static_file, url, get, post, response, error
from bottle import redirect
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

SECRET_KEY = 'some-secret-key'
LIFE_TIME = 120

@route("/")
def html_index():
    user_id = request.get_cookie('account', secret=SECRET_KEY)
    if user_id is None:
        redirect('/login')
    else:
        return template('index',url=url)


@route("/static/<filepath:path>", name="static_file")
def static(filepath):   
    user_id = request.get_cookie('account', secret=SECRET_KEY)
    if user_id is None:
        redirect('/login')
    else:
        return static_file(filepath, root="./static")


@get("/login")
def login():
    return """
        <form action="/login" method="post">
            Username: <input name="username" type="text" />
            Password: <input name="password" type="password" />
            <input value="Login" type="submit" />
        </form>
    """

@route("/login", method="POST")
def do_login():
    username = request.forms.get("username")
    password = request.forms.get("password")
    if check_login(username, password):
        response.set_cookie("account", username, secret=SECRET_KEY, path='/', max_age=LIFE_TIME )
        redirect('/')
    else:
        redirect('/login')

def check_login(username, password):
  if username == "admin" and password=="password":
    return True
  else:
    return False


@route('/logout')
@route('/logout', method="POST")
def logout():
    response.delete_cookie('account')
    redirect('/login')

@error(404)
def error404(error):
    return template("404")

run(host="localhost", port=8080, debug=True, reloader=True)

これで、
・最初の状態はログイン画面に遷移する。
・ログインしたらcookieにユーザー情報を登録し、以後のアクセスはそちらを見て行う。
・/logoutにアクセスしたらcookieの情報を削除してログアウトした状態になる。
・指定時間たったらcookieが無効になる。
ってことができた。

ディレクトリ構造はこんな感じで。

├─static
│  ├─css
│  ├─img
│  └─js
└─views

viewsの下にtemplateで使うファイルを入れてあげればよいはず。
templateはこちらのページに詳しく解説されているので、ここを参照のこと。
http://www.denzow.me/entry/2018/03/03/220942

Templateの中でmicro Pythonも使えそうなのでとっても便利そう。

この方法で一般的なお作法にのっとっているかは???
いろいろ難しいなぁ。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3