Exemplo n.º 1
0
def admin_install(user):
    db.drop_all()
    db.create_all()

    create_test_data()

    return redirect("/admin", code=302)
Exemplo n.º 2
0
def create_app(config_file):
    # load config
    app.config.from_pyfile(config_file)

    from views.backgrounds import load_backgrounds
    load_backgrounds(app)

    # setup db
    from database import db
    db.init_app(app)

    # setup login
    login_manager.init_app(app)

    # login_manager.setup_app(app)

    from monkey.views import index_view, login_view

    for bp in [login_view, index_view]:
        app.register_blueprint(bp)

    # init all
    with app.app_context():
        db.create_all()
        import api

        api.start_api([UserModel])
        UserModel.initialize()

    return app
Exemplo n.º 3
0
def create_app(app):
    # config app
    app.config.from_object(os.environ["APP_SETTINGS"])

    # initiate extensions
    db.init_app(app)
    ma.init_app(app)
    celery.init_app(app)
    jack_apns.init_app(app)

    # declare models
    import models

    # init app
    with app.app_context():
        # db.reflect()
        # db.drop_all()
        db.create_all()
        app.register_blueprint(auth, url_prefix="/auth")
        app.register_blueprint(user, url_prefix="/user")
        app.register_blueprint(group, url_prefix="/group")
        app.register_blueprint(post, url_prefix="/post")
        app.register_blueprint(comment, url_prefix="/comment")
        app.register_blueprint(invite, url_prefix="/invite")
        app.register_blueprint(generic, url_prefix="/generic")
        app.register_blueprint(rule, url_prefix="/rule")
Exemplo n.º 4
0
def setup_db():
    with app.app_context():
    # print app
        db.drop_all()
        db.create_all()
        db.session.commit()
    print "database is set up!"
Exemplo n.º 5
0
 def setUp(self):
     # Change the database to a test one in memory and
     # create all our tables there
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
     with app.app_context():
         db.create_all()
     self.app = app.test_client()
Exemplo n.º 6
0
def create_app(debug=False):
    def load_env(env_name, conf_name = None):
        """Load the specified key to config from env if exists"""
        if conf_name is None:
            conf_name = env_name
        
        app.config[conf_name] = os.environ.get(env_name, app.config.get(conf_name))


    app = Flask(__name__)
    app.debug = debug

    app.config.from_object(os.environ.get('APP_CONFIG', 'config.DevelopmentConfig'))

    load_env('DATABASE_URL', 'SQLALCHEMY_DATABASE_URI')
    load_env('GCM_TOKEN')

    app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

    # Database creation
    db.init_app(app)
    with app.app_context():
        db.create_all()

    #
    # Create the services
    #
    gcm = GCM(app.config['GCM_TOKEN'])
    authService = AuthenticationService(db)
    messageService = GCMMessengerService(db, gcm)
    locatorService = LocatorService(db, messageService)
    relayService = RelayService(db, messageService)

    # Easy method to get currentuser
    def current_user():
        token = request.headers.get('Authorization')
        return authService.getUserFromAccessToken(token)

    #
    # Blueprints
    # 
    authcheckBlueprint = authcheck_blueprint(authService, locatorService)
    locatorBlueprint = locator_blueprint(db, locatorService, current_user)
    relayBlueprint = relay_blueprint(db, relayService, current_user)
    refBlueprint = refactor_blueprint(db, authService, app, current_user) # Needs app for now as it has the apimanager...
    app.register_blueprint(locatorBlueprint)
    app.register_blueprint(relayBlueprint)
    app.register_blueprint(authcheckBlueprint)
    app.register_blueprint(refBlueprint)
    
    # Create admin interface
    admin.init_app(app, messageService, locatorService)

    # I'm a teapot.
    @app.route("/")
    def index():
        abort(418)

    return app
Exemplo n.º 7
0
def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/user_management.db'
	db.init_app(app)
	db.app = app
	from models import User, Group
	db.create_all()
	migrate.init_app(app,db)
	return app
Exemplo n.º 8
0
    def setUp(self):
        app.config.from_object('config.TestingConfig')
        self.client = app.test_client()

        db.init_app(app)
        with app.app_context():
            db.create_all()
            user_datastore.create_user(email='test', password=encrypt_password('test'))
            db.session.commit()
Exemplo n.º 9
0
 def setUp(self):
   if not main.app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite://'):
     raise RuntimeError('Test against sqlite DB! not %r'
                        % main.app.config['SQLALCHEMY_DATABASE_URI'])
   main.app.config['TESTING'] = True
   main.app.debug = True
   main.app.test_request_context().push()
   db.drop_all()
   db.create_all()
Exemplo n.º 10
0
def test_db(flask_app):
    uuid = str(uuid4())
    flask_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test-{}.db'.format(uuid)

    db.init_app(flask_app)
    with flask_app.app_context():
        db.create_all()

    return db
Exemplo n.º 11
0
def setup_database(app):
    with app.app_context():
        db.create_all()
    home = Page()
    home.name = "Home"
    contact = Page()
    contact.name = Page()
    db.session.add(home)
    db.session.add(contact)
    db.session.commit()   
Exemplo n.º 12
0
def create_db():
    import os
    if os.path.exists(DB_PATH):
        return
    
    db.create_all()

    roles = [u'user', u'operator', u'administrator']
    subjects = [u'Programming']
    categories = [
        u'ASP.NET',
        u'Assembler',
        u'C',
        u'C#',
        u'C++',
        u'Delphi | Pascal',
        u'Java',
        u'HTML | CSS | JavaScript',
        u'Oracle',
        u'Python',
        u'QT',
        u'SQL | MySQL | MS SQL | PL/SQL',
        u'Visual Basic',
        u'Other'
    ]
    os_list = [u'Windows', u'Unix-like']

    task_statuses = [
        ('New', 'Client submitted the new task and operator hasn\'t got it yet'),
        ('Discussion', 'Operator discussing details with Client'),
        ('Solving', 'Task went off to solving'),
        ('Pending', 'Payment is going to be delivered soon by PayPal'),
        ('Done', 'User received solution'),
    ]

    for r in roles:
        db.session.add(Role(r))
    db.session.commit()

    for s in subjects:
        db.session.add(Subject(s))
    db.session.commit()

    s = Subject.query.filter_by(name=u'Programming').first()

    for c in categories:
        db.session.add(Category(name=c, subject_id=s.id))

    for o in os_list:
        db.session.add(OS(n=o))

    for ts in task_statuses:
        db.session.add(TaskStatus(*ts))

    db.session.commit()
Exemplo n.º 13
0
	def setUp(self):
		db.create_all()
		man1 = Manufacturer('chrysler', 3, 32971.67, 'town-and-country', 291.33)
		db.session.add(man1)
		man2 = Manufacturer('buick', 3, 31050.0, 'cascada', 236.33)
		db.session.add(man2)
		man3 = Manufacturer('kia', 9, 28725.56, 'k900', 216.11)
		db.session.add(man3)
		man4 = Manufacturer('lexus', 25, 52488.2, 'ls-600h-l', 290.32)
		db.session.add(man4)
		db.session.commit()
Exemplo n.º 14
0
	def setUp(self):
		db.create_all()
		engine1 = Engine('3.5 V6', 6, 'premium unleaded (recommended)', 279, 252)
		db.session.add(engine1)
		engine2 = Engine('Engine', 4, 'regular unleaded', 200, 206)
		db.session.add(engine2)
		engine3 = Engine('Engine', 4, 'premium unleaded (required)', 237, 258)
		db.session.add(engine3)
		engine4 = Engine('Hybrid', 6, 'premium unleaded (recommended)', 377, 341)
		db.session.add(engine4)
		db.session.commit()
Exemplo n.º 15
0
	def setUp(self):
		db.create_all()
		car1 = Car('acura', 'ilx', 2016, 31890.0, 201)
		db.session.add(car1)
		car2 = Car('toyota', 'tundra', 2015, 46530.0, 381)
		db.session.add(car2)
		car3 = Car('ford', 'fusion', 2017, 33360.0, 325)
		db.session.add(car3)
		car4 = Car('acura', 'rdx', 2016, 40370.0, 279)
		db.session.add(car4)
		db.session.commit()
Exemplo n.º 16
0
def create_app(config):
    """
    Given a configuration object, create a WSGI(Flask) app
    See `APP_CONFIG` in ../config.py for example configuration.
    """
    app = Flask(__name__)
    app.config.update(config)
    register_blueprints(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Exemplo n.º 17
0
def initialize_database():
    """
    Initialisiere die Datenbank mit Testdaten. Alle vorhandenen Daten werden geluescht.
    """
    stations = (("Oper", "Operngasse 1", "1010", "Wien", u"Österreich"),
                 ("Hohe Warte Stadium", "Heiligenstadt", "1190", "Wien", u"Österreich"),
                 ("Fliegerhorst Brumowski", "Brumowskigasse 23", "3425", "Tulln an der Donau", u"Österreich"),
                 ("FH Technikum Wien", "Höchstädtplatz 6", "1200", "Wien", u"Österreich"),
                 ("Red Bull Ring", u"Schloßweg 1", "8724", "Spielberg", u"Österreich"))
    cars = (("Citroen", u"C3", "silber", 5, 4.8, 50, "W-997G"),
             ("Ford", u"Focus", "rot", 5, 5.9, 70, "W-997GH"),
             ("Smart", u"ForTwo", "gelb", 2, 3.5, 70, "W-997GI"),
             ("VW", u"Käfer", "Rost", 4, 6.8, 40, "W 992223" ),
             ("Renault", "Grand Espace", "schwarz", 7, 8.8, 120, "K 009DF"),
             ("McLaren", "P1", "gelb", 2, 12.3, 190, "S 99823"))
    kunden = (("Alice Amber", "Nussdorfer Strasse 77", "1090", "Wien", u"Österreich"),
              ("Bob Builder", "Lederwaschstrasse 2", "5589", "Tamsweg", u"Österreich"),
              ("Istvan Nagy", "Halasz utca 25", "9400", "Sopron", u"Ungarn"),
              ("Ignaz Zurbgriggen", "Wildbachstrasse 9", "8340", "Hinwil", u"Schweiz"),
              ("Charly Custer", "Albrechtgasse 530", "3571", "Gars am Kamp", u"Österreich"),
              ("Eve Easter", "Kardinal Piffl Platz 2", "3400", "Klosterneuburg", u"Österreich"))

    db.drop_all()
    db.create_all()

    for c in cars:
        d = dict(zip( ('manufacturer', 'typ', 'color', 'seats', 'consumption', 'price', 'platenumber'), c))
        db.session.add(Car(**d))

    for s in stations:
        d = dict(zip( ('name', 'street', 'plz', 'city', 'country'), s))
        db.session.add(Station(**d))

    for k in kunden:
        d = dict(zip( ('name', 'street', 'plz', 'city', 'country'), k))
        db.session.add(Kunde(**d))

    db.session.flush()
    c3, focus, fortwo, kaefer, espace, p1 = Car.query.all()
    oper, hohewarte, lale, fh, rbr = Station.query.all()
    alice, bob, istvan, ignaz, charly, eve = Kunde.query.all()

    c3.station = hohewarte
    focus.station = lale
    espace.station = hohewarte

    Leihe(kunde=alice, car=c3, von=parsedate('2014-02-01 14:00'), bis=parsedate('2014-02-10 10:00'), returned=True, station_abhol=hohewarte, station_return=hohewarte)
    Leihe(kunde=alice, car=c3, von=parsedate('2014-02-14 08:00'), bis=parsedate('2014-02-15 22:00'), returned=True, station_abhol=hohewarte, station_return=lale)
    Leihe(kunde=ignaz, car=c3, von=datetime.today() - timedelta(days=2), bis=datetime.today() + timedelta(days=5), returned=False, station_abhol=hohewarte, station_return=rbr)
    Leihe(kunde=istvan, car=p1, von=parsedate('2014-01-14 09:00'), bis=datetime.today() + timedelta(days=2), returned=False, station_abhol=lale, station_return=fh)
    Leihe(kunde=charly, car=p1, von=datetime.today() + timedelta(days=10), bis=datetime.today() + timedelta(days=12), returned=False, station_abhol=lale, station_return=fh)

    db.session.commit()
Exemplo n.º 18
0
def main(run_folders, users_file):
    db.init_app(app)
    logging.basicConfig(filename = 'NIPT_database_log', level=logging.DEBUG)
    db.create_all()
    NDBS = NiptDBSetup(db)
    NDBS.set_users(users_file)

    for folder in run_folders:
        BM = BatchMaker(db)
        BM.get_run_folder_info(folder)
        if BM.batch_id:
            BM.update_nipt_db(folder)
        else:
            logging.warning("Could not add to database from resultfile: %s" % path)
Exemplo n.º 19
0
def configure_app(app, workdir):
    import os.path
    workdir = os.path.abspath(workdir)

    app.config['OSMPOINT_ADMINS'] = []
    app.config['IMPORTED_POINTS_PATH'] = None

    config_file = os.path.join(workdir, 'config.py')
    app.config.from_pyfile(config_file, silent=False)

    app.config['IMPORTED_POINTS'] = load_imported_points(
        app.config['IMPORTED_POINTS_PATH'])

    with app.test_request_context():
        db.create_all()
Exemplo n.º 20
0
def main(flowcell_ids, users_file):
    db.init_app(app)
    logging.basicConfig(filename = 'NIPT_database_log', level=logging.DEBUG)
    db.create_all()
    NDBS = NiptDBSetup(db)
    NDBS.set_users(users_file)

    for flowcell_id in flowcell_ids:
        BM = BatchMaker(db)
        BM.parse_path(flowcell_id)
        BM.get_run_folder_info()
        if BM.batch_id:
            BM.update_nipt_db()
        else:
            logging.warning("Could not add to database from run: %s" % flowcell_id)
Exemplo n.º 21
0
def build_db(app):
	with app.app_context():
		print("dropping...")
		db.drop_all()
		print("creating structure...")
		db.create_all()

	if prompt_bool("Populate from 'rare pepes (tm)' album"):
		if not client:
			raise RuntimeError("no imgur credentials found")
		for album in ["U2dTR"]:
			for img in client.get_album_images(album):
				add_from_img(img, origin="1270 rare pepes (U2dTR)")
				#sleep(1)
	db.session.commit()
Exemplo n.º 22
0
def check():
	#database stuff
	db.create_all()

	ans = request.form
	ans_graded = []
	for item in ans:
		if item == ans[item]:
			modifyDatabase(item, True)
			ans_graded.append(True)
		else:
			modifyDatabase(item, False)
			ans_graded.append(False)

	return jsonify(answers = ans_graded)
Exemplo n.º 23
0
  def setUp(self):
    app.config.from_object('config.DevelopmentConfig')
    app.config['TESTING'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///contacts_test'
    app.config['WTF_CSRF_ENABLED'] = False
    self.app = app.test_client()
    with app.app_context():
      db.create_all()

    self.data = {
      'first_name': "first_name",
      "last_name": "last_name",
      "phone_number": "1111111111",
      "email": "*****@*****.**",
      "birthdate": str(int(time.mktime(datetime.date.today().timetuple()) * 1000))
    }
Exemplo n.º 24
0
def create_app():
    from views import auth, main

    app = Flask(__name__, template_folder='templates')
    app.config.from_object(config)

    # Blueprints:
    app.register_blueprint(auth)
    app.register_blueprint(main)

    # Custom modules:
    login_manager.init_app(app)
    # login_manager.login_view = 'auth.login'

    db.init_app(app)
    # Dynamic context:
    with app.app_context():
        db.create_all()
    return app
Exemplo n.º 25
0
    def __init__(self, name, config=None, reinit_db=False):
        if not config:
            config = {"SQLALCHEMY_DATABASE_URI": "sqlite:///platformer_node_{}.db".format(name)}
        self.app = flask.Flask(__name__)
        self.app.config.update(config)
        db.init_app(self.app)
        with self.app.app_context():
            if reinit_db:
                db.drop_all()
            db.create_all()

        manager = flask.ext.restless.APIManager(self.app, flask_sqlalchemy_db=db)
        manager.create_api(Peer, url_prefix="", methods=["GET", "POST", "PUT", "DELETE"], include_columns=["url"])
        manager.create_api(Secret, url_prefix="", methods=["POST"])

        # Note that route definitions have to go here, because the app is not global.
        @self.app.route("/", methods=["HEAD"])
        def pong():
            return ""
Exemplo n.º 26
0
    def setUp(self):
        # Change the database to a test one in memory and
        # create all our tables there
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        app.config['UPLOAD_LOCATION'] = os.path.join(HERE, 'test_uploads')
        with app.app_context():
            db.create_all()
        self.app = app.test_client()

        # Create a test user
        self.app.post("/user", data={'username': '******',
                                     'password': '******',
                                     'email': '*****@*****.**'})

        with open(os.path.join('test_data', 'test.mp3'), 'rb') as f:
            self.mp3_file = f.read()

        with open(os.path.join('test_data', 'test.txt'), 'rb') as f:
            self.text_file = f.read()
Exemplo n.º 27
0
def setup():
    if not config.get('setup', bool):
        abort(404)

    if request.method == 'POST':
        if not check_keys():
            flash(error_message)
            return render_template('setup.html')

        username = request.form['username']
        password = request.form['password_1']
        email = request.form['email']
        db_uri = request.form['database_uri']

        # create database
        config.set('database_uri', db_uri)
        app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
        db.drop_all()
        db.create_all()

        # create admin user
        admin = NewUser(username, password, email)
        admin.admin = True
        admin.active = True
        admin.create()

        # generate secret key
        secret_key = os.urandom(24)
        config.set('secret_key', secret_key)
        app.config['SECRET_KEY'] = secret_key

        # set a default upload directory
        blackboard_root = os.path.dirname(os.path.abspath(__file__))
        config.set('upload_destination', blackboard_root + '/static/upload')

        # disable setup
        config.set('setup', 'False')

        flash(messages.setup_finished, 'message')
        return redirect(url_for('login'))    

    else:
        return render_template('setup.html')
Exemplo n.º 28
0
def create_database():
	db.create_all()

	'''car_json = json.load(open('cars_list.json'))
	create_cars(car_json)

	manufacturer_json = json.load(open('makes_list.json'))
	create_manufacturers(manufacturer_json)'''

	with open('cars_list.json') as car_json:
		car_data = json.load(car_json)
		create_cars(car_data)

	with open('makes_list.json') as manufacurer_json:
		manufacturer_data = json.load(manufacturer_json)
		create_manufacturers(manufacturer_data)	

	with open('engines_list.json') as engine_json:
		engine_data = json.load(engine_json)
		create_engines(engine_data)	
Exemplo n.º 29
0
def setup_flask(drop_all=False):
    '''
    initialize top level objects
    give orm and router accesss flash
    returns app and api to simplify
    usining this independently of the full app
    '''
    # TODO error handling
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
    db.init_app(app)
    with app.app_context():
        # Extensions like Flask-SQLAlchemy now know what the "current" app
        # is while within this block. Therefore, you can now run........
        if drop_all:
            db.drop_all()
        db.create_all()
    api = Api(app, catch_all_404s=True)
    build_endpoints(api)
    return app, api
Exemplo n.º 30
0
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            app = Flask(__name__)

            app.register_blueprint(PeopleBluePrintFactory.create())

            flask_injector = FlaskInjector(
                app=app,
                modules=[DatabaseModule(), ],
            )

            app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
            app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/production.db'

            db.init_app(app)
            with app.app_context():
                db.create_all()

            cls._instance = flask_injector

        return cls._instance
Exemplo n.º 31
0
def init_db(database_path):
    if not os.path.exists(database_path):
        db.create_all()
        populateEmployeeTable()
        populateEmployeeLeaveTable()
Exemplo n.º 32
0
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import json
from controllers import mainControllers
from database import db
from models import Organization

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///static/db/ey.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
CORS(app)
db.init_app(app)
# db.drop_all(app=app)
db.create_all(app=app)
api = Api(app)

api.add_resource(mainControllers.OrganizationList, '/orgs')
api.add_resource(mainControllers.OrganizationController, '/orgs/<org_id>')

api.add_resource(mainControllers.NewsController, '/news/<news_keyword>')


def populate_db():
    with app.app_context():
        o = Organization('Testing', '555-512-1234')
        db.session.add(Organization('Real Estate', '555-555-5555'))
        db.session.add(Organization('Insurance', '555-555-5556'))
        db.session.add(Organization('Private Equity', '555-555-5557'))
        db.session.commit()
Exemplo n.º 33
0
 def setUp(self):
     db.create_all()
Exemplo n.º 34
0
                d.session.add(db_game)
            db_steamgame = database.SteamGame(game=db_game,
                                              steam_app_id=game["appid"],
                                              steam_app_name=game["name"])
            d.session.add(db_steamgame)
        copy = d.session.query(database.SteamGame) \
            .filter_by(steam_app_id=game["appid"]) \
            .join(database.Game) \
            .join(database.Copy) \
            .filter_by(owner_id=user["id"]) \
            .first()
        if copy is not None:
            continue
        print(game["name"])
        if game["playtime_forever"] > 0:
            play_status = None
        else:
            play_status = database.GameProgress.NOT_STARTED
        d.session.flush()
        copy = database.Copy(owner_id=user["id"],
                             game_id=db_steamgame.game_id,
                             progress=play_status)
        d.session.add(copy)
    d.session.commit()
    return f.redirect(f.session.get("openid_redirect_to"))


if __name__ == "__main__":
    d.create_all(app=app)
    app.run()
Exemplo n.º 35
0
 def setUp(self):
     create_test_app()
     db.create_all()
Exemplo n.º 36
0
def create_db():
    db.create_all()
Exemplo n.º 37
0
def create_database():
    from database import db

    db.create_all()
Exemplo n.º 38
0
def init_db(app):
    with app.app_context():
        db.create_all()
    print 'created tables'
Exemplo n.º 39
0
def index():
    db.create_all()
    return 'Hello World'
Exemplo n.º 40
0
def create_db():
    """Create database migrations and upgrade it"""
    db.create_all()
Exemplo n.º 41
0
api_instance.add_namespace(endpoint_api, path='/endpoint')
api_instance.init_app(app)  # Initialize the api

TaskBase = celery.Task  # Fiddle with celery because Flask needs to be able to work with celery, and without this bit celery doesn't have the correct app context.


class ContextTask(TaskBase):
    abstract = True

    def __call__(self, *args, **kwargs):
        with app.app_context():
            return TaskBase.__call__(self, *args, **kwargs)


celery.Task = ContextTask

# Set up database
db.init_app(app)  # Initialize the database with the app
print("Resetting the database")
db.drop_all(
    app=app)  # Drop the table here, so we have a fresh start every time.
db.create_all(
    app=app
)  # If the database table doesn't already exist, then create it here.

# Setup cache
cache.init_app(app)

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True, port=80)
Exemplo n.º 42
0
def create():
    db.create_all()
Exemplo n.º 43
0
def create_db(app):
    with app.app_context():
        db.create_all()
Exemplo n.º 44
0
def init_db(flask_app):
    db.init_app(flask_app)
    db.create_all()
Exemplo n.º 45
0
def create_db():
    """Creates database"""
    db.create_all()
Exemplo n.º 46
0
def basic_auto_migrate_relational_db(app, bind):
    """Inspired with http://stackoverflow.com/questions/2103274/"""

    from sqlalchemy import Table
    from sqlalchemy import MetaData

    print('Performing very simple automigration in', bind, 'database...')
    db.session.commit()
    db.reflect()
    db.session.commit()
    db.create_all(bind=bind)

    with app.app_context():
        engine = db.get_engine(app, bind)
        tables = db.get_tables_for_bind(bind=bind)
        metadata = MetaData()
        metadata.engine = engine

        ddl = engine.dialect.ddl_compiler(engine.dialect, None)

        for table in tables:

            db_table = Table(table.name,
                             metadata,
                             autoload=True,
                             autoload_with=engine)
            db_columns = get_column_names(db_table)

            columns = get_column_names(table)
            new_columns = columns - db_columns
            unused_columns = db_columns - columns
            existing_columns = columns.intersection(db_columns)

            for column_name in new_columns:
                column = getattr(table.c, column_name)
                if column.constraints:
                    print('Column %s skipped due to existing constraints.' %
                          column_name)
                    continue
                print('Creating column: %s' % column_name)

                definition = ddl.get_column_specification(column)
                add_column(engine, table.name, definition)

            if engine.dialect.name == 'mysql':
                sql = 'SHOW CREATE TABLE `%s`' % table.name
                table_definition = engine.execute(sql)
                columns_definitions = {}

                to_replace = {
                    'TINYINT(1)':
                    'BOOL',  # synonymous for MySQL and SQLAlchemy
                    'INT(11)': 'INTEGER',
                    'DOUBLE': 'FLOAT(53)',
                    ' DEFAULT NULL': ''
                }
                for definition in table_definition.first()[1].split('\n'):
                    match = re.match(
                        '\s*`(?P<name>.*?)` (?P<definition>[^,]*),?',
                        definition)
                    if match:
                        name = match.group('name')
                        definition_string = match.group('definition').upper()

                        for mysql_explicit_definition, implicit_sqlalchemy in to_replace.items(
                        ):
                            definition_string = definition_string.replace(
                                mysql_explicit_definition, implicit_sqlalchemy)

                        columns_definitions[
                            name] = name + ' ' + definition_string

                columns_to_update = []
                for column_name in existing_columns:

                    column = getattr(table.c, column_name)
                    old_definition = columns_definitions[column_name]
                    new_definition = ddl.get_column_specification(column)

                    if old_definition != new_definition:
                        columns_to_update.append(
                            [column_name, old_definition, new_definition])

                if columns_to_update:
                    print(
                        '\nFollowing columns in `%s` table differ in definitions '
                        'from those in specified in models:' % table.name)
                for column, old_definition, new_definition in columns_to_update:
                    answer = get_answer(
                        'Column: `%s`\n'
                        'Old definition: %s\n'
                        'New definition: %s\n'
                        'Update column definition?' %
                        (column, old_definition, new_definition))
                    if answer == 'y':
                        update_column(engine, table.name, new_definition)
                        print('Updated %s column definition' % column)
                    else:
                        print('Skipped %s column' % column)

            if unused_columns:
                print('\nFollowing columns in `%s` table are no longer used '
                      'and can be safely removed:' % table.name)
                for column in unused_columns:
                    answer = get_answer('Column: `%s` - remove?' % column)
                    if answer == 'y':
                        drop_column(engine, table.name, column)
                        print('Removed column %s.' % column)
                    else:
                        print('Keeping column %s.' % column)

    print('Automigration of', bind, 'database completed.')
Exemplo n.º 47
0
def db(app):
    _db.create_all()

    yield _db

    _db.drop_all()
Exemplo n.º 48
0
def db(request, app):
    app.config['SQLALCHEMY_DATABASE_URI'] = TEST_DB

    test_db.init_app(app)
    test_db.create_all()
    yield test_db
Exemplo n.º 49
0
def init_db():
    ''' Initialize the database '''
    with app.test_request_context():
        db.create_all()
Exemplo n.º 50
0
def _preload():
    db.create_all()
    roles = _role_preload()
    _user_preload(roles)
Exemplo n.º 51
0
def create_tables():
    db.create_all()
Exemplo n.º 52
0
def init_db():
    db.init_app(app)
    db.app = app
    db.create_all()
Exemplo n.º 53
0
    """

    for _, name, _ in pkgutil.iter_modules(package_path):
        import_string = '%s.%s' % (package_name,
                                   name) if package_name else name
        m = pkgutil.importlib.import_module(import_string)
        for item in dir(m):
            item = getattr(m, item)
            if isinstance(item, Blueprint):
                app.register_blueprint(item)


register_blueprints("modules", ["modules"])


@app.route("/")
def home():
    return jsonify({"test": "home"})


if __name__ == "__main__":
    import sys

    if len(sys.argv) == 2 and sys.argv[1] == "create":
        from database import db
        from models import *
        db.create_all()
    else:
        manager.run()
        # app.run(debug=True, port=5000, host='0.0.0.0')
Exemplo n.º 54
0
def setup_database(app):
    with app.app_context():
        db.create_all()
Exemplo n.º 55
0
 def setUp(self):
     self.logged_user = None
     self.add_csrf_to_default_post()
     db.create_all()
Exemplo n.º 56
0
 def setUp(self):
     db.create_all()
     db.session.commit()
Exemplo n.º 57
0
def create_tables():
    db.create_all(
    )  #when this runs, it'll create data.db and all the tables in the file unless they exist already
Exemplo n.º 58
0
from flask import Flask
from flask import render_template
from flask import request  # Flask is the web app that we will customize
from flask import redirect, url_for
from database import db
from models import Note as Note
from models import User as User

app = Flask(__name__)  # create an app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flask_note_app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#  Bind SQLAlchemy db object to this Flask app
db.init_app(app)
# Setup models
with app.app_context():
    db.create_all()  # run under the app context


# @app.route is a decorator. It gives the function "index" special powers.
# In this case it makes it so anyone going to "your-url/" makes this function
# get called. What it returns is what is shown as the web page
@app.route('/')
@app.route('/index')
def index():
    a_user = db.session.query(User).filter_by(email='*****@*****.**').one()

    return render_template('index.html', user=a_user)


@app.route('/notes')
def get_notes():
Exemplo n.º 59
0
def create_tables():
    db.create_all()
    from models.user import UserModel
    user = UserModel('flask', 'flask')
    user.save_to_db()
Exemplo n.º 60
0
# 2. SETTING UP FLASK DATABASE

from database import db, Puppy

db.create_all() # Transforms the Model class to the database table

sam = Puppy('Sam', 3) # Creating database entries
frank = Puppy('Frankie', 1)

# This will report back "None", since we haven't added these into our database yet
print(sam.id)
print(frank.id)

db.session.add_all([sam, frank])

db.session.commit() # commit the changes in the database

print(frank.id)
print(sam.id)