Apologies I'm fairly new to python and have been given a task to complete for a course but I'm a bit stuck and I'm not getting a lot of tutor feedback.
My question is how do I format this response in order to get back the values from the sqlite queries without causing a 500 internal server error?
# Function to get a database connection.
# This function connects to database with the name `database.db`
def get_db_connection():
connection = sqlite3.connect('database.db')
connection.row_factory = sqlite3.Row
return connection
#Define the metrics endpoint of the web application
@app.route('/metrics')
def metrics():
connection = get_db_connection()
posts = connection.execute('SELECT COUNT(*) FROM posts')
changes = connection.total_changes
connection.close()
response = app.response_class(
response=json.dumps({"db_connection_count": changes}, {"post_count": posts}, default=default_json),
status=200,
mimetype='application/json'
)
app.logger.info('Metrics request successfull.')
return response
I know the response=json.dumps section is wrong. I've tried several options but I keep getting the same error. The previous error was a cursor error and now it doesn't like the default_json option.
12/08/2022 07:21:00 AM Exception on /metrics [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "app.py", line 53, in metrics
response=json.dumps({"db_connection_count": changes}, {"post_count": posts}, default=default_json),
NameError: name 'default_json' is not defined
12/08/2022 07:21:00 AM 172.17.0.1 - - [12/Aug/2022 07:21:00] "GET /metrics HTTP/1.1" 500 -
Is anyone able to advise of point me in the right direction? Thanks
CodePudding user response:
Part of the problem is that you get a cursor (posts) which you then pass to app.response_class after you've closed the database connection.
That renders the cursor unusable.
Consider using a context manager for opening and closing the database connection.
Something like this might show an improvement:
@app.route('/metrics')
def metrics():
with sqlite3.connect('database.db') as conn:
cursor = None
try:
cursor = conn.execute('SELECT COUNT(*) FROM posts')
posts = cursor.fetchone()[0]
jdata = {'db_connection_count': conn.total_changes, 'post_count': posts}
response = app.response_class(
response=json.dumps(jdata), status=200, mimetype='application/json')
app.logger.info('Metrics request successfull.')
return response
finally:
if cursor:
cursor.close()
CodePudding user response:
If you are trying to collect the response then you may try the following:
json_object = json.loads(response.text)