Skip to content

Instantly share code, notes, and snippets.

@timmyomahony
Last active December 5, 2017 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timmyomahony/c176426e0dfa2cf4bb82989f9376f72b to your computer and use it in GitHub Desktop.
Save timmyomahony/c176426e0dfa2cf4bb82989f9376f72b to your computer and use it in GitHub Desktop.
Getting Flask and MySQL set up

OSX

Need install MySQL here:

https://dev.mysql.com/downloads/mysql/

and the workbench here:

https://dev.mysql.com/downloads/workbench/

Reset root password

https://stackoverflow.com/questions/6474775/setting-the-mysql-root-user-password-on-os-x

You only get one opportunity to see the default root password. If you miss that, you have to reset the password manually.

  1. Stop the MySQL server from running by going to "System Preference" then "MySQL" and hitting "Stop MySQL Server"
  2. Open a new console terminal and run sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables. This will start the MySQL database server running again in safe mode.
  3. Open a second console and connect to the database with sudo /usr/local/mysql/bin/mysql -u root. This will ask you for a password which is the adminstrator password for your machine
  4. In the database prompt enter USE mysql; then UPDATE mysql.user SET authentication_string=PASSWORD("YOUR PASSWORD") WHERE User='root'; being careful to replace your own new password

Use the workbench to create a test database

https://stackoverflow.com/questions/5515745/create-a-new-database-with-mysql-workbench

Create a basic server

Use the Flask app above to connect to the test database you created and pull out data. Bear in mind that in my test database I only has one "name" column in the database. Your script will be different depending on how you set up your database.

from flask import Flask, jsonify
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'testtest1234'
app.config['MYSQL_DB'] = 'test_db'
mysql = MySQL(app)
@app.route('/')
def hello_world():
cursor = mysql.connection.cursor()
cursor.execute('select name from test_table')
items = cursor.fetchall()
return jsonify([{'name': name} for name, in items])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment