flask で MariaDB を使う

  • 0
    いいね
  • 0
    コメント

    flask_jun12.png

    フォルダー構成

    mariadb.py
    template/hello.html
    template/template.html

    mariadb.py
    # --------------------------------------------------------------------
    #   mariadb.py
    #
    #                       Jun/12/2017
    #
    # --------------------------------------------------------------------
    from flask import Flask, render_template
    import sys
    import mysql.connector
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        name = "皆さんこんにちは"
        return name
    
    
    @app.route('/mariadb')
    def mariadb():
        host_aa='localhost'
        data_base = 'city'
        user_aa ='scott'
        password_aa = 'tiger123'
        conn = mysql.connector.connect(user=user_aa, password=password_aa, \
                                  host=host_aa,database=data_base)
    #
        cursor = conn.cursor (dictionary=True)
    #
        sql_str="select id, name, population, date_mod from cities order by id"
        cursor.execute (sql_str)
        rows = cursor.fetchall ()
    #
        cursor.close ()
        conn.close ()
    #
        return render_template('hello.html', title='MariaDB', cities=rows)
    
    ## おまじない
    if __name__ == "__main__":
        app.run(debug=True)
    
    hello.html
    {% extends "layout.html" %}
    {% block content %}
    <blockquote>
    <h3>都市一覧</h3>
    </blockquote>
    <table>
    <tr>
    <th>id</th>
    <th>name</th>
    <th>population</th>
    <th>date_mod</th>
    </tr>
    {% for city in cities %}
            <tr>
            <td>{{ city.id}}</td>
            <td>{{ city.name}}</td>
            <td>{{ city.population }}
            <td>{{ city.date_mod }}
            </tr>
    {% endfor %}
    </table>
    {% endblock %}
    
    layout.html
    <!doctype html>
    <html>
    <head>
    <title>{{ title }}</title>
    <body>
    {% block content %}
    <!-- ここにメインコンテンツを書く -->
    {% endblock %}
    </body>
    </head>
    

    サーバーの実行

    $ python mariadb.py 
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
     * Restarting with stat
     * Debugger is active!
     * Debugger PIN: 197-707-221
    

    クライアントは、
    http://localhost:5000/mariadb
    にアクセスする。

    データベース
    text
    MariaDB [city]> select * from cities;
    +-------+--------+------------+------------+
    | id | name | population | date_mod |
    +-------+--------+------------+------------+
    | t3321 | 岡山 | 645927 | 2017-05-30 |
    | t3322 | 倉敷 | 791835 | 2003-02-15 |
    | t3323 | 津山 | 163754 | 2003-08-18 |
    | t3324 | 玉野 | 369172 | 2003-01-09 |
    | t3325 | 笠岡 | 237451 | 2003-03-04 |
    | t3326 | 井原 | 518397 | 2003-05-21 |
    | t3328 | 高梁 | 478294 | 2003-10-26 |
    | t3329 | 新見 | 863751 | 2003-12-15 |
    +-------+--------+------------+------------+