def init(): import application.data as data from application import db from application.persistence import user_persistence, category_persistence, report_persistence db.drop_all() db.create_all() for user_data in data.users: user = User(email=user_data['email'], password=user_data['password'], user_id=user_data['id']) user_persistence.save(user) for category_data in data.categories: category = Category(name=category_data['name'], category_id=category_data['id']) category_persistence.save(category) for report_data in data.reports: user_id = report_data['user_id'] category_id = report_data['category_id'] report = Report(lat=report_data['lat'], lng=report_data['lng'], description=report_data['description'], time=report_data['time'], user=user_persistence.get(user_id), category=category_persistence.get(category_id), report_id=report_data['id']) report_persistence.save(report) return redirect(url_for('index'))
def init_db(): try: # if app.debug: # 但开发告一段落时将这里改成 if app.debug: db.drop_all()以使只在开发模式下清空表, db.drop_all() # 但之前这样做以使得无论本地开发还是部署到appfog等云上都可以正常运行(开发时) db.create_all() except: pass
def setUp(self): # for now lets assert we never run test suite in production environment = os.environ.get('APPLICATION_ENV', 'testing') self.assertEqual(environment, 'testing') db.create_all() self.insert_dummy_data()
def setup_databases(app=createApp()): with app.app_context(): db.drop_all() db.create_all() setup_users() setup_timeslots()
def setUp(self): create_db_dir = _basedir + "/db" if not os.path.exists(create_db_dir): os.mkdir(create_db_dir, 0755) app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(_basedir, "db/tests.db") self.app = app.test_client() db.create_all()
def setUp(self): app.config['LOGIN_DISABLED'] = True app.config['VIEW_COUNT_ENABLED'] = False db.drop_all() db.create_all() self.search_api = app.config['AUTHENTICATED_SEARCH_API'] self.client = app.test_client()
def setUp(self): app.config["TESTING"] = True, app.config['WTF_CSRF_ENABLED'] = False app.config['CSRF_ENABLED'] = False app.config['SECRET_KEY'] = 'testing-not-a-secret' db.create_all() self.app = app self.client = app.test_client()
def setUp(self): create_db_dir = _basedir + '/db' if not os.path.exists(create_db_dir): os.mkdir(create_db_dir, 0755) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = ('sqlite:///' + os.path.join(_basedir, 'db/tests.db')) self.app = app.test_client() db.create_all()
def setUp(self): create_app("test") from application import app, db self.app = app with app.test_request_context(): db.create_all() # Initialize database, if needed self.db_session = db.create_scoped_session()
def setupdb(): """ Create all database tables """ db.drop_all() db.create_all() # scaffold some basic data db.session.add(Location(name="Uber", address="800 Market St., San Francisco, CA")) db.session.add(Location(name="Home", address="Sacramento St., San Francisco, CA")) db.session.commit()
def install_db_create_all(): """Create the DB schema for all models""" from application import db from models.feedback import Feedback from models.translation import Translation from models.variable import Variable from models.account import Account, Preference, Group from models.project import Project, Component, Label, Role, Membership from models.report import Report db.create_all()
def setUp(self): app.config["TESTING"] = True, db.drop_all() db.create_all() self.app = app self.client = app.test_client() with app.test_request_context(): user_datastore.create_user(email='*****@*****.**', password=encrypt_password('password')) db.session.commit()
def setUp(self): # self.db_fd, app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/server_test.sqlite" app.config["TESTING"] = True self.app = app.test_client() db.create_all() # add fake worker worker = Worker( hostname="debian", status="enabled", connection="offline", system="Linux", ip_address="127.0.0.1", port=5000 ) db.session.add(worker) db.session.commit()
def CreationDB(): """ Création de la DB """ with app.app_context(): app.logger.info("Creation de la base de donnees...") db.create_all() app.logger.info("Creation ok.") app.logger.info("Initialisation de la migration de sqlalchemy...") flask_migrate.init() app.logger.info("Initialisation ok.") # Mémorisation du numéro de version dans la DB m = Parametre(nom="version", parametre=app.config["VERSION_APPLICATION"]) db.session.add(m) db.session.commit()
def setUp(self): #self.db_fd, app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/server_test.sqlite' app.config['TESTING'] = True self.app = app.test_client() db.create_all() # add fake worker worker = Worker(hostname='debian', status='enabled', connection='offline', system='Linux', ip_address='127.0.0.1', port=5000) db.session.add(worker) db.session.commit()
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() self.client = self.app.test_client(use_cookies=True) db.create_all() # create test user user = User( email='*****@*****.**', first_name='Alan', last_name='Smith', password='******' ) db.session.add(user) db.session.commit()
def main(): parser = argparse.ArgumentParser() parser.add_argument("--reset_db", action='store_true', help="Delete all code in database") import controllers import models args = parser.parse_args() app = create_app() if args.reset_db: db.drop_all() db.create_all() populate() app.run(host=app.config['HOST'], port=app.config['PORT'])
def setUp(self): # we need to use the root user # to be able to create the new database self.db_username = os.environ['DB_USERNAME'] self.db_password = os.environ['DB_PASSWORD'] self.db_name = os.environ['DATABASE_NAME'] + '_test' self.db_uri = 'postgresql://%s:%s@%s:5432' % (self.db_username, self.db_password, DB_HOST) engine = sqlalchemy.create_engine(self.db_uri + '/postgres') conn = engine.connect() conn.execute("commit") conn.execute("create database " + self.db_name) conn.close() self.app_factory = self.create_app() self.app = self.app_factory.test_client() with self.app_factory.app_context(): db.create_all()
def setUp(self): with self.app.app_context(): db.create_all() # create user self.test_username = '******' self.test_password = '******' self.test_user = UsersTest.create_user( username=self.test_username, password=self.test_password ) # create auth header self.auth_headers = UsersTest.create_basic_auth_header( username=self.test_username, password=self.test_password )
def load(): # Refresh the database db.drop_all() db.create_all() with warnings.catch_warnings(): warnings.simplefilter('ignore') # This throws a warning about a named ranged ... we don't care workbook = load_workbook(filename=application.config['QASSIGNMENTS_FILE_URI'], read_only=True) sheet = workbook['q Assignments'] parser = SheetParser(sheet) for data in parser.parse(): entry = Entry(*data) db.session.add(entry) db.session.commit()
def init_app(): app.config.from_object('config') from application import ( auth, models, service, conc, rest, forms, feeds, views ) if not app.testing and not path.exists(app.config['DATABASE']): db.create_all() return(app)
def setUp(self): db.drop_all() db.create_all() self.app = app self.client = app.test_client() user = User(email='*****@*****.**', password='******', name='noname', gender='M', date_of_birth=datetime.datetime.now(), current_address='nowhere', previous_address='nowhere', blocked=False, view_count=0) db.session.add(user) db.session.commit() self.lrid = uuid.uuid4() self.roles = ['CITIZEN']
def before_first_request(): logging.info("-------------------- initializing everything ---------------------") db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='editor', description='Editor') user_datastore.find_or_create_role(name='enduser', description='End-User') encrypted_password = utils.encrypt_password('hardpassword') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, active=True, confirmed_at=datetime.datetime.now()) encrypted_password = utils.encrypt_password('editorpassword') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password, active=True, confirmed_at=datetime.datetime.now()) db.session.commit() user_datastore.add_role_to_user('*****@*****.**', 'admin') user_datastore.add_role_to_user('*****@*****.**', 'editor') db.session.commit()
def index(): db.create_all() form = TicketForm(request.form) ticket_data = {} if request.method == 'POST': project_data = form.project.data title_data = form.title.data description_data = form.description.data contact_data = form.contact.data priority_data = form.priority.data ticket_row = Tickets(project=project_data, title=title_data, description=description_data, contact=contact_data, priority=priority_data) db.session.add(ticket_row) db.session.commit() tickets = Tickets.query.all() for ticket_row in tickets: print('-__-__-__-__-__-__--__-_-_-_-_') print(ticket_row.project,ticket_row.title,ticket_row.contact) ticket_data.update({"project": ticket_row.project, "title": ticket_row.title, "description": ticket_row.description, "contact": ticket_row.contact, "priority": ticket_row.priority}) return render_template('view_tickets.html', ticket_data=ticket_data)
def create_db(): """Creates database from sqlalchemy schema.""" db.create_all()
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all()
def setUp(self): self.app = create_app(TestConfig) self.app_context = self.app.app_context() self.app_context.push() # creates all database tables db.create_all()
def setUp(self): db.session.commit() db.drop_all() db.create_all()
def init_schema(): db.create_all()
def init(): db.create_all()
def setUp(self): db.create_all()
def setUp(self): # Set up the database schema(table). db.create_all() # Create table test_task = Tasks( description="Test the flask app") # create a new class >>same<< db.session.add(test_task) # save users to database db.session.commit()
def create_db(): db.create_all()
from application import db db.create_all()
def db_create(): db.create_all() print('Database Created!')
def create(default_data=True, sample_data=False): "Creates database tables from sqlalchemy models" db.create_all() populate(default_data, sample_data)
def setUp(self): #self.db_fd, app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/server_test.sqlite' app.config['TESTING'] = True self.app = app.test_client() db.create_all()
def recreate_db(): db.drop_all() db.create_all() db.session.commit()
def create_all(): from common.models.user import User print("enter") db.create_all()
def setUp(self): db.create_all() db.session.add( Qrand(qran_num='test num', qran_meal='debug', qran_what='what')) db.session.commit()
def create_courses(): if 'courses' not in db.engine.table_names(): db.create_all() course = Courses(title="foo1", description="foo fighters", credits=1, term="sei la") db.session.add(course) course = Courses(title="foo2", description="foo fighters2", credits=2, term="sei la2") db.session.add(course) course = Courses(title="foo3", description="foo fighters3", credits=2, term="sei la3") db.session.add(course) db.session.commit() flash('cursos registrado com sucesso', 'success') return render_template('index.html', indexhl=True) #%% Modelo para gerar tabelas automaticamente caso elas nao estejam no database # if 'users' not in db.engine.table_names(): # print('######################################## 2') # db.create_all() #Cria a nova tabela # flash("A tabela user nao foi encontrada e uma nova tabela foi gerada","danger") #%% # @app.route("/create_users") # def create_users(): # # Checa se a table já existe, se nao existir, cria uma nova. # if 'users' not in db.engine.table_names(): # db.create_all() #Cria a nova tabela # #modelo de usuario para tentar criar no dataframe # usuario = Users(first_name="Plinio",last_name="Silva",email = "*****@*****.**", # password = "******",admin = False) # usuario.set_password(usuario.password) # # Checa nome de usuarios na tabela # bool_usuario_registrado = False # users = Users.query.all() # for user in users: # if user.email == usuario.email: # bool_usuario_registrado = True # print('encontrado usuario já registrado') # if not bool_usuario_registrado: # db.session.add(usuario) # db.session.commit() # users = Users.query.all() # for user in users: # if user.email == usuario.email: # print('Registrado com sucesso %s'%user.email) # return render_template("user.html", users = users)
#!/usr/bin/env python3 import os from application import create_app, db # from application import AddInstrument # from flask_script import Manager app = create_app(os.getenv('FLASK_CONFIG') or 'default') # manager = Manager(app) db.create_all(app=app) if __name__ == "__main__": app.run(debug=True) # app.run(debug=True)
def setUp(self): """Create tables before test cases""" api.app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" api.app.config['TESTING'] = True self.app = api.app.test_client() db.create_all()
def init_db(): # Empty Database db.reflect() db.drop_all() db.session.commit() db.session.rollback() db.create_all() # Create New Table Entries u = User( id=5, user="******", university1="The University of Bristol MSc in Computer Science", university2= "King's College London BSc in Neuroscience First Class Degree", age=26, skill1="Python", skill2="Java", skill3="Bash", fact="I am a huge history fan and enjoy learning new tech skills!", bio= "I founded this company to pass on an essential skillset to the next generation. Programming truly changed my life! Maybe it will change yours.", interests= "I love the outdoors. Catch me outside when I'm not glued to my computer." ) u2 = User( id=2, user="******", university1="The University of Brighton BSc in Physics", university2="", age=26, skill1="Python", skill2="Java", skill3="Bash", fact= "I'm currently on a worldwide trip having randomly bumped into Harrison in Nicaragua! I'm in New Zealand right now! I'm stuck here as of Coronavirus!", bio= "I've been developing now for 5 years. I have loved every moment of it and look forward to teaching the next generation!", interests="DJ and music enthusiast.") u3 = User( id=3, user="******", university1= "Imperial College London MEng in Mathematics and Computer Science", university2="", age=21, skill1="Java", skill2="Python", skill3="C", fact= "I love the cold weather! I’d preference a ski trip over a holiday on the beach any day.", bio= "I believe the world is advancing in computing, everyone should learn to code so what a great time to start learning!", interests= "Video games, mathematics and when I finally leave the house, I enjoy hiking and exploring new places." ) u4 = User( id=4, user="******", university1="The University of Manchester in BSc in Computer Science", university2="", age=21, skill1="Java", skill2="Python", skill3="OOP", fact= "I used to participate in competitive mathematics when I was young. Now I have a pretty nice collection of medals.", bio="Programming is a great skill to have. Why not start right now?", interests= "Playing guitar, practicing yoga and travelling are some of my hobbies." ) # Add New Table Entries db.session.add(u) db.session.add(u2) db.session.add(u3) db.session.add(u4) # Push New Table Entries db.session.commit()
def Importation(secret=0): """ Importation des données depuis le serveur """ # Vérifie que le fichier d'import existe bien (vérification du code secret) nomFichier = os.path.join(basedir, "data/import_%d.crypt" % secret) if not os.path.isfile(nomFichier): return "fichier crypt inexistant" # Décryptage du fichier if IMPORT_AES == False : return "AES non disponible" cryptage_mdp = app.config['SECRET_KEY'][:10] nomFichierZIP = nomFichier.replace(".crypt", ".zip") resultat = DecrypterFichier(nomFichier, nomFichierZIP, cryptage_mdp) os.remove(nomFichier) # Décompression du fichier import zipfile if zipfile.is_zipfile(nomFichierZIP) == False : return "Le fichier n'est pas une archive valide" nomFichierDB = nomFichierZIP.replace(".zip", ".db") fichierZip = zipfile.ZipFile(nomFichierZIP, "r") buffer = fichierZip.read(os.path.basename(nomFichierDB)) f = open(nomFichierDB, "wb") f.write(buffer) f.close() fichierZip.close() os.remove(nomFichierZIP) # Importation des données from_db = "sqlite:///" + os.path.join(basedir, "data/" + os.path.basename(nomFichierDB)) to_db = app.config['SQLALCHEMY_DATABASE_URI'] # Ouvertures des bases source, sengine = make_session(from_db) smeta = MetaData(bind=sengine) destination = db.session dengine = db.engine dmeta = MetaData(bind=dengine) # Traitement de la table des paramètres #app.logger.debug("Traitement de la table parametres...") liste_parametres_destination = destination.query(models.Parametre).all() dict_parametres_destination = {} for parametre in liste_parametres_destination : dict_parametres_destination[parametre.nom] = parametre liste_tables_modifiees = [] liste_parametres_source = source.query(models.Parametre).all() for parametre in liste_parametres_source : # Mémorisation du paramètre if parametre.nom in dict_parametres_destination : # Modification si besoin d'un paramètre existant if dict_parametres_destination[parametre.nom].parametre != parametre.parametre : dict_parametres_destination[parametre.nom].parametre = parametre.parametre else : # Saisie d'un nouveau paramètre destination.add(models.Parametre(nom=parametre.nom, parametre=parametre.parametre)) # Recherche la liste des tables à importer if parametre.nom == "tables_modifiees_synchro" : tables_modifiees_synchro = parametre.parametre.split(";") destination.commit() # Traitement de la table users app.logger.debug("Traitement de la table users...") liste_users_destination = destination.query(models.User).all() dict_users_destination = {"familles" : {}, "utilisateurs" : {}} for user in liste_users_destination : if user.IDfamille != None : dict_users_destination["familles"][user.IDfamille] = user if user.IDutilisateur != None : dict_users_destination["utilisateurs"][user.IDutilisateur] = user liste_users_source = source.query(models.User).all() liste_destination = [] for user_source in liste_users_source : user_destination = None # Recherche si l'user existe déjà dans la base destination if user_source.IDfamille != None : if user_source.IDfamille in dict_users_destination["familles"] : user_destination = dict_users_destination["familles"][user_source.IDfamille] if user_source.IDutilisateur != None : if user_source.IDutilisateur in dict_users_destination["utilisateurs"] : user_destination = dict_users_destination["utilisateurs"][user_source.IDutilisateur] # Si l'user existe déjà, on le modifie si besoin if user_destination != None : if user_destination.identifiant != user_source.identifiant : user_destination.identifiant = user_source.identifiant if user_destination.password != user_source.password : user_destination.password = user_source.password if user_destination.nom != user_source.nom : user_destination.nom = user_source.nom if user_destination.email != user_source.email : user_destination.email = user_source.email if user_destination.actif != user_source.actif : user_destination.actif = user_source.actif if user_destination.session_token != user_source.session_token : user_destination.session_token = user_source.session_token # Si l'utilisateur n'existe pas, on le créé : if user_destination == None : destination.add(models.User(identifiant=user_source.identifiant, cryptpassword=user_source.password, nom=user_source.nom, email=user_source.email, \ role=user_source.role, IDfamille=user_source.IDfamille, IDutilisateur=user_source.IDutilisateur, actif=user_source.actif, \ session_token=user_source.session_token)) app.logger.debug("Enregistrement de la table users...") destination.commit() app.logger.debug("Fin de traitement de la table users.") # Liste des autres tables à transférer app.logger.debug("Traitement des autres tables...") tables = [ "cotisations_manquantes", "cotisations", "factures", "types_pieces", "pieces_manquantes", "reglements", "consommations", "periodes", "prefacturation", "ouvertures", "feries", "unites", "inscriptions", "groupes", "activites", "individus", "messages", "regies", "pages", "blocs", "elements", ] # Recherche si des actions sont présentes nbre_actions_destination = destination.query(func.count(models.Action.IDaction)).scalar() if nbre_actions_destination == 0 : # S'il n'y a aucune actions présentes, on importe toute la table Actions de la source tables.append("actions") else : # Sinon, on importe uniquement l'état des actions liste_actions_source = source.query(models.Action).all() for action in liste_actions_source : # Update table_actions_destination = Table('%sportail_actions' % PREFIXE_TABLES, dmeta, autoload=True) u = table_actions_destination.update() u = u.values({"etat" : action.etat, "traitement_date" : action.traitement_date, "reponse" : action.reponse}) u = u.where(table_actions_destination.c.ref_unique == action.ref_unique) dengine.execute(u) destination.commit() # Suppression des tables for nom_table in tables: if nom_table in tables_modifiees_synchro : try : dengine.execute("DROP TABLE %s" % "%sportail_%s" % (PREFIXE_TABLES, nom_table)) except : pass app.logger.debug("Suppression des tables ok.") # Création des tables db.create_all() # Remplissage des tables (ordre spécial) app.logger.debug("Remplissage des autres tables...") tables = [ "activites", "unites", "cotisations_manquantes", "cotisations", "factures", "types_pieces", "pieces_manquantes", "reglements", "individus", "groupes", "inscriptions", "consommations", "periodes", "ouvertures", "prefacturation", "feries", "messages", "regies", "pages", "blocs", "elements", ] if "mysql" in to_db : dengine.execute("SET foreign_key_checks = 0;") for nom_table in tables: if nom_table in tables_modifiees_synchro: dtable = Table("%sportail_%s" % (PREFIXE_TABLES, nom_table), dmeta, autoload=True) stable = Table("portail_%s" % nom_table, smeta, autoload=True) NewRecord = quick_mapper(stable) columns = list(stable.columns.keys()) data = source.query(stable).all() listeDonnees = [] for record in data : data = dict([(str(column), getattr(record, column)) for column in columns]) listeDonnees.append(data) if len(listeDonnees) > 0 : dengine.execute(dtable.insert(), listeDonnees) # Commit de l'importation des tables destination.commit() if "mysql" in to_db : dengine.execute("SET foreign_key_checks = 1;") # Fermeture et suppression de la base d'import source.close() os.remove(os.path.join(basedir, "data/" + os.path.basename(nomFichierDB))) app.logger.debug("Fin de l'importation.") return True
def init_request(): db.create_all()
def main(): db.create_all() manager.run()
def create_models(): """Map all models to database""" from application import db db.create_all()
from application import db from application.models import Vehicles db.create_all()
def CreateDatabase(): db.create_all()
def create_db(): with app.app_context(): db.create_all()
def init_database(): db.drop_all() db.create_all() # 添加用户 for i in range(0, 100): db.session.add( User('User' + str(i), 'a' + str(i), '.'.join(sample('0123456789asdfghjklqwertyuiopzxcvbnm', 10)), get_image_url())) for j in range(0, 5): db.session.add(Image(get_image_url(), i + 1)) for k in range(0, 3): db.session.add( Comment('This is a comment' + str(k), 1 + 1 * i + j, i + 1)) db.session.commit() # 修改两种方式 for i in range(50, 100, 2): user = User.query.get(i) user.username = '******' + user.username db.session.commit() User.query.filter_by(id=51).update({'username': '******'}) db.session.commit() # 删除 for i in range(50, 100, 2): comment = Comment.query.get(i + 1) db.session.delete(comment) db.session.commit() # 另一种直接使用delete()方法 # 查询 print(1) print(User.query.all()) print(2) print(User.query.get(3)) print(3) print(User.query.filter_by(id=5).first()) print(4) print(User.query.order_by(User.id.desc()).offset(1).limit(2).all()) print(5) print(User.query.filter(User.username.endswith('0')).limit(3).all()) print(6) print(User.query.filter(or_(User.id == 88, User.id == 99)).all()) print(7) print(User.query.filter(and_(User.id > 88, User.id < 99)).all()) print(8) print(User.query.filter(and_(User.id > 88, User.id < 99)).first_or_404()) print(9) print( User.query.order_by(User.id.desc()).paginate(page=1, per_page=10).items) user = User.query.get(1) # 从1开始,第1个用户 print(10) print(user.images.all()) image = Image.query.get(1) print(11) print(image.user)
def create_all(): from application import db from common.models.user import User db.create_all()
def setUp(self): db.create_all() db.session.add(Todos(task="Test the application", complete=False)) db.session.add(Todos(task="Take out the trash", complete=False)) db.session.add(Todos(task="Be a real cool dude", complete=False)) db.session.commit()
def setup(self): self.app = create_app('testing') self.client = self.app.test_client() self.ctx = self.app.test_request_context() self.ctx.push() db.create_all()
def init_db(): db.drop_all() db.create_all() click.echo('Database has been rebuilt.')
def create_data(): with app.app_context(): from application import db import models db.create_all()
def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client with self.app.app_context(): db.create_all()
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all()
def do_init_db(): if not database_exists(db.engine.url): create_database(db.engine.url) db.create_all()