You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# web_app/models.pyfromflask_sqlalchemyimportSQLAlchemyfromflask_migrateimportMigratedb=SQLAlchemy()
migrate=Migrate()
classBook(db.Model):
id=db.Column(db.Integer, primary_key=True)
title=db.Column(db.String(128))
author_id=db.Column(db.String(128))
def__repr__(self):
returnf"<Book {self.id}{self.title}>"defparse_records(database_records):
""" A helper method for converting a list of database record objects into a list of dictionaries, so they can be returned as JSON Param: database_records (a list of db.Model instances) Example: parse_records(User.query.all()) Returns: a list of dictionaries, each corresponding to a record, like... [ {"id": 1, "title": "Book 1"}, {"id": 2, "title": "Book 2"}, {"id": 3, "title": "Book 3"}, ] """parsed_records= []
forrecordindatabase_records:
print(record)
parsed_record=record.__dict__delparsed_record["_sa_instance_state"]
parsed_records.append(parsed_record)
returnparsed_records
Some example usage of the models (for example in a route):
# SELECT * FROM booksbook_records=Book.query.all()
print(book_records)
# INSERT INTO books ...new_book=Book(title=request.form["title"], author_id=request.form["author_name"])
db.session.add(new_book)
db.session.commit()
Web app init config:
# web_app/__init__.pyfromflaskimportFlaskfromweb_app.modelsimportdb, migratefromweb_app.routes.home_routesimporthome_routesfromweb_app.routes.book_routesimportbook_routesDATABASE_URI="sqlite:///web_app_99.db"# using relative filepath#DATABASE_URI = "sqlite:////Users/Username/Desktop/your-repo-name/web_app_99.db" # using absolute filepath on Mac (recommended)#DATABASE_URI = "sqlite:///C:\\Users\\Username\\Desktop\\your-repo-name\\web_app_99.db" # using absolute filepath on Windows (recommended) h/t: https://stackoverflow.com/a/19262231/670433defcreate_app():
app=Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] =DATABASE_URIdb.init_app(app)
migrate.init_app(app, db)
app.register_blueprint(home_routes)
app.register_blueprint(book_routes)
returnappif__name__=="__main__":
my_app=create_app()
my_app.run(debug=True)
Creating and Migrating the database:
FLASK_APP=web_app flask db init #> generates app/migrations dir# FLASK_APP=web_app flask db stamp head # if there is an issue# run both when changing the schema:
FLASK_APP=web_app flask db migrate #> creates the db (with "alembic_version" table)
FLASK_APP=web_app flask db upgrade #> creates the specified tables
The text was updated successfully, but these errors were encountered:
Notes for using
Flask-SQLAlchemy
package for database withFlask-Migrate
package for migrations.Flask-SQLAlchemy:
Flask-Migrate:
Model class(es):
Some example usage of the models (for example in a route):
Web app init config:
Creating and Migrating the database:
The text was updated successfully, but these errors were encountered: