Flask/project_name/ext/commands.py

44 lines
1.1 KiB
Python
Raw Normal View History

2024-11-10 07:27:36 -08:00
import click
from project_name.ext.auth import create_user
from project_name.ext.database import db
from project_name.models import Product
def create_db():
"""Creates database"""
db.create_all()
def drop_db():
"""Cleans database"""
db.drop_all()
def populate_db():
"""Populate db with sample data"""
data = [
Product(
id=1, name="Ciabatta", price="10", description="Italian Bread"
),
Product(id=2, name="Baguete", price="15", description="French Bread"),
Product(id=3, name="Pretzel", price="20", description="German Bread"),
]
db.session.bulk_save_objects(data)
db.session.commit()
return Product.query.all()
def init_app(app):
# add multiple commands in a bulk
for command in [create_db, drop_db, populate_db]:
app.cli.add_command(app.cli.command()(command))
# add a single command
@app.cli.command()
@click.option("--username", "-u")
@click.option("--password", "-p")
def add_user(username, password):
"""Adds a new user to the database"""
return create_user(username, password)