Flask + Python 基礎
Flask 基礎を勉強中。
環境構築
OS:CentOS 5.4
Python-2.6.6 インストール。
$ pythonbrew install 2.6.6
$ pythonbrew switch 2.6.6
Flask インストール。
$ pip install Flask
Hello Flask
$ vi main.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello Flask.'
if __name__ == '__main__':
app.run()
$ python main.py
* Running on http://127.0.0.1:5000/
ルーティング&変数ルール
from flask import Flask
app = Flask(__name__)
@app.route('/user/')
def show_username(username):
return 'User. name:%s' % username
@app.route('/post/')
def show_post(post_id):
return 'Post. post_id:%s' % post_id
if __name__ == '__main__':
app.run()
リダイレクト
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello Flask.'
@app.route('/redirect')
def redirect_hello():
return redirect(url_for('hello'))
if __name__ == '__main__':
app.run()
リクエスト
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
return 'Get. name:%s' % request.values.get('name', '')
if __name__ == '__main__':
app.run()
スタティックファイル&テンプレート
ディレクトリ構成
/
main.py
|-- static
| |-- style.css
|-- templates
|-- index.html
main.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
@app.route('/')
def index(name=None):
return render_template('index.html', name=name)
if __name__ == '__main__':
app.run()
style.css
h1{
font-size: 12px;
font-weight: normal;
}
index.html
Hello from Flask
{% if name %}
Hello {{ name }}!
{% else %}
Hello World!
{% endif %}