0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

getting started: Python で Web UI (with Flask)

Last updated at Posted at 2019-05-07

背景

  • Web 系の実装を少しくらいは自分でできるように、
    前回は SQLite3 の使い方を勉強した。

  • 今回は、UI 部分を Flask を使って実装します。


構成

  1. トップページ (index)
  2. 情報閲覧ページ (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>

おわり

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?