python

python flask mysql で訪問者の履歴照会

環 境

ubuntsu20.04

apache2

python3.8.10

flask2.2.2

インストール

$ sudo apt install python3-pip libapache2-mod-wsgi-py3
$ sudo pip3 install flask

プロジェクト作成

$ mkdir app
appディレクトリ内に作成
app.py 作成
wsgi.py 作成
templatesディレクトリ 

app.py

rom flask import Flask,render_template
from flask_mysqldb import MySQL

app = Flask(__name__)
# Required
app.config['MYSQL_DATABASE_Host'] = '192.168.10.71'
app.config["MYSQL_USER"] = "ssk2"
app.config["MYSQL_PASSWORD"] = "Ssk1009@"
app.config["MYSQL_DB"] = "wordpress_db"
# Extra configs, optional:
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
app.config["MYSQL_CUSTOM_OPTIONS"] = {"ssl": {"ca": "/path/to/ca-file"}}  # https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes

mysql = MySQL(app)

@app.route('/') 

def users():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * from wp_homonsha")
    results = cur.fetchall()
    #return str(results)
    return render_template('index.html', results=results)
    
if __name__ == '__main__':
    app.run()

wsgl.py

import sys 
sys.path.insert(0, '/var/www/html/app')
from app import app as application

templatesフォルダ index.html

<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<title>訪問者の履歴</title>
</head>
<body bgcolor="#daefef">
<h1>  訪問者の履歴 </h1>
<table class="table table-bordered" border='1' id="dataTable" width="350" cellspacing="0">
<tbody>
<tr>
<td align="center" bgcolor="pink">訪 問 者</td>
<td align="center" bgcolor="pink">訪 問 日</td>
</tr>
{% for row in results %}
<tr>
<td align="center" bgcolor="white">{{ row["ip"] }}</td>
<td align="center" bgcolor="white">{{ row["dt"] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

apache2の設定

$ sudo ln -sT ~/app /var/www/html/app
/etc/apache2/sites-enabled/000-default.conf の設定
DocumentRoot /var/www/html の下に次の設定を追記します。
        WSGIDaemonProcess app threads=5
        WSGIScriptAlias / /var/www/html/app/wsgi.py
        WSGIApplicationGroup %{GLOBAL}
        <Directory app>
             WSGIProcessGroup app
             WSGIApplicationGroup %{GLOBAL}
             Order deny,allow
             Allow from all 
        </Directory>

$ sudo service apache2 restart

-python

PAGE TOP