from flask import Flask, render_template_string, jsonify
import sqlite3
app = Flask(__name__)
DB_FILE = '/db/counter.db'
def init_db():
"""Initialize the database and set the starting number to 0 if it doesn't exist."""
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# 1. Setup Button Counter Table
c.execute('CREATE TABLE IF NOT EXISTS counter (id INTEGER PRIMARY KEY, value INTEGER)')
c.execute('SELECT value FROM counter WHERE id = 1')
if c.fetchone() is None:
c.execute('INSERT INTO counter (id, value) VALUES (1, 0)')
# 2. Setup Visit Counter Table
c.execute('CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, count INTEGER)')
c.execute('SELECT count FROM visits WHERE id = 1')
if c.fetchone() is None:
c.execute('INSERT INTO visits (id, count) VALUES (1, 0)')
conn.commit()
# We added an ID to the counter div and a JavaScript block at the bottom
HTML_TEMPLATE = '''
Counter
'''
@app.route('/')
def index():
"""Update visit count, fetch both counts, and load the page."""
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# Increment the visit counter every time this route is hit
c.execute('UPDATE visits SET count = count + 1 WHERE id = 1')
conn.commit()
# Fetch the newly updated visit count
c.execute('SELECT count FROM visits WHERE id = 1')
visit_count = c.fetchone()[0]
# Fetch the current button count
c.execute('SELECT value FROM counter WHERE id = 1')
button_count = c.fetchone()[0]
# Pass both variables into the HTML template
return render_template_string(HTML_TEMPLATE, count=button_count, visits=visit_count)
@app.route('/increment', methods=['POST'])
def increment():
"""Add 1 to the database value and return the new number as JSON."""
with sqlite3.connect(DB_FILE) as conn:
c = conn.cursor()
# Update the database
c.execute('UPDATE counter SET value = value + 1 WHERE id = 1')
# Grab the new value so we can send it back to the frontend
c.execute('SELECT value FROM counter WHERE id = 1')
new_count = c.fetchone()[0]
conn.commit()
# Return JSON instead of redirecting the whole page
return jsonify({'new_count': new_count})
if __name__ == '__main__':
init_db()
# Keeping the host='0.0.0.0' so your outside connections still work!
app.run(host='0.0.0.0', port=5000, debug=True)