def writeDatabase(data): ''' goes through 2D list, where each row has the player data and stores the data into a database : param: data; data stored in a 2D list : return: None Preconditions: data has been accurately scraped and stored in a 2D list; for each row, data is stored as follows: firstName, lastName, special, number, position,shoots, height, weight Postconditions: database of players has been created ''' # go through list of data and store each row, representing player data for i in range(len(data)): db.session.add( Player( firstName=data[i][FIRST_NAME], lastName=data[i][LAST_NAME], special=data[i][SPECIAL], number=data[i][NUMBER], position=data[i][POSITION], shoots=data[i][SHOOTS], height=data[i][HEIGHT], weight=data[i][WEIGHT], )) # create and commit changes db.create_all() db.session.commit()
def drop_and_create_database(): if database_exists(db.engine.url): drop_database(db.engine.url) create_database(db.engine.url) db.drop_all() db.create_all() db.session.commit()
def listlink(): try: links= Link.query.all() return render_template("_link.html", links = links) except: db.create_all() return render_template("_link.html", links = None)
def listssh(): try: sshs= Ssh.query.all() return render_template("_ssh.html", sshs = sshs) except: db.create_all() return render_template("_ssh.html", sshs = None)
def initdb(): """initialize database""" db.drop_all() db.create_all()
def setUp(self): """ Runs before each test """ service.init_db() db.drop_all() # clean up the last tests db.create_all() # create new tables Shopcart(user_id=1, product_id=1, quantity=1, price=12.00).save() Shopcart(user_id=1, product_id=2, quantity=1, price=15.00).save() self.app = service.app.test_client()
def setUp(self): """ Runs before each test """ # service.init_db() db.drop_all() # clean up the last tests db.create_all() # create new tables Product(pid=1,pname="Athens Table", pdesc='Stupid Table', pcat="Table", pprice=20, pcond="Boxed",pinv=2, prev="", prat=5).save() Product(pid=2,pname="Rome Chair", pdesc='Stupid Chair', pcat="Chair", pprice=40, pcond="Boxed", pinv=2, prev="",prat=8).save() self.app = service.app.test_client()
def client(app): with app.app_context() as c: from app.model import db try: db.create_all() yield app.test_client() finally: db.session.remove() db.drop_all()
def setUp(self): self.app = create_app("config.TestingConfig") self.db_fd, self.app.config[ "SQLALCHEMY_DATABASE_URI"] = tempfile.mkstemp() with self.app.app_context(): db.create_all()
def init(u, p): # 初始化数据库 db.init_app(app) db.create_all(app=app) # 新建用户 new_user = UserModel(name=u, password_hash=UserModel.set_password(p)) db.session.add(new_user) db.session.commit() click.echo('Success.')
def build_sample_db(): """ Populate a small db with some example entries. """ import string import random db.drop_all() db.create_all() with app.app_context(): user_role = Role(name='user') super_user_role = Role(name='superuser') db.session.add(user_role) db.session.add(super_user_role) db.session.commit() test_user = user_datastore.create_user( name='admin', email='admin', password=hash_password('admin'), roles=[super_user_role, user_role]) test_user = user_datastore.create_user( name='zhang', email='zhang', password=hash_password('123123'), roles=[user_role]) roles = [user_role, super_user_role] # # first_names = [ # 'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie', 'Mia', # 'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica', # 'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy' # ] # last_names = [ # 'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas', # 'Roberts', 'Khan', 'Lewis', 'Jackson', 'Clarke', 'James', 'Phillips', 'Wilson', # 'Ali', 'Mason', 'Mitchell', 'Rose', 'Davis', 'Davies', 'Rodriguez', 'Cox', 'Alexander' # ] # # for i in range(len(first_names)): # tmp_email = first_names[i].lower() + "." + last_names[i].lower() + "@example.com" # tmp_pass = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)) # user_datastore.create_user( # first_name=first_names[i], # last_name=last_names[i], # email=tmp_email, # password=encrypt_password(tmp_pass), # roles=[user_role, ] # ) db.session.commit() return
def setUp(self): app = create_app() self.app = app self.client = app.test_client() db.init_app(app) db.app = app with app.app_context(): db.drop_all() db.create_all()
def run(): app.host = '0.0.0.0' app.port = PORT app.debug = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Jackson/work/web/myblog/database/test.db' db.init_app(app) db.create_all() from livereload import Server server = Server(app) server.serve(port=PORT)
def client(): """Create flask test client""" instance = app.create_app() instance.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" instance.app_context().push() with instance.app_context(): db.create_all() yield instance.test_client() with instance.app_context(): db.drop_all()
def initialize_app(flask_app): setup_log() configure_app(flask_app) blueprint = Blueprint("api", __name__, url_prefix="/api") api.init_app(blueprint) api.namespaces = [] api.add_namespace(nqueen) flask_app.register_blueprint(web) flask_app.register_blueprint(blueprint) db.init_app(flask_app) with flask_app.app_context(): log.debug(f"Creating database: {settings.SQLALCHEMY_DATABASE_URI}") db.create_all(app=flask_app)
def create_app(cache): app = Flask(__name__, static_url_path='') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pong.db' cache.init_app(app) compress.init_app(app) Bootstrap(app) db.init_app(app) with app.app_context(): db.create_all() admin = Admin(app, name='pongr', template_mode='bootstrap3') admin.add_view(GameView(Game, db.session)) admin.add_view(DoublesView(DoublesGame, db.session)) admin.add_view(PlayerView(Player, db.session)) admin.add_view(RatingsView(Ratings, db.session)) return app, cache
def create_app(): app = Flask(__name__) app.config.from_object(config.DevelopmentConfig) from app.model import db db.init_app(app) from app.model import User, UserRoles, Author, Book, Role with app.app_context(): db.create_all() CORS(app) api = Api(app) create_routes(api) # user_manager = UserManager(app, db, User.UserModel) return app
def create_app(): """ :rtype: Flask """ app = Flask(__name__) # 读取配置文件 app.config.from_object('app.secure') # 注册蓝图 register_blueprint(app) # 初始化dao db.init_app(app) db.create_all(app=app) # 初始化flask_login插件 login.init_app(app) login.login_message = '请先注册或登录' login.login_view = 'web.login' # 初始化mail mail.init_app(app) return app
def setUp(self): """ Create test database and set up test client """ self.app = app.test_client() engine = create_engine(os.environ['TESTDB']) if not database_exists(engine.url): create_database(engine.url) # db.drop_all() db.create_all() db.session.commit() user1 = Users(username="******", password="******", email="*****@*****.**", fname="joshua", sname="joshua", lname="joshua", category=1) user2 = Users(username="******", password="******", email="*****@*****.**", fname="joshua2", sname="joshua2", lname="joshua2", category=2) user3 = Users(username="******", password="******", email="*****@*****.**", fname="joshua2", sname="joshua2", lname="joshua2", category=3) subject1 = Subjects(name="Artificial Intelligence", description="Computer Science AI, SC0AI", created_by=1) subject2 = Subjects(name="Human Psychology", description="Sociology, S0HP", created_by=1) userrights1 = UserRights(name="Admin") userrights2 = UserRights(name="Teacher") userrights3 = UserRights(name="Student") usersubject1 = UserSubject(user=2, subject=1) usersubject2 = UserSubject(user=3, subject=1) usersubject3 = UserSubject(user=3, subject=2) db.session.add(user1) db.session.add(user2) db.session.add(user3) db.session.add(subject1) db.session.add(subject2) db.session.add(userrights1) db.session.add(userrights2) db.session.add(userrights3) db.session.add(usersubject1) db.session.add(usersubject2) db.session.add(usersubject3) db.session.commit()
def create_app(config="app.config"): app = Flask(__name__) with app.app_context(): app.config.from_object(config) from app.model import Beautys, db if not database_exists( app.config['SQLALCHEMY_DATABASE_URI'] ) and not app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'): create_database(app.config['SQLALCHEMY_DATABASE_URI']) db.init_app(app) db.create_all() app.db = db from app.fanfan import fanfan app.register_blueprint(fanfan) return app
def create_app(): app = Flask(__name__) # 加载配置文件 app.config.from_object('app.config.secure') app.config.from_object('app.config.settings') # 加载插件 register_extensions(app) # 初始化数据库 db.init_app(app) db.create_all(app=app) # 注册api register_api(app) api = Api(app) # 注册命令 register_commands(app) # 解决跨域请求问题 CORS(app) return app
def ssh(): if request.method == "POST": if request.form.get('name') and \ request.form.get('host') and \ request.form.get('user') and \ request.form.get('pwd'): ssh = Ssh(request.form.get('name').strip(),\ request.form.get('host').strip(),\ request.form.get('user').strip(),\ request.form.get('pwd').strip() ) try: ssh.save() flash("SSH: %s added."% ssh.name, 'successfully') return redirect(url_for("admin.ssh")) except: db.create_all() flash("Add SSH: %s failed."% ssh.name, 'error') return redirect(url_for("admin.ssh")) else: sshs= Ssh.query.all() return render_template("ssh.html", sshs = sshs)
def index(): if request.method == "POST": # Add host if not request.form['host']: flash('Host is required', 'error') else: host = Host(request.form['host'].strip()) type = request.values['type'] hostname=host.hostname host.type = type # check unique try: if Host.query.filter_by(hostname=hostname).first(): flash("Host: %s has been registered before." % hostname) return redirect(url_for("index")) except: # create_all db.create_all() # check pingable if int(subprocess.call("ping -n 1 %s" % hostname)): flash("Host: %s is not pingable." % (hostname), 'error') return redirect(url_for("index")) # check system information host.save() flash("Host: %s added." % hostname, 'successfully') return redirect(url_for("index")) else: try: types = Type.query.all() rings = Ring.query.order_by(Ring.id.desc()).all() # availeble = [] # for ring in rings: # if ring.hosts[]: # print(ring.name) # availeble.append(ring) return render_template("index.html", types = types, rings = rings) except: db.create_all() return render_template("index.html", types = None, rings = None)
def initdb(): try: db.create_all() except: db.drop_all() db.create_all() # init some data try: # ring required unringed = Ring(name = "unringed") unringed.save() # data for simon wiki = Link("Team Wiki", "http://twiki.emccrdc.com/twiki/bin/view/ESD/Test/UsdEftTeam") wiki.save() report = Link("Weekly Report", 'http://report.emccrdc.com/mytimesheet.php?action=showts&reporter_id=177') report.save() myssh = Ssh("MyLinux", "10.109.17.204 ", "xinming", "111111") myssh.save() rayssh = Ssh("RayLinux", "10.32.191.173 ", "simon", "simon") rayssh.save() iohost = Type("IO HOST") iohost.save() spa = Type("SPA") spa.save() spb = Type("SPB") spb.save() vm = Type("VM") vm.save() host = Host("localhost") host.ring_id = unringed.id host.type = spa.name host.save() flash("Init database successfully.", 'successfully') except Exception as e: flash("Init database failed. %s" % e, 'error') return redirect(url_for("admin.index"))
def initdb(): print('were') db.drop_all() db.create_all()
def setUp(self): db.drop_all() db.create_all() create_user(self.username, self.password)
def setUp(self): # Product.init_db(app) db.drop_all() # clean up the last tests db.create_all() # make our sqlalchemy tables
#!/usr/bin/env python from app import app import os if __name__ == '__main__': import os from app.model import db db.create_all() port = int(os.environ.get('PORT', 33507)) app.run(host='0.0.0.0', port=port, use_reloader=True)
def on_status(self, status): # Exclude retweets and Tweets w/o geotag if ('RT @' not in status.text) and (status.place != None) and ( status.place.country_code == 'US'): # Choose only geotagged tweets in Frederick County, MD longitude = sum( [pair[0] for pair in status.place.bounding_box.coordinates[0]]) / 4 latitude = sum( [pair[1] for pair in status.place.bounding_box.coordinates[0]]) / 4 #Frederick County, MD bounding box bounding_box = dict(upper_right_latitude=39.7366, upper_right_longitude=-77.0961, lower_left_latitude=39.2133, lower_left_longitude=-77.6713) #Locating within Frederick County, MD bounding box if ((longitude >= bounding_box['lower_left_longitude']) and (longitude <= bounding_box['upper_right_longitude']) and (latitude >= bounding_box['lower_left_latitude']) and (latitude <= bounding_box['upper_right_latitude'])): #Try to write tweet information to db try: try: tweet = Tweets( id=status.id, tweet=status.extended_tweet['full_text'], username=status.user.screen_name, realname=status.user.name, timestamp=status.created_at, longitude=sum([ pair[0] for pair in status.place.bounding_box.coordinates[0] ]) / 4, latitude=sum([ pair[1] for pair in status.place.bounding_box.coordinates[0] ]) / 4) with app.app_context(): db.create_all() db.session.add(tweet) db.session.commit() print(status.extended_tweet['full_text'], status.user.location, status.place.name) except AttributeError as e: tweet = Tweets( id=status.id, tweet=status.text, username=status.user.screen_name, realname=status.user.name, timestamp=status.created_at, longitude=sum([ pair[0] for pair in status.place.bounding_box.coordinates[0] ]) / 4, latitude=sum([ pair[1] for pair in status.place.bounding_box.coordinates[0] ]) / 4) with app.app_context(): db.create_all() db.session.add(tweet) db.session.commit() print(status.text, status.user.location, status.place.name) #if error occurs except Exception as e: print(e) db.session.rollback() pass
def create_db(): # 创建数据库 db.create_all() return '创建成功'
def create_data(): db.create_all() return "sqlite create database OK"
from app.controller import app from app.model import db if __name__ == '__main__': #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) db.create_all(app=app) app.run()
def resetdatabase(): # 重置数据库 db.drop_all(app=app) db.create_all(app=app) click.echo('Reset database, successful.')
def setUp(self): Shopcart.init_db() db.drop_all() # clean up the last tests db.create_all() # make our sqlalchemy tables
def create_db(): # 创建db db.create_all()
def create_db(): # 用于初次创建模型 db.create_all() return '创建成功'
def create_db(): db.create_all()
def init_db(): db.create_all()