def populte(): print('drop database') db.drop_all() print('drop done') print('create database') db.create_all() print('create database done') print('creating......') for user in users: hash_password = bcrypt.generate_password_hash( user.get('password')).decode('utf-8') create_user = User(username=user.get('username'), email=user.get('email'), password=hash_password) account = Account() create_user.account = account db.session.add(create_user) db.session.commit() print('create user success') print('create users done') admin = User.query.filter_by(username='******').first() for post in posts: create_post = Post(title=post, content=post * 3, author=admin) db.session.add(create_post) db.session.commit() print('create post success') print('done')
def setUp(self): self.db_uri = 'mysql://%s:%s@mysql:3306' % (app.config['DB_USERNAME'], app.config['DB_PASSWORD']) app.config['testing'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQL_ALCHEMY_DATABASE_URI'] = self.db_uri + app.config['BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): self.db_uri = 'mysql+pymysql://%s:%s@%s/' % (app.config['DB_USERNAME'], app.config['DB_PASSWORD'], app.config['DB_HOST']) app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQLALCHEMY_DATABASE_URI'] = self.db_uri + app.config['BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("create database " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): self.db_uri = 'mysql://%s:%s@mysql:3306' % (app.config['DB_USERNAME'], app.config['DB_PASSWORD']) app.config['testing'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQL_ALCHEMY_DATABASE_URI'] = self.db_uri + app.config[ 'BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): db_username = app.config['DB_USER'] db_password = app.config['DB_PASSWORD'] db_host = app.config['DB_HOST'] self.db_uri = "mysql+pymysql://%s:%s@%s/" % (db_username, db_password, db_host) app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQLALCHEMY_DATABASE_URI'] = self.db_uri + app.config['BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute('commit') conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): print('setUp()') self.db_uri = 'mysql+pymysql://%s:%s@%s/' % ('harinder', '12345', 'localhost') app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQLALCHEMY_DATABASE_URI'] = self.db_uri + app.config[ 'BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("create database " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def app(): print("\nCalling app fixture...\n") app = create_app(testing=True) with app.app_context(): db.drop_all() db.create_all() db.session.add_all((User(username='******', password='******'), User(username='******', password='******'), Post(title='test title', body='test\nbody', author_id=1, created=datetime.date(2021, 2, 28)))) db.session.commit() yield app
def setUp(self): db_username = app.config["DB_USERNAME"] db_password = app.config["DB_PASSWORD"] db_host = app.config["DB_HOST"] self.db_uri = "mysql+pymysql://%s:%s@%s/" % (db_username, db_password, db_host) app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False app.config["BLOG_DATABASE_NAME"] = "test_blog" app.config["SQLALCHEMY_DATABASE_URI"] = self.db_uri + app.config["BLOG_DATABASE_NAME"] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config["BLOG_DATABASE_NAME"]) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): db_username = app.config['DB_USERNAME'] db_password = app.config['DB_PASSWORD'] db_host = app.config['DB_HOST'] self.db_uri = 'mysql+pymysql://%s:%s@%s/' % (db_username, db_password, db_host) app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQLALCHEMY_DATABASE_URI'] = self.db_uri + app.config['BLOG_DATABASE_NAME'] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute('commit') conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): db_username = app.config["DB_USERNAME"] db_password = app.config["DB_PASSWORD"] db_host = app.config["DB_HOST"] self.db_uri = "mysql+pymysql://%s:%s@%s/" % (db_username, db_password, db_host) app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False app.config["BLOG_DATABASE_NAME"] = "test_blog" app.config["SQLALCHEMY_DATABASE_URI"] = self.db_uri + app.config[ "BLOG_DATABASE_NAME"] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config["BLOG_DATABASE_NAME"]) db.create_all() conn.close() self.app = app.test_client()
def setUp(self): self.db_uri = "mysql://%s:%s@mysql:3306" % (app.config["DB_USERNAME"], app.config["DB_PASSWORD"]) app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] app.config["BLOG_DATABASE_NAME"] = "test_blog" app.config["SQL_ALCHEMY_DATABASE_URI"] = self.db_uri + app.config["BLOG_DATABASE_NAME"] engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config["BLOG_DATABASE_NAME"]) db.create_all() conn.close() self.app = app.test_client() def tearDown(self): db.session.remove() engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("DROP DATABASE " + app.config["BLOG_DATABASE_NAME"]) conn.close() def create_blog(self): return self.app.post( "/setup", data=dict( name="Test Blog", fullname="Libert R Schmidt", email="*****@*****.**", username="******", password="******", confirm="test", ), follow_redirect=True, ) def test_create_blog(self): rv = self.create_blog() print rv.data assert "Blog created" in rv.data
def setUp(self): #setting up the test db db_username = app.config['DB_USERNAME'] db_password = app.config['DB_PASSWORD'] db_host = app.config['DB_HOST'] self.db_uri = DB_URI = "mysql+pymysql://%s:%s@%s/" % (db_username, db_password, db_host) #so flask knows that testing is happening app.config['TESTING'] = True #since we are checking we want to allow mock requests without checking csrf app.config['WTF_CSRF_ENABLED'] = False app.config['BLOG_DATABASE_NAME'] = 'test_blog' app.config['SQLALCHEMY_DATABASE_URI'] = self.db_uri + app.config['BLOG_DATABASE_NAME'] #create sqlalchemy instance we can talk to engine = sqlalchemy.create_engine(self.db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) #so all tables are created db.create_all() conn.close() #instantiate app self.app = app.test_client()
def make_migration(): with app.app_context(): db.drop_all() tables_name = ['user','post','account'] for name in tables_name: conn = psycopg2.connect(database='flaskdb',user='******',password='******',host='localhost') cursor = conn.cursor() try: cursor.execute(f'select * from public.{name}') conn.close() except Exception as e: # 需要将连接写入循环,因查询第一次后会触发连接断开 if f'错误: 关系 "public.{name}" 不存在' in str(e): print(f'确认删除表{name}') conn.close() # print(dir(cursor)) else: print(e) print('清空数据库成功') print('准备重新初始化数据库') db.create_all() print('初始化数据库成功') # 获取上次excel文件 os.getcwd() file_dir = os.getcwd()+'/migrations/' ls = os.listdir(file_dir) next_number = 0 # 初始编号 if ls: combine_tuple = tuple(zip(range(len(ls)),ls)) print(combine_tuple) next_number = combine_tuple[-1][0] ex_file_name = f'migrations/mg{next_number}_blog.xlsx' wb = load_workbook(filename = ex_file_name) with psycopg2.connect(database='flaskdb',user='******',password='******',host='localhost') as conn: cursor = conn.cursor() for name in tables_name: sheet = wb[f'{name} data'] rows = sheet.rows # print(dir(rows)) print('-'*12) model_name = name.title() # model名 same_fields = None # 字段相同但是位置不一样时这个变量用来代替real_fields tag_delete = None # 字段减少标志重置 tag_add = None # 字段增加标志重置 diff_fields = None # 子循环完毕重置 diff_fields_index = [] # 索引位列表,用于删除或插入line的数据 for row in rows: cursor.execute(f'select * from public.{name}') fields = cursor.description # print(fields) fields_name = [ field[0] for field in fields] line = [col.value for col in row] real_fields = fields_name orig_fields = line # print(real_fields) # print(orig_fields) if fields_name == orig_fields: # 字段没有改变 print(f'The {name} table fields no change') continue elif len(fields_name) < len(orig_fields) and tag_delete is not True: # 字段减少 diff_fields = [ field for field in orig_fields if field not in fields_name] print(f'The {name} table fields have been changed ,{diff_fields} are removed') tag_delete = True # 字段减少导致的数据错位,需要删除对应字段的数据 if diff_fields: for field in diff_fields: index = orig_fields.index(field) diff_fields_index.append(index) # print(diff_fields_index) continue elif len(fields_name) > len(orig_fields) and tag_add is not True: # 字段增加 diff_fields = [ field for field in real_fields if field not in orig_fields] print(f'The {name} table fields have been changed ,{diff_fields} are added') tag_add = True # 字段增加导致的数据错位,需要插入对应字段的数据,默认插入None,字段要在数据库中允许为空 if diff_fields: for field in diff_fields: index = real_fields.index(field) diff_fields_index.append(index) continue elif fields_name != orig_fields and orig_fields[0] == 'id': # print(fields_name == line) diff_fields = [ field for field in orig_fields if field not in fields_name] # print(diff_fields) if not diff_fields and len(fields_name) == len(orig_fields): # 字段相同但是位置不一样 print(f'The {name} table fields are same before , but locations are difference') same_fields = orig_fields # print(same_fields) if diff_fields: raise AttributeError(f'{diff_fields} fields not found') continue if same_fields: import_db(name,same_fields,line) if diff_fields_index: # print(diff_fields_index) diff_index = 0 for index in diff_fields_index: if tag_delete: _data = line.pop(index-diff_index) print(f'因{diff_fields[diff_index]}移除,{_data}将不被导入数据库') if tag_add: line.insert(index,None) print(f'字段{diff_fields[diff_index]}增加,开始导入默认数据') diff_index += 1 dict_data = dict(zip(real_fields,line)) if tag_add: list_data = list(zip(real_fields,line)) rm_index = 0 for index in diff_fields_index: rm_data = list_data.pop(index-rm_index) rm_index += 1 print(f'该行导入默认数据完成') dict_data = dict(list_data) import_db(model_name,dict_data) print('-'*8) if (not tag_add and not tag_delete) and not same_fields: dict_data = dict(zip(real_fields,line)) import_db(model_name,dict_data)
import os, sys #scripts sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask_blog import app import sqlalchemy try: db_uri = 'mysql://%s:%s@mysql:3306/' % (app.config['DB_USERNAME'],app.config['DB_PASSWORD']) engine = sqlalchemy.create_engine(db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) conn.close() except: print "Database exists" from flask_blog import db #add all modules here from user.models import * from home.models import * db.create_all()
import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask_blog import app import sqlalchemy try: db_uri = 'mysql://%[email protected]:3306/' % (app.config['DB_USERNAME']) engine = sqlalchemy.create_engine(db_uri) conn = engine.connect() conn.execute("commit") conn.execute("CREATE DATABASE " + app.config['BLOG_DATABASE_NAME']) conn.close() except: print "Database Exists" from flask_blog import db # add all models here from user.models import * db.create_all()
def init_db(): db.drop_all() db.create_all()
def run(self): 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 init_db(): db.create_all()
def run(self): # 実際にスクリプトで実行される内容。 db.create_all() # →これでモデル定義が反映される。