背景
-
Web 系の実装を少しくらいは自分でできるように、
前回は SQLite3 の使い方を勉強した。 -
今回は、UI 部分を Flask を使って実装します。
構成
- トップページ (index)
- 情報閲覧ページ (view DB)
Flask service の起動 + index の定義
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import os
import sqlite3
from flask import Flask, render_template, request
app = Flask( __name__)
@app.route( '/')
def index() :
return "{}".format( sqlite3.__path__)
def main( argv) :
host_ip = argv[1]
host_port = int( argv[2])
app.run( host = host_ip,
port = host_port )
if __name__ == "__main__" :
if len( sys.argv) < 3 :
print( "USAGE: {:s} [ip] [port]".format( sys.argv[0]))
sys.exit( 1)
main( sys.argv)
view DB
- 前回作った example.sqlite3 を使います。
@app.route( '/view')
def view() :
''' SQLite3 '''
s3f = 'example.sqlite3'
if not os.path.exists( s3f) :
print( "SQL file not found.")
con = sqlite3.connect( s3f)
c = con.cursor()
c.execute( "select * from logs")
data = c.fetchall()
con.close()
return render_template( "view.html", result = data)
templates/view.html
<html>
<body>
<table border="1" cellspacing="0" cellpadding="4">
{% for line in result %}
<tr>
{% for item in line %}
<td align="right"> {{ item }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
<br/>
<a href="/">Go TOP</a>
</body>
</html>