Connecting MySQL to Flask Web App

From TRCCompSci - AQA Computer Science
Revision as of 09:17, 29 April 2019 by Admin (talk | contribs)
Jump to: navigation, search

Flask can use sqlite for its database, this would be ideal for most situations. Sqlite is serverless and creates the database in a file contained within the project. This would work well if a single copy of the app exists and is accessed by everyone, and you want the app and data on the same server. SQL wise sqlite supports practically everything, but there are some things not supported (you are unlikely to encounter any of these). You could therefore install MySQL support instead.

Adding MySQL Support

Download the following zip file and extract it into your site-packages folder. If you are using your own machine installing flask-mysql an pymysql will do the same thing.

We need to run the USBWebserver, in College this must be on your compiled storage folder (download it HERE). When you run the executable you should get 2 firewall messages, click allow. If you get no firewall messages on the first run, then your system is preventing it from running:

Webserver.png

This shows USBWebserver running and fully active. Now click PHPmyAdmin button to open PHPmyAdmin:

Now click on database and enter a name to create a new database:

You should now be able to add the following code to import MySQL and connect to a database:

from flaskext.mysql import MySQL

mysql = MySQL()
 
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'usbw'
app.config['MYSQL_DATABASE_DB'] = 'Test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

conn = mysql.connect()