Skip to content

Commit

Permalink
Create visitors_app.py
Browse files Browse the repository at this point in the history
  • Loading branch information
erinecon authored Oct 30, 2024
1 parent dac9233 commit ecbbb94
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/tutorial/code/flask/visitors_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import datetime
import os

import flask
import psycopg2

app = flask.Flask(__name__)
app.config.from_prefixed_env()

DATABASE_URI = os.environ["POSTGRESQL_DB_CONNECT_STRING"]


@app.route("/")
def index():
with psycopg2.connect(DATABASE_URI) as conn, conn.cursor() as cur:
user_agent = flask.request.headers.get('User-Agent')
timestamp = datetime.datetime.now()

cur.execute(
"INSERT INTO visitors (timestamp, user_agent) VALUES (%s, %s)",
(timestamp, user_agent)
)
conn.commit()


greeting = app.config.get("GREETING", "Hello, world!")
return f"{greeting}\n"


@app.route("/visitors")
def visitors():
with psycopg2.connect(DATABASE_URI) as conn, conn.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM visitors")
total_visitors = cur.fetchone()[0]

return f"{total_visitors}\n"


if __name__ == "__main__":
app.run()

0 comments on commit ecbbb94

Please sign in to comment.