How to insert data by default in Python-Flask avoiding duplication?

1

When you work with Flask in debug mode, Werzeug runs a child thread of your application which will receive the changes you make to the source code and update them live.

You can disable this option of the son thread but what you read is not recommended, even when you are out of debug mode.

Therefore it is necessary to verify the existence of the models loaded in Flask, to insert them or not.

Search the site in English and I found this function:

def get_or_create(session, model, **kwargs):
    '''
    Creates an object or returns the object if exists
    credit to Kevin @ StackOverflow
    from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
    '''
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        session.add(instance)
        session.commit()
        return instance

This function allows you to verify that the models have not been created before.

The problem:

I do not know in which part of the code to place the call to the function.

Try adding it directly to the models.py file

from app import db

def get_or_create(session, model, **kwargs):
    '''
    Creates an object or returns the object if exists
    credit to Kevin @ StackOverflow
    from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
    '''
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance
    else:
        instance = model(**kwargs)
        session.add(instance)
        session.commit()
        return instance

def fill_database():
    #: UserAccess
    administrador = get_or_create(session, UserAccess, description="Administrador")
    jefe_de_departamento = get_or_create(session, UserAccess, description="Jefe de Departamento")
    personal_de_departamento = get_or_create(session, UserAccess, description="Personal de Departamento")

class UserAccess(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(50), nullable=False)
    useraccess__user = db.relationship("User", backref="useraccess__user")

fill_database()

But I get the following error:

Working outside of request context

This is my app.py

# -*- coding = utf8 -*-
from flask import Flask
from flask import abort
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from flask_sqlalchemy import SQLAlchemy

from config import DevelopmentConfig

from functools import wraps

app = Flask(__name__)
app.config.from_object(DevelopmentConfig)

db = SQLAlchemy(app)

from models import *

if __name__ == "__main__":
    with app.app_context():
        db.init_app(app)
        db.create_all()
    app.run()

How can I use that function to fill my database?

    
asked by Victor Alvarado 15.04.2018 в 06:37
source

1 answer

0

The problem occurs when executing an application with the mode 'debug = True, this is because when executing with that parameter in True, Flask will use a second application which will receive the changes and then update the first one, therefore executing new the code of the insertion, so the most practical would be:

A - Run the function and then comment on it

B - Execute the function and leave the application in production mode, that is, DEBUG = False

    
answered by 09.11.2018 / 19:17
source