Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save santiagosilas/a8dc760889e7fae7a716ceb1c18c8b5a to your computer and use it in GitHub Desktop.

Select an option

Save santiagosilas/a8dc760889e7fae7a716ceb1c18c8b5a to your computer and use it in GitHub Desktop.
# MySQL in PythonAnywhere with Flask -SQLAlchemy.py
# A very simple Flask Hello World app for you to get started with...
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# import MySQLdb
app = Flask(__name__)
app.config["DEBUG"] = True
user, password = '********', '********'
host = '********.mysql.pythonanywhere-services.com'
db = '********$dbFlask' # dbFlask was created as a PythonAnywhere MySQL database
# connection string: mysql://user:pword@host/db
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{0}:{1}@{2}/{3}'.format(user, password, host, db)
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20))
email = db.Column(db.String(50))
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User name:%r>' % self.username
@app.route('/')
def hello_world():
u = User('Fulano', '[email protected]')
db.session.add(u)
db.session.commit()
u = User.query.first()
return u.username
@app.route('/reload')
def reload():
db.drop_all()
db.create_all()
return 'database (re)created!'
@santiagosilas
Copy link
Author

MySQL in PythonAnywhere with Flask-SQLAlchemy extension - A Simple Example

Connection String Format: mysql://user:pword@host/db

SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{0}:{1}@{2}/{3}'.format(user, password, host, db)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment