def admin(): adm = tables.User.query.filter_by(admin=2).first() if adm is None: while (True): name = prompt("Please enter the administrator's name") if name == None: print("You must enter a name!!!") else: if prompt_bool("Correct name?", default=True): break while (True): email = prompt("Enter admin email") if email == None: print("You must enter an email!!!") else: if prompt_bool("Email Correct?", default=True): break while (True): password = prompt_pass("Enter the administrator password") password_v = prompt_pass("Re-enter password") if password == None or password_v == None or password != password_v: print("You must enter a valid password!!!") else: if prompt_bool("Password correct?", default=True): break adm = tables.User(name=name, password=password, email=email, admin=2) adm.hash_password(password) db.session.add(adm) db.session.commit() print("Admin created!") else: print("Admin already exists!")
def create(): "Creates database tables" if prompt_bool("**DANGER AREA** Are you sure you want to proceed?"): if prompt_bool( "You are about to create the ENTIRE database from scratch. Are you sure?" ): db.create_all()
def create_user(): username = prompt('用户名').strip() password = prompt_pass('密码').strip() repassword = prompt_pass('重复密码').strip() is_super = prompt_bool('超级用户') is_staff = prompt_bool('后台用户') if not all([username, password, repassword]): print('请输入完整数据') return if password != repassword: print('两次输入密码不同') return connect_db() user = User() user.username = username user.password = password user.is_super = is_super user.is_staff = is_staff db_session.add(user) db_session.commit() print('创建用户成功!')
def rebuild(): "Rebuild database tables" if prompt_bool("**DANGER AREA** Are you sure you want to proceed?"): if prompt_bool( "You are about to rebuild the ENTIRE database from scratch. Are you sure?" ): db.drop_all() db.create_all()
def init_db(table_name=None): """ Initialize DB or table """ if table_name: if prompt_bool( f'Are you sure you want to initialized table of {table_name}'): Base.metadata.tables[table_name].create(bind=engine) elif prompt_bool('Are you sure you want to initialized database'): Base.metadata.create_all(engine)
def createuser(username=None, password=None, admin=None): """Create a user account for the application. """ u_name = username pw = password make_admin = admin if u_name is None: while True: u_name = prompt("User Name") user = User.query.filter(User.name == u_name).first() if user is not None: print("{}: USER ALREADY EXISTS!".format(u_name)) else: break if pw is None: pw = prompt_pass("Password") while True: pw_again = prompt_pass("Password Again") if pw != pw_again: print("PASSWORDS DO NOT MATCH!") else: break if make_admin is None: make_admin = prompt_bool("Do you wish to make {} an administrator?".\ format(u_name)) user = User(name=u_name, password="", admin=make_admin, enabled=True) user.set_password(pw) db.session.add(user) db.session.commit() print("Successfully created '{}' with ID: {}.".format(user.name, user.id))
def drop(): """Drops database tables""" if prompt_bool("Are you sure you want to lose all your data"): inspector = reflection.Inspector.from_engine(db.engine) metadata = MetaData() tbs = [] all_fks = [] for table_name in inspector.get_table_names(): fks = [] for fk in inspector.get_foreign_keys(table_name): if not fk['name']: continue fks.append( ForeignKeyConstraint((),(),name=fk['name']) ) t = Table(table_name,metadata,*fks) tbs.append(t) all_fks.extend(fks) for fkc in all_fks: db.engine.execute(DropConstraint(fkc)) for table in tbs: db.engine.execute(DropTable(table)) db.session.commit() print ('All tables are dropped.') return True return False
def run(self): if prompt_bool("This will permanently alter the database. Continue?"): tmdb = current_app.tmdb cursor = tmdb.get_cursor() cursor.execute(tmdb.DEPLOY_QUERY % {'slang': 'en'}) tmdb.connection.commit() print("Succesfully altered the database for deployment.")
def test(force_unittest): """Try to run the tests. If Flask-Testing does not exist, a hint is displayed. """ spec = importlib.util.find_spec("flask_testing") if spec is None: large_message("It seems Flask-Testing is missing. " "Are you sure you are in the " "correct environment?") if not prompt_bool("Continue?", default=False): print("Aborting.") exit(255) timeout = os.getenv('CONNETION_TIMEOUT') if os.getenv('CONNETION_TIMEOUT'): connections = [('postgres', 5432), ('ldap_hss', 389)] if not wait_until_ready(connections): exit(254) if not force_unittest: result = run_tests_nose() else: result = run_tests_unittest() exit(result)
def user_create(grant_admin): """Creates new user""" update_session_options(db) user_type = 'user' if not grant_admin else 'admin' while True: email = prompt_email() if email is None: return email = email.lower() if not User.find(User.all_emails.contains(email), ~User.is_deleted, ~User.is_pending).count(): break error('Email already exists') first_name = prompt("First name") last_name = prompt("Last name") affiliation = prompt("Affiliation", '') print() while True: username = prompt("Enter username").lower() if not Identity.find(provider='indico', identifier=username).count(): break error('Username already exists') password = prompt_pass() if password is None: return identity = Identity(provider='indico', identifier=username, password=password) user = create_user(email, {'first_name': to_unicode(first_name), 'last_name': to_unicode(last_name), 'affiliation': to_unicode(affiliation)}, identity) user.is_admin = grant_admin print_user_info(user) if prompt_bool(cformat("%{yellow}Create the new {}?").format(user_type), default=True): db.session.add(user) db.session.commit() success("New {} created successfully with ID: {}".format(user_type, user.id))
def drop_db(): """Drop all db tables""" if prompt_bool('Are you sure you want to lose all your data'): db.drop_all() result = db.engine.execute( "DROP TABLE IF EXISTS `ops`.`alembic_version`") print "delete version table: " + str(result)
def drop(yes=False): """drop all database tables""" try: if yes or prompt_bool("Are you sure you want to lose all your data"): db.drop_all() except KeyboardInterrupt: pass
def user_create(grant_admin): """Creates new user""" user = User() user_type = 'user' if not grant_admin else 'admin' print() name = prompt("First name") surname = prompt("Last name") affiliation = prompt("Affiliation") print() username = prompt("Enter username") email = prompt_email() if email is None: return password = prompt_pass() if password is None: return user.first_name = to_unicode(name) user.last_name = to_unicode(surname) user.affiliation = to_unicode(affiliation) user.email = email user.is_admin = grant_admin print_user_info(user) if prompt_bool(cformat("%{yellow}Create the new {}?").format(user_type), default=True): # TODO: adapt to new authentication system, create local identity with username/password # user.identities.append(UserIdentity(..., identifier=username, password=password)) db.session.add(user) transaction.commit() success("New {} created successfully with ID: {}".format(user_type, user.id))
def dropall(pass_ask=None): "Drops all database tables" if pass_ask: db.drop_all() else: if prompt_bool("Are you sure ? You will lose all your data !"): db.drop_all()
def dropall(): # 终端下给与简单的确认提示 if prompt_bool('确定要删除所有数据表吗?'): db.drop_all() return '数据表已删除' else: return '最好再考虑一下'
def drop_db(): if prompt_bool( "Are you sure you would like to permanently" + " erase this data? You should do an upgrade of the db after this"): db.drop_all() print "dropped db"
def create_user(): """ Create a new user. """ email = None while not email: email_tmp = prompt("Email") email_test = _DummyEmailField(email_tmp) email_validator = Email() try: email_validator(None, email_test) except ValidationError: print("Email is invalid") else: with current_app.app_context(): if User.query.filter_by(email=email_tmp).first(): print("User already exists") else: email = email_tmp password = None while not password: password = prompt_pass("Password") admin = prompt_bool("Administrator?") roles = ("Admin",) if admin else () add_user(email, password, roles) print("User added")
def dropdb(): """ drops the database """ if prompt_bool("Are you sure you want to lose all your data"): db.drop_all() print "Dropped the database"
def run(self, source_langs): ensure_source_exists() if prompt_bool("This will permanently destroy all data in the " "configured database. Continue?"): current_app.tmdb.drop_db(source_langs) langs = "', '".join(source_langs) print("Successfully dropped the database for '%s'." % langs)
def resetdatabase(): "Delete all data, reset everything" if prompt_bool("Are you absolutely certain you want to delete all this things?"): db = connect(app.config['MONGODB_DB'], host=app.config['MONGODB_HOST'], port=app.config['MONGODB_PORT']) db.drop_database(app.config['MONGODB_DB']) print("Deleted all collections from database ...")
def create_user(): def create_and_add_user(email): password = prompt('Enter password') user = user_datastore.create_user(email=email, password=password) super_user = prompt_bool('Should user be admin?') if super_user: super_user_role = user_datastore.find_or_create_role('superuser') user_datastore.add_role_to_user(user, super_user_role) else: user_role = user_datastore.find_or_create_role('user') user_datastore.add_role_to_user(user, user_role) db.session.add(user) db.session.commit() print('New credentials are {}/{}'.format(email, password)) with app.app_context(): email = prompt('Enter email') user = user_datastore.find_user(email=email) if user: if prompt_bool('User already exists. Override?'): user_datastore.delete_user(user) db.session.commit() create_and_add_user(email) else: print('Exiting...') exit(0) else: create_and_add_user(email)
def drop_all_tables(): if prompt_bool("Are you sure you want to lose all your data?"): try: db.drop_all() except Exception as e: return f'Unable to drop tables: {e}' print('[ db ] -> All tables have been dropped')
def run(self): """Drop all tables after user ha verified.""" verified = prompt_bool( 'Do you really want to drop all the database tables?') if verified: sys.stdout.write('All tables dropped. Database is now empty.\n') drop_all()
def recreate(): "Recreates database tables (same as issuing 'drop' and then 'create')" print 'Connected to {}'.format(repr(db.engine.url)) if prompt_bool("Are you sure you want to recreate the database?"): db.drop_all() db.create_all() print 'Database re-created'
def user_create(grant_admin): """Creates new user""" user = User() user_type = 'user' if not grant_admin else 'admin' print() name = prompt("First name") surname = prompt("Last name") affiliation = prompt("Affiliation") print() username = prompt("Enter username") email = prompt_email() if email is None: return password = prompt_pass() if password is None: return user.first_name = to_unicode(name) user.last_name = to_unicode(surname) user.affiliation = to_unicode(affiliation) user.email = email user.is_admin = grant_admin print_user_info(user) if prompt_bool(cformat("%{yellow}Create the new {}?").format(user_type), default=True): # TODO: adapt to new authentication system, create local identity with username/password # user.identities.append(UserIdentity(..., identifier=username, password=password)) db.session.add(user) transaction.commit() success("New {} created successfully with ID: {}".format( user_type, user.id))
def dropdb(): "drop db" result = prompt_bool("Are you sure to delete all databases?") print(result) if result: print("ahahaa") pass
def run(self, index_name): """Delete timeline in both Timesketch and Elasticsearch. Args: index_name: The name of the index in Elasticsearch """ index_name = unicode(index_name.decode(encoding=u'utf-8')) searchindex = SearchIndex.query.filter_by( index_name=index_name).first() if not searchindex: sys.stdout.write(u'No such index\n') sys.exit() es = ElasticsearchDataStore(host=current_app.config[u'ELASTIC_HOST'], port=current_app.config[u'ELASTIC_PORT']) timelines = Timeline.query.filter_by(searchindex=searchindex).all() sketches = [ t.sketch for t in timelines if t.sketch and t.sketch.get_status.status != u'deleted' ] if sketches: sys.stdout.write(u'WARNING: This timeline is in use by:\n') for sketch in sketches: sys.stdout.write(u' * {0:s}\n'.format(sketch.name)) sys.stdout.flush() really_delete = prompt_bool( u'Are you sure you want to delete this timeline?') if really_delete: for timeline in timelines: db_session.delete(timeline) db_session.delete(searchindex) db_session.commit() es.client.indices.delete(index=index_name)
def createUser(): """create new user """ from app import db from app.services.models.user import User from app.services.forms.users import CreateUserForm name = prompt("name ?") userName = prompt("user name ?") password = prompt_pass("password ?") print([name, userName, password]) superUser = prompt_bool("Is super user ?") user = User(password=password, name=name, userName=userName, allowLogin=True, active=True, isAdmin=superUser) form = CreateUserForm(obj=user) if form.validate(): try: db.session.add(user) db.session.commit() except Exception as e: print(e) else: print(form.errors)
def dropall(): """ 删除所有表 :return: """ if prompt_bool("Are you sure?"): db.drop_all()
def dropdb(): ''' Delete the SQL database. ''' from app.database import drop_db if prompt_bool('Are you sure you want to lose all your SQL data?'): drop_db() print(colored('The SQL database has been deleted', 'green'))
def db_init(): if not prompt_bool('Caution!!!\nThis will drop the whole database ' 'and re-create it, are you sure? [yn]'): return db.drop_all() db.create_all()
def migratedb(): """Migrates the DB.""" if prompt_bool("Are you sure you want to lmigrate all data"): dropdb() initdb() populatedb() print("Database Migrated")
def config( mysql=None, username=_default, password=None, server=_server, database=_default, folder=_folder, ): """Generate config.py for AwesomeTitle. If there were some given parameters, those questions will be handled automatically. """ # TODO : Is Existed config.py? base = dirname(abspath(__file__)) # XXX : Check '-m' or '--mysql' options entered. if mysql is None: use_mysql = prompt_bool("Use MySQL?", default=True) else: if mysql == "True": use_mysql = True elif mysql == "False": use_mysql = False else: raise Exception("`-m` or `--mysql` needed `True` or `False`.") if use_mysql is True: # XXX : Check '-u' or '--username' options entered. if username is _default: username = prompt("MySQL DB Username", default=username) # XXX : Check '-p' or '--password' options entered. if not password: password = prompt_pass("MySQL DB Password") # XXX : Check '-s' or '--server' options entered. if server is _server: server = prompt("MySQL DB Server", default=server) # XXX : Check '-d' or '--database' options entered. if database is _default: database = prompt("MySQL DB Database", default=database) # XXX : Check '-f' or '--folder' options entered. if folder is _folder: folder = prompt("Image Upload Folder", default=folder) folder = join(base, folder) if not exists(folder): makedirs(folder) secret_key = urandom(24) with open("confs/config.py.tmpl") as tmpl: Template( tmpl.read() ).stream( base=base, username=username, password=password, server=server, database=database, folder=folder, secret_key=secret_key, use_mysql=use_mysql, ).dump("AwesomeTitleServer/config.py")
def drop(): """ Drops database tables """ verified = prompt_bool( 'Do you really want to drop all the database tables?') if verified: sys.stdout.write('All tables dropped. Database is now empty.\n') db.drop_all()
def demoData(): """create demo data """ if not prompt_bool("Are you sure ?????"): return from app import db from app.services.models.patient import Patient from app.services.models.room import Room from app.services.models.service import Service from app.services.models.user import User, Doctor # create admin user for testing db.session.add(User(password='******', name='admin', userName='******', allowLogin=True, active=True, isAdmin=True)) # create normal user for testing db.session.add(User(password='******', name='user1', userName='******', allowLogin=True, active=True, isAdmin=False)) # create service for x in range(1, 150): db.session.add(Service(name='service ' + str(x), price=x * 100)) # create doctors for x in range(1, 50): db.session.add(Doctor(name='dr. ' + str(x), userName='******' + str(x), password='******')) for x in range(1, 15): db.session.add(Room(name='room ' + str(x))) for x in range(1, 1000): db.session.add(Patient(name='patient ' + str(x), mobileNumber=str(1212891289) + str(x))) try: db.session.commit() except Exception as e: print(e)
def pg_migrate(project_id, project_group_slug): project_group = ProjectGroup.objects(slug=project_group_slug).first() project = Project.objects(id=project_id).first() if project_group and \ project_group.is_not_default and \ project and \ prompt_bool("Are you sure you want to migrate all project-env?"): project.project_group = project_group project.save() # project_group_join for user in project.members: try: pgu = project_group.join(user) except NotUniqueError: pgu = ProjectGroupUser.objects.get(project_group=project_group, user=user) # user.default_project_group_id = pg.id # user.save() # project_user pu = ProjectUserBase.objects.get(project=project, user=user) pu.project_group_user = pgu pu.save() # pg.save() print('done')
def dropdb(): """Drop database tables""" manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
def dropdb(): "Drop database tables" manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
def create_all_tables(): if prompt_bool("Are you sure you want to create all tables?"): try: db.create_all() except Exception as e: return f'Unable to create all tables: {e}' print("[ db ] -> All tables have been successfully created")
def delete_contracts(): if prompt_bool("Are you sure you want to lose all contracts & companies?"): print 'Deleting!' from purchasing.data.models import ContractBase, Company ContractBase.query.delete() Company.query.delete() db.session.commit() return
def drop_database(): """Drop database tables.""" if prompt_bool("Are you sure you want to lose all your data"): try: db.drop_all() print("Dropped all tables susscefully.") except Exception: print("Failed, make sure your database server is running!")
def drop_db(): if prompt_bool( 'Are you sure you want to lose all your data for {0} ? \nThis is process is not reversible'.format( app.config['SQLALCHEMY_DATABASE_URI'].split('@')[1]) ): db.drop_all() db.session.commit() print('Database has been dropped')
def install(username=None, password=None, email=None): """Installs FlaskBB with all necessary data.""" print("Creating default data...") try: create_default_groups() create_default_settings() except IntegrityError: print("Couldn't create the default data because it already exist!") if prompt_bool("Found an existing database." "Do you want to recreate the database? (y/n)"): db.session.rollback() db.drop_all() upgrade() create_default_groups() create_default_settings() else: sys.exit(0) except OperationalError: print("No database found.") if prompt_bool("Do you want to create the database now? (y/n)"): db.session.rollback() upgrade() create_default_groups() create_default_settings() else: sys.exit(0) print("Creating admin user...") if username and password and email: create_admin_user(username=username, password=password, email=email) else: create_admin() print("Creating welcome forum...") create_welcome_forum() print("Compiling translations...") compile_translations() if prompt_bool("Do you want to use Emojis? (y/n)"): print("Downloading emojis. This can take a few minutes.") download_emoji() print("Congratulations! FlaskBB has been successfully installed")
def test(): """Run the unit tests.""" if not prompt_bool("Are you sure ?????"): return import unittest startDir = 'app' tests = unittest.TestLoader().discover(startDir) unittest.TextTestRunner(verbosity=2, failfast=True).run(tests)
def wrapper(*args, **kwargs): if NOI_ENVIRONMENT != DEV_ENVIRONMENT: print ( "WARNING: The '%s' command was designed for use *only* in \n" "%s mode, but you seem to be in %s mode." ) % (fn.__name__, DEV_ENVIRONMENT, NOI_ENVIRONMENT) if not prompt_bool("Are you sure you want to proceed?"): print "Aborting operation." return fn(*args, **kwargs)
def drop(): "Drops database tables" if prompt_bool("Are you sure you want to lose all your data"): print 'Droping Tables ...' try: db.drop_all() except Exception as e: print 'Failed due to exception:{ex}'.format(ex=e) else: print 'Done'
def init(username=None, password=None, email=None): """Initializes FlaskBB with all necessary data.""" app.logger.info("Creating default data...") try: create_default_groups() create_default_settings() except IntegrityError: app.logger.error("Couldn't create the default data because it already " "exist!") if prompt_bool("Found an existing database." "Do you want to recreate the database? (y/n)"): db.session.rollback() db.drop_all() upgrade() create_default_groups() create_default_settings() else: sys.exit(0) except OperationalError: app.logger.error("No database found.") if prompt_bool("Do you want to create the database now? (y/n)"): db.session.rollback() upgrade() create_default_groups() create_default_settings() else: sys.exit(0) app.logger.info("Creating admin user...") if username and password and email: create_admin_user(username=username, password=password, email=email) else: create_admin() app.logger.info("Creating welcome forum...") create_welcome_forum() app.logger.info("Compiling translations...") compile_translations() app.logger.info("Congratulations! FlaskBB has been successfully installed")
def create_user(): connect_db() username = prompt('username') password = prompt_pass('password') repassword = prompt_pass('repassword') is_super = prompt_bool('is super(default: True)', default='y') is_staff = prompt_bool('is staff(default: True)', default='y') if password != repassword: print('the two password is not same!') return user = User() user.username = username user.password = password user.is_super = is_super user.is_staff = is_staff db_session.add(user) db_session.commit() print('create user success')
def drop_db(remove=False, force=False): if not force: if not prompt_bool("Are you sure?"): return db.drop_all() logger.info("Database was dropped") if remove: call(["rm", app.config["DB_PATH"]]) logger.info("Database file was removed")
def createSchema(): """create database schema """ if not prompt_bool("Are you sure ?????"): return from app import db try: db.create_all() except Exception as e: print(e)
def reset_db(): if prompt_bool( 'Are you sure you want to lose all your data for {0}'.format( app.config['SQLALCHEMY_DATABASE_URI'].split('@')[1]) ): from alembic.command import downgrade, upgrade from alembic.config import Config as AlembicConfig config = AlembicConfig('alembic.ini') downgrade(config, 'base') upgrade(config, 'head') print('Database has been reset')
def sharedSessionPrices(): """update all session shared prices""" if not prompt_bool("Are you sure ?????"): return from app import db from app.services.models.serviceOrder import ServiceOrder serviceOrders = db.session.query(ServiceOrder).all() for serviceOrder in serviceOrders: serviceOrder.calculateSessionsSharedPrice() db.session.add(serviceOrder) db.session.commit()
def delete_contracts(): if prompt_bool("Are you sure you want to lose all contracts & companies?"): print 'Disabling triggers...' turn_off_sqlalchemy_events() print 'Deleting!' from purchasing.data.contracts import ContractBase, Company ContractBase.query.delete() Company.query.delete() db.session.commit() print 'Enabling triggers...' turn_on_sqlalchemy_events() return
def add_blueprint(testing=False): template_dir = _template_dir('blueprint') if testing: target_dir = './testing' else: target_dir = os.curdir if target_dir == os.curdir: if not prompt_bool('not testing, are you sure you want to continue...'): sys.exit(0) list_questions = False non_interactive = False args = [template_dir,'-O',target_dir,'-v','-w'] cli.main(args)
def install(username=None, password=None, email=None): """Installs DTS with all necessary data.""" print ("Creating default data...") try: Role.insert_roles() BugStatus.insert_bug_status() except IntegrityError: print ("Couldn't create the default data because it already exist!") if prompt_bool("Found an existing database." "Do you want to recreate the database? (y/n)"): db.session.rollback() db.drop_all() db.create_all() print ("Creating DataBase Default Data...") Role.insert_roles() BugStatus.insert_bug_status() else: sys.exit(0) except OperationalError: print ("No database found.") if prompt_bool("Do you want to create the database now? (y/n)"): db.session.rollback() db.drop_all() db.create_all() print ("Creating DataBase Default Data...") Role.insert_roles() BugStatus.insert_bug_status() else: sys.exit(0) print ("Creating admin user...") if username and password and email: User.create_admin_user(username=username, password=password, email=email) else: create_admin() dir_create() print ("Congratulations! DTS has been successfully installed")