samedi 25 juin 2016

Python, Flask -- count page visit and write in database

There is a small hello world Flask with visit statistics. I managed to count visits with redis, but I also have to add support storing date and number of visits in MySQL database. The current code is: I was trying to access previously created database. Currently I have no idea how to store such info in MySQL.

I was trying to access previously created database. Currently I have no idea how to store such info in MySQL.

from flask import Flask
from redis import Redis

app = Flask(__name__)
redis = Redis(host="redis")
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'passwd'
app.config['MYSQL_DATABASE_DB'] = 'hello'
app.config['MYSQL_DATABASE_HOST'] = 'mysql'
mysql.init_app(app)

@app.route("/")
def hello():
    visits = redis.incr('counter')
    html = "<h3>Hello, world!</h3>" 
           "<b>Visits:</b> {visits}" 
           "<br/>"
    return html.format(visits=visits)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80)

How this can be solved? I will be grateful for any suggestions.

Aucun commentaire:

Enregistrer un commentaire