Last active
January 16, 2025 03:36
-
-
Save santiagosilas/a8dc760889e7fae7a716ceb1c18c8b5a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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!' |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)