- new project
- pip install flask
- create new file > application.py
import flask
app = flask.Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '_main__':
app.run()
-
intelliJ run
-
windows
- set FLASK_APP=application.py
- flask run
-
mac
- export FLASK_APP=application.py
- flask run
@app.route('/greeting/<string:user_name>')
def greeting_user(user_name):
return '{uname}さん、こんばんは!'.format(uname=user_name)
@app.route('/greeting')
def greeting_name():
user = flask.request.args.get('user')
display = 'こんにちは! ' + user
return flask.render_template_string(display)
- templatesディレクトリの作成
- index.htmlの作成
<title>welcome!</title>
<h1>Welcome! {{name}}さん!</h1>
- ルーティング
@app.route('/welcome/<string:user_name>')
def welcome_index(user_name):
return flask.render_template(
'index.html',
name=user_name
)
- echo.htmlの作成
<p>あなたの打った文字はこちら</p>
<h1>{{echo}}</h1>
- index.htmlに追加
<form action="/echo" method="POST">
<input type="text" name="input_word" />
<button type="submit">GO!</button>
</form>
- ルーティング
@app.route('/echo', methods=['POST'])
def echo():
echo_word = flask.request.form['input_word']
return flask.render_template(
'echo.html',
echo=echo_word
)
-
run
- http://localhost:5000/greeting?user=まーや
- http://localhost:5000/greeting?user=<script>alert("hack")</script>
-
コード変更
- display = 'こんにちは! ' + flask.escape(user)
-
run
- http://localhost:5000/greeting?user=<script>alert("hack")</script>