I wanted to make it a little, so I looked it up. The following page was used as a reference
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
It looks like this. Most of the scripts on the reference page were diverted. Thanks.
!/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)
with this, -The initial state transitions to the login screen. ・ After logging in, register user information in a cookie, and then access it afterwards. -When you access / logout, the cookie information is deleted and you are logged out. ・ The cookie becomes invalid after the specified time. I was able to do it.
The directory structure looks like this.
├─static
│ ├─css
│ ├─img
│ └─js
└─views
You should put the file used in template under views. The template is explained in detail on this page, so please refer to it here. http://www.denzow.me/entry/2018/03/03/220942
It seems to be very convenient because micro Python can be used in Template.
Does this method follow the general practice? ?? ?? It's a lot difficult.
Recommended Posts