Skip to content

Instantly share code, notes, and snippets.

@mahya8585
Last active December 25, 2019 05:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahya8585/7a659e0a59dab0dda186015c059354e6 to your computer and use it in GitHub Desktop.
Save mahya8585/7a659e0a59dab0dda186015c059354e6 to your computer and use it in GitHub Desktop.
2019/12/21 PyLadies Caravan 北海道

Hello world

  • new project
  • pip install flask
  • create new file > application.py

Hello API

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
  • http://localhost:5000/

routing(動的パラメータ)

@app.route('/greeting/<string:user_name>')
def greeting_user(user_name):
    return '{uname}さん、こんばんは!'.format(uname=user_name)

routing(GETパラメータ)

@app.route('/greeting')
def greeting_name():
    user = flask.request.args.get('user')
    display = 'こんにちは! ' + user
    return flask.render_template_string(display)

Hello Jinja2

  • 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
    )

post form

  • 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
       )

Hello injection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment