Search code examples
pythonmysql-pythonbottle

Bottle and Mysql blocking request


I'm trying to figure out why my simple code have a blocking concurrent request:

# -*- coding: utf-8 -*-
import MySQLdb
from bottle import route, run
from gevent import monkey
monkey.patch_all()


cnx = MySQLdb.connect(host='127.0.0.1', port=3306, db='db', user='user', passwd='pass', use_unicode=True, charset="utf8mb4")
cursor = cnx.cursor()


@route('/testlong', method='GET')
def test_long():
    cursor.execute('SELECT SLEEP(5);')
    return 'finished'


@route('/testfast', method='GET')
def test_fast():
    return 'finished'


if __name__ == '__main__':
    run(host='127.0.0.1', port=46677, debug=True, server='gevent')

If I run http://localhost:46677/testlong and at the same moment http://localhost:46677/testfast on a different browser, my second request have to wait that the first is finished (so 5 seconds).

What I'm doing wrong please ? Thank you for your help.


Solution

  • The MySQLdb package is just a thin Python wrapper on top of a C extension, which means that gevent can't monkey patch it.

    You should either use a pure Python MySQL client (like PyMySQL) or use a different framework that supports threading (like FastAPI/Starlette).