0

Most of the tutorials only show how to deploy a simple Flask hello world app on Heroku. But I have a Flask app which contains URLs with both GET and POST requests and they use MySQLdb library for fetching data from database.

How to set up such apps on Heroku? Currently I have a MySQL database on my local machine which is used by the code to fetch data. The Flask code contains many functions which are invoked by API calls. For example:

@app.route('/display_table', methods=['POST'])
def display_webstats():
    db = MySQLdb.connect("localhost", "root", "root", "db_name")
    cursor = db.cursor()
    cursor.execute("select * from table_name")
    ws = cursor.fetchall()
    return jsonify(ws), 200

How to deploy such apps on Heroku?

0

1 Answer 1

1
  1. Make sure your dependencies are listed in your requirements.txt or Pipfile and Pipfile.lock.

  2. Select a MySQL addon and provision it, e.g.

    heroku addons:create cleardb:ignite
    
  3. Update your code to connect to the database provided by whatever environment variables the addon provides, e.g. CLEARDB_DATABASE_URL. You can use os.getenv() with a default argument to fall back in your development environment:

    import os
    
    database_url = os.getenv(
        'CLEARDB_DATABASE_URL',
        default='mysql://root:root@localhost/db_name',  # For local development
    )
    

    It's probably also a good idea to centralize your database connection logic so it's not done in every controller. Something like Flask-SQLAlchemy might be helpful to simplify connecting and querying your database. It also provides an ORM if you want one of those.

  4. Deploy.

  5. Assuming you have them, run your migrations on Heroku via heroku run. If you're not using a migrations library I urge you to start. Flask-Migrate might be a good fit.

    The alternative is manually creating and maintaining your schema across environments, and that's time-consuming, error prone, and frustrating.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.