Working with Python-Flask-MySQL
If you want to develop a webservice using python, flask and MySQL, here are some setup instructions and pre-requisites which are required, for both platforms — Windows and Linux.
(Also, I have added some tips and tricks for some of the issues I had faced)
Step -1
Check the Python version using,
$ python -V
Download the latest python version 3.X
$ sudo apt-get install python3-pi
Step-2
You need to install the below dependencies using,
$ pip install -r pymysql$ pip install -r Flask$ pip install -r Flask-cors$ pip install -r simpleJson
(Also, you need to install some extra dependencies you are using)
Step-3
Create a config file, config.py and add your connection details
DB_CONF = {'host':'<YOUR-MYSQL-HOST>','port':3306,'user':'<YOUR-MYSQL-USERNAME>','passwd':'<YOUR-MYSQL-PASSWORD>','db':'<YOUR-MYSQL-DATABASE>'}In main.py, put your real query like this,sql="<PUT YOUR MySQL QUERY HERE>"eg.
@app.route(‘/testWebService’)
def test_get():
# create mysql connection
Conn = pymysql.connect(host=config.DB_CONF[‘host’],
port=config.DB_CONF[‘port’],
user=config.DB_CONF[‘user’],
passwd=config.DB_CONF[‘passwd’],
db=config.DB_CONF[‘db’])cur = conn.cursor()
sql="<PUT YOUR MySQL QUERY HERE>"
cur.execute(sql)
Step-4
Start a web service,
On Windows, you can start the web service using,
>waitress-serve — listen=*:8080 main:app
On Ubuntu, you can use,
$ gunicorn — log-level debug — bind 0.0.0.0:30443 server:app
For Python3,$ gunicorn3 --log-level debug --bind 0.0.0.0:30443 server:app
In Ubuntu, you may face timeout issue. In that case, you can execute the command,
$ gunicorn3 --workers=3 --bind 0.0.0.0:3000 main:app
If the command fails, saying there are already some instance running (zombie processes) and you want to restart the service, you can execute this command before above command,
$ sudo fuser -k 3000/tcp
(You may want to add all these commands, and get the logs in shell file, execute below command)
$ ./sampleWebService.sh
Thank You!