22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでbottleを使うときに流用できるスクリプト

Last updated at Posted at 2015-06-03

Pythonでbottleを使うときやはり色々最初から書くのは面倒臭い。
ということですぐに使えるように必要最低限中身を書いてそこから書くことにしている。

main_app.py

#!/user/bin/env python
# -*- coding: utf-8 -*-
from bottle import route, run, template, request, static_file, url, get, post, response, error
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

@route("/")
def html_index():
	return template("index")

@route("/static/<filepath:path>", name="static_file")
def static(filepath):	
	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="some-secret-key")
        return template("index", name=username)
    else:
        return "<p>Failed !</p>"
def check_login(username, password):
  if username == "admin" and password=="password":
    return True
  else:
    return False


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

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

こんな感じでログイン機能自体も最初から書いておく。
エラーでの404だけは最初から書いて、500エラーとかは使うときに応じて追記。

myapp - bottle.py
		main_app.py
		
		/static
			- /css
			- /img
			- /js
		
		/views 
			- index.html
			- 404.html

こういう感じでディレクトリ作ればいいと思う。
ちなみにviewsのテンプレートファイルは拡張子が.tplである必要はない。

22
27
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
22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?