-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
149 lines (117 loc) · 4.04 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import sys
import sqlite3
import logging
from flask import Flask, render_template, request, url_for, redirect, flash, json
# This variable stores the number of connections made to the database
# and will be viewed by at the /metrics endpoint
connection_count = 0
# Function to get a database connection.
# This function connects to database with the name `database.db`
DATABASE_FILE = './database.db'
def get_db_connection():
global connection_count
app.logger.debug(f'Connecting to database file {DATABASE_FILE}')
try:
connection = sqlite3.connect(DATABASE_FILE)
connection_count += 1
result = connection.execute("SELECT COUNT(name) FROM sqlite_master WHERE name='posts'").fetchone()
if result[0] != 1:
message = "The required database table 'posts' is missing"
app.logger.debug(message)
raise Exception(message)
except Exception as e:
raise e
else:
connection.row_factory = sqlite3.Row
return connection
# Function to get a post using its ID
def get_post(post_id):
connection = get_db_connection()
post = connection.execute('SELECT * FROM posts WHERE id = ?',
(post_id,)).fetchone()
connection.close()
return post
# Define the Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your secret key'
# Define the main route of the web application
@app.route('/')
def index():
connection = get_db_connection()
posts = connection.execute('SELECT * FROM posts').fetchall()
connection.close()
return render_template('index.html', posts=posts)
# Define how each individual article is rendered
# If the post ID is not found a 404 page is shown
@app.route('/<int:post_id>')
def post(post_id):
post = get_post(post_id)
if post is None:
app.logger.debug(f'article with post ID {post_id} does not exist.')
return render_template('404.html'), 404
else:
app.logger.debug(
f'Article "{post["title"]}" page retrieved.')
return render_template('post.html', post=post)
# Define the About Us page
@app.route('/about')
def about():
app.logger.debug(
f'The "About Us" page retrieved.')
return render_template('about.html')
# Define the Health endpoint
@app.route('/healthz')
def status():
try:
get_db_connection()
except Exception as e:
return app.response_class(
response=json.dumps({'result':f'Error - {e.args[0]}'}),
status=500,
mimetype='application/json'
)
else:
return {
"result": "OK - healthy"
}
# Define the metrics endpoint
@app.route('/metrics')
def metrics():
connection = get_db_connection()
post_count = 0
with connection:
posts = connection.execute('SELECT COUNT(*) FROM posts').fetchone()
post_count = posts[0]
return {
'db_connection_count': connection_count,
'post_count': post_count
}
# Define the post creation functionality
@app.route('/create', methods=('GET', 'POST'))
def create():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if not title:
flash('Title is required!')
else:
connection = get_db_connection()
connection.execute('INSERT INTO posts (title, content) VALUES (?, ?)',
(title, content))
connection.commit()
connection.close()
app.logger.debug(f'New page created, with Title "{title}"')
return redirect(url_for('index'))
return render_template('create.html')
# start the application on port 3111
if __name__ == "__main__":
FORMAT = '%(asctime)-15s -- %(funcName)s -- %(message)s'
logging.basicConfig(
level=logging.DEBUG,
format=FORMAT,
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler(),
logging.StreamHandler(stream=sys.stdout)
])
app.run(host='0.0.0.0', port='3111')