🐙

flaskでwebアプリを作成

2022/02/13に公開
  1. 階層
    /var/www/python 
    ├─ app.py
    ├─ condb.py 
    ├─ app.wsgi 
    ├─ templates
    │   ├─ index.html
    │   └─ ver.html
    └─ static
        ├─ css
        └─ js
  1. pythonのバージョン確認
app.py
from flask import Flask,render_template, request, redirect
import sys 

app = Flask(__name__)

ver = sys.version

@app.route('/')
def adr():
  return render_template('ver.html',ver = ver)
if __name__ == '__main__':
  app.run()
ver.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>pythonのバージョン確認</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>pythonのバージョン</h1>
    {{ ver }} 
  </body>
</html>
  1. データベースから値を取得
app.py
from flask import Flask,render_template, request, redirect
from condb import conn

app = Flask(__name__)

# カーソル作成
cur = conn.cursor()
# 取得(zipコードで取得)
cur.execute("select * from ad_address where zip like '001-%'")
adrrs = cur.fetchall()

# DB操作終了
cur.close()

@app.route('/')
def adr():
  return render_template('index.html',adrrs = adrrs)
  
if __name__ == '__main__':
  app.run()
condb.py
import mysql.connector as connector
conn = connector.connect(
    host='localhost',
    port='3306',
    user='root',
    password='password',
    database='zenkoku'
)
index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>住所</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>住所</h1>
    <tbody>
      {% for addr in adrrs %}
       <table border="1">
          <tr>
            {{ addr[0] }}
            {{ addr[1] }}
            {{ addr[2] }}
            {{ addr[3] }}
            {{ addr[4] }}
            {{ addr[5] }}
            {{ addr[6] }}
            {{ addr[7] }}
            {{ addr[8] }}
            {{ addr[9] }}
            {{ addr[10] }}
            {{ addr[11] }}
          </tr>
       </table>
      {% endfor %}
    </tbody>  
  </body>
</html>

Discussion