Estoy usando matraz, sqlalchemy, sqlite y python para mi aplicación. Cuando ejecuto db init para crear la base de datos, quiero que se agregue un conjunto predeterminado de valores a la base de datos. He intentado estas dos cosas para agregar los registros a la tabla. Un método es usar 'evento'.
from sqlalchemy.event import listen from sqlalchemy import event, DDL @event.listens_for(studentStatus.__table__, 'after_create') def insert_initial_values(*args, **kwargs): db.session.add(studentStatus(status_name='Waiting on admission')) db.session.add(studentStatus(status_name='Waiting on student')) db.session.add(studentStatus(status_name='Interaction Initiated')) db.session.commit()cuando corro
python manage_db.py db init, python manage_db.py db migrate, python manage_db.py db upgradeNo tuve ningún problema, pero los registros no se crean.
El otro método que probé es, en models.py que he incluido
record_for_student_status = studentStatus(status_name="Waiting on student") db.session.add(record_for_student_status) db.session.commit() print(record_for_student_status)El código del modelo de clase:
class StudentStatus(db.Model): status_id = db.Column(db.Integer,primary_key=True) status_name = db.Column(db.String) def __repr__(self): return f"studentStatus('{self.status_id}','{self.status_name}')"Cuando ejecuto python manage_db.py db init, recibo un error Student_status, no existe tal tabla.
¿Puede alguien ayudarme a agregar los valores predeterminados a la tabla student_status cuando ejecuto db init?
También he probado con sembradora de matraces. Instalé la sembradora de matraces y agregué un nuevo archivo llamado seed.py y ejecuté la ejecución de la semilla del matraz
Mi seed.py se ve así
class studentStatus(db.Model): def __init__(self, status_id=None, status_name=None): self.status_id = db.Column(db.Integer,primary_key=True) self.status_name = db.Column(db.String,status_name) def __str__(self): return "ID=%d, Name=%s" % (self.status_id, self.status_name) class DemoSeeder(Seeder): # run() will be called by Flask-Seeder def run(self): # Create a new Faker and tell it how to create User objects faker = Faker( cls=studentStatus, init={ "status_id": 1, "name": "Waiting on Admission" } ) # Create 5 users for user in faker.create(5): print("Adding user: %s" % user) self.db.session.add(user)Ejecuté db init, db migrate y db upgrade. No tuve ningún problema. Cuando ejecuté la ejecución de la semilla del matraz, aparece este error
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directoryLo busqué en Google e intenté exportar FLASK_APP=seeds.py
Then I ran the flask seed run ,I am getting an error ``` error could not import seeds.py``` Please help me in this. What I need finally is when I do db initialization for the first time some default value have to be added to the database.humm, parece que pusiste un guión bajo en Student_status , intenta eliminarlo. Y otra cosa, intente escribir su clase en CamelCase, es una forma más "Pythonic" de escribir un código, cuando lo ejecute, SQLalchemy transformará este nombre de clase en la tabla student_status automáticamente
Antes de ejecutar la aplicación del matraz, debe crear una instancia de FLASK_APP y FLASK_ENV.
Primero Cree una función para agregar datos. suponga que el nombre de la función se ejecuta como el suyo,
def run(self): # Create a new Faker and tell it how to create User objects faker = Faker( cls=studentStatus, init={ "status_id": 1, "name": "Waiting on Admission" } ) # Create 5 users for user in faker.create(5): print("Adding user: %s" % user) self.db.session.add(user)Ahora puede llamar a esta función en el archivo de ejecución de la aplicación. Supongamos que mi archivo tiene el nombre app.py.
from application import app if __name__ == '__main__': run() app.run(debug=True)Ahora configure FLASK_APP y FLASK_ENV como se muestra a continuación.
export FLASK_APP=app.py export FLASK_ENV=developmentDespués de eso, puede ejecutar los siguientes comandos.
flask db init flask db migrate flask db upgradeesto creará todas las tablas y los datos que desee.
Para obtener más detalles, puede obtenerlos desde el siguiente enlace. Este enlace es para un repositorio de Github. Allí he agregado algunos datos al iniciar la aplicación. Simplemente lea el archivo Léame.MD y podrá obtener más información sobre cómo configurar FLASK_APP.
Adición de datos de matraz cuando se crea una instancia de base de datos