I'm building a simple app using Flask and PyMySQL to be load-tested using JMeter for academic purposes. It already receives requests and sending out responses. But when I send multiple requests, it spews out the error below after a few requests (sometimes as few as one request).
Traceback (most recent call last):
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/username/BossFight/python/helloflask.py", line 82, in get_driver
if (authentication_success(token)):
File "/home/username/BossFight/python/helloflask.py", line 21, in authentication_success
cursor.execute("SELECT COUNT(*) AS matches FROM users WHERE id=%s", (id))
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/pymysql/connections.py", line 515, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/home/username/BossFight/python/venv/lib/python3.6/site-packages/pymysql/connections.py", line 745, in _execute_command
raise err.InterfaceError("(0, '')")
pymysql.err.InterfaceError: (0, '')
After that, it doesn't respond with anything but HTTP 500 anymore and has to be restarted.
Here's the relevant parts of the source:
from flask import Flask,jsonify,request
import pymysql.cursors
import bcrypt
import jwt
from pprint import pprint
app = Flask(__name__)
connection = pymysql.connect(
host='localhost',
db='omnibus',
user='starleaf1',
password='alleluia',
cursorclass=pymysql.cursors.DictCursor
)
secret = 'keyboard cat'
def authentication_success(token):
id=jwt.decode(token, secret, algorithms=['HS256'])["id"]
cursor=connection.cursor()
cursor.execute("SELECT COUNT(*) AS matches FROM users WHERE id=%s", (id))
return (cursor.fetchone()['matches'] == 1)
# Other routes goes here....
@app.route('/api/driver/<string:driver_id>', methods=['GET'])
def get_driver(driver_id):
cursor = connection.cursor()
token=request.headers['Authorization'][7:]
if (authentication_success(token)):
cursor.execute(query_get_driver_by_id, (driver_id))
driver=cursor.fetchone()
if (not(driver is None)):
return jsonify(message="ok",driver=driver)
else:
return jsonify(message="not found"),404
else:
return jsonify(message="authentication required"),401
Please keep in mind that I'm a beginner at Python. Any help would be appreciated.
The problem is likely that you have a global connection. In a web application, each request should have its own db connection. So your get_driver
function should create a connection and close that connection when it is finished (in a finally clause).
So something like:
def create_connection():
return pymysql.connect(
host='localhost',
db='omnibus',
user='starleaf1',
password='alleluia',
cursorclass=pymysql.cursors.DictCursor
)
@app.route('/api/driver/<string:driver_id>', methods=['GET'])
def get_driver(driver_id):
connection = create_connection()
try:
cursor = connection.cursor()
token=request.headers['Authorization'][7:]
if (authentication_success(token)):
cursor.execute("SELECT COUNT(*) AS matches FROM users WHERE id=%s", (driver_id))
driver=cursor.fetchone()
if (not(driver is None)):
return jsonify(message="ok",driver=driver)
else:
return jsonify(message="not found"),404
else:
return jsonify(message="authentication required"),401
finally:
connection.close()