LoginSignup
1
0

More than 3 years have passed since last update.

Flaskの個人用メモ その1

Last updated at Posted at 2020-03-04

Flaskを業務で初めて利用するため、メモ書きをする。

モジュールの利用

from flask import Flask,render_template,request

# from モジュール import クラス1, クラス2, クラス3...

GETリクエストの受け取り方

# requestクラスを使用
from flask import Flask, render_template, request

name = request.args.get("name")

POSTリクエストの受け取り方

# requestクラスを使用し、POSTで受け取った場合のメソッドを用意する
from flask import Flask, render_template, request

@app.route("/post", methods = ["post"])
def post():
    name = request.form["name"]
    # リストの場合はgetlistを利用する
    names = request.form.getlist("names")

変数のレンダリング

# コントローラ側
 render_template("index.html", name = name)

# テンプレート側
<div>{{name}}</div>

テンプレートでのif文利用

# テンプレート側
{% if name == "tokyo" %}
<div>首都{{name}}</div>
{% elif name %}
<div>{{name}}</div>
{% else %}
<div>無名</div>
{% endif %}

テンプレートでのfor文利用

# テンプレート側
{% for city in cities %}
<div>{{city}}</div>
{% endfor %}

ルーティング

# GET
@app.route("/get")
def get():

# POST
@app.route("/post", methods = ["post"])
def post():

モジュールをまとめてインストール

pip install -r requirements.txt

requirements.txtの中身はこんな感じ

Flask==1.1.1
SQLAlchemy==1.3.10
・
・
・
インストールしたいモジュールをどんどん追加していく

その2へ続く

1
0
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
1
0