def create_db_and_default_roles():
"""Create the database and the default roles.
This is the command you run when you've deployed
for the first time.
Warning:
This is different from `flask db init`,
which is a Flask-Migrate command.
"""
db.create_all()
if not Role.query.first():
# Create the roles and two test users
user_datastore.create_role(name='free')
user_datastore.create_role(name='university')
user_datastore.create_role(name='publisher')
db.session.commit()
print("Database created and default roles added.")
else:
print("Roles already exist!")
python类Migrate()的实例源码
def init_db(app):
db.init_app(app)
from .models import BaseModel
migrate = Migrate(
app, db,
directory=os.path.join(SRC_ROOT, 'migrations')
)
@app.before_first_request
def setup_database(*args, **kwargs):
db_data_seed()
@app.teardown_request
def teardown_request(exception):
if exception:
db.session.rollback()
db.session.remove()
db.session.remove()
return db
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
Bootstrap(app)
db.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login"
migrate = Migrate(app, db)
from app import models
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
return app
def migrate():
#query.drop_table('alembic_version')
query.create_database(config.database_name)
migrate = Migrate(app, db)
return migrate
def migrate():
#query.drop_table('alembic_version')
query.create_database(database_name)
migrate = Migrate(app, db)
return migrate
def migrate():
#query.drop_table('alembic_version')
query.create_database(config.database_name)
migrate = Migrate(app, db)
return migrate
def __init__(self, master, app, db):
super().__init__(master, app, db)
self.migrate = flask_migrate.Migrate(self.app, self.db)
def configure_db(app):
"""
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revision which contains the latest state of the database prior to this.
"""
db.init_app(app)
log = logging.getLogger(app.logger_name)
if app.config.get('ARA_AUTOCREATE_DATABASE'):
with app.app_context():
migrations = app.config['DB_MIGRATIONS']
flask_migrate.Migrate(app, db, directory=migrations)
config = app.extensions['migrate'].migrate.get_config(migrations)
# Verify if the database tables have been created at all
inspector = Inspector.from_engine(db.engine)
if len(inspector.get_table_names()) == 0:
log.info('Initializing new DB from scratch')
flask_migrate.upgrade(directory=migrations)
# Get current alembic head revision
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# Get current revision, if available
connection = db.engine.connect()
context = MigrationContext.configure(connection)
current = context.get_current_revision()
if not current:
log.info('Unstable DB schema, stamping original revision')
flask_migrate.stamp(directory=migrations,
revision='da9459a1f71c')
if head != current:
log.info('DB schema out of date, upgrading')
flask_migrate.upgrade(directory=migrations)
def configure_db(app):
"""
0.10 is the first version of ARA that ships with a stable database schema.
We can identify a database that originates from before this by checking if
there is an alembic revision available.
If there is no alembic revision available, assume we are running the first
revision which contains the latest state of the database prior to this.
"""
db.init_app(app)
log = logging.getLogger(app.logger_name)
if app.config.get('ARA_AUTOCREATE_DATABASE'):
with app.app_context():
migrations = app.config['DB_MIGRATIONS']
flask_migrate.Migrate(app, db, directory=migrations)
config = app.extensions['migrate'].migrate.get_config(migrations)
# Verify if the database tables have been created at all
inspector = Inspector.from_engine(db.engine)
if len(inspector.get_table_names()) == 0:
log.info('Initializing new DB from scratch')
flask_migrate.upgrade(directory=migrations)
# Get current alembic head revision
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# Get current revision, if available
connection = db.engine.connect()
context = MigrationContext.configure(connection)
current = context.get_current_revision()
if not current:
log.info('Unstable DB schema, stamping original revision')
flask_migrate.stamp(directory=migrations,
revision='da9459a1f71c')
if head != current:
log.info('DB schema out of date, upgrading')
flask_migrate.upgrade(directory=migrations)
def register(self):
"""
Register the service provider
"""
# Enabled?
if not self.app.config('app.database.enabled', False):
return
# Load instances (which binds sql-alchemy)
self.app.extensions['edmunds.database'].get(no_instance_error=True)
# Assign to extensions
migrate = Migrate(self.app, DatabaseManager.get_sql_alchemy_instance())
self.app.extensions['edmunds.database.migrate'] = migrate
def create_application():
sentry = Sentry()
app = Flask(__name__)
app.config.from_object('config.Blacklist')
migrate = Migrate(app, db)
babel = Babel(app)
# sentry = Sentry(app)
# Convert decimals to floats in JSON
def url_for_other_page(page):
args = request.view_args.copy()
args['page'] = page
return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
class APIoTJSONEncoder(flask.json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
# Convert decimal instances to float.
return float(obj)
return super(APIoTJSONEncoder, self).default(obj)
app.json_encoder = APIoTJSONEncoder
db.init_app(app)
sentry.init_app(app)
app.sentry = sentry
app.register_blueprint(home)
app.register_blueprint(api, url_prefix='/api')
app.register_blueprint(user, url_prefix='/user')
app.register_blueprint(blacklist, url_prefix='/blacklist')
app.register_blueprint(crawl, url_prefix='/crawl')
return app
def create_app(config_name):
if os.getenv('FLASK_CONFIG') == "production":
app = Flask(__name__)
app.config.update(
SECRET_KEY=os.getenv('SECRET_KEY'),
SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI')
)
else:
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
Bootstrap(app)
db.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login"
migrate = Migrate(app, db)
from app import models
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/403.html', title='Forbidden'), 403
@app.errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html', title='Page Not Found'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('errors/500.html', title='Server Error'), 500
return app
def create_app(config_name):
"""
Main app settings
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.init_app(app)
"""
LoginManager settings
"""
login_manager.init_app(app)
login_manager.login_message = "Lutfen uye olunuz."
login_manager.login_view = "uye.giris"
migrate = Migrate(app, db)
Bootstrap(app)
from app import models
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .Uye import uye as uye_blueprint
app.register_blueprint(uye_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/Yasak.html', title='Yasak'), 403
@app.errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html', title='Sayfa Bulunamadi'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('errors/500.html', title='Server Hatasi'), 500
return app
def test_register(self):
"""
Test register
:return: void
"""
# Write config
self.write_config([
"from edmunds.database.drivers.mysql import MySql \n",
"APP = { \n",
" 'database': { \n",
" 'enabled': True, \n",
" 'instances': [ \n",
" { \n",
" 'name': 'mysql',\n",
" 'driver': MySql,\n",
" 'user': 'root',\n",
" 'pass': 'root',\n",
" 'host': 'localhost',\n",
" 'database': 'edmunds',\n",
" }, \n",
" ], \n",
" }, \n",
"} \n",
])
# Create app
app = self.create_application()
# Test extension
self.assert_in('edmunds.database', app.extensions)
self.assert_is_none(app.extensions['edmunds.database']._instances)
self.assert_not_in('edmunds.database.migrate', app.extensions)
# Register
app.register(MigrateServiceProvider)
# Test extension
self.assert_in('edmunds.database.migrate', app.extensions)
self.assert_is_not_none(app.extensions['edmunds.database.migrate'])
self.assert_is_instance(app.extensions['edmunds.database.migrate'], Migrate)
self.assert_is_not_none(app.extensions['edmunds.database']._instances)
def create_app(config_name):
"""
Given a configuration name, loads the correct
configuration from the config.py
:param config_name: The configuration name to load the configuration
:return: The app to be initialized
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.init_app(app)
"""
Configurations of the flask-login, in which, if user tries to access a
page that they are not authorized to, it will redirect to the specific
view and display the message below on the route auth.login
"""
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page"
login_manager.login_view = "auth.login"
"""
Migrations setting up.
This object "migrate" will allow us to run migrations using Flask-Migrate.
We also have imported the models from the app package.
"""
migrate = Migrate(app, db)
Bootstrap(app)
"""
Import the models to be used in the application
"""
from app import models
"""
Configuring the blueprints of each package on the app
"""
from .admin import admin as admin_blueprint
# This url_prefix means that all the views for this blueprint will be
# accessed in the browser with the url prefix admin.
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
return app
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
Bootstrap(app)
db.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login"
migrate = Migrate(app, db)
from app import models
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/403.html', title='Forbidden'), 403
@app.errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html', title='Page Not Found'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('errors/500.html', title='Server Error'), 500
@app.route('/500')
def error():
abort(500)
# @app.route('/')
# def hello_world():
# return 'Hello, World!'
return app
__init__.py 文件源码
项目:flask-selenium-webdriver-part-one
作者: mbithenzomo
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def create_app(config_name):
if os.getenv('FLASK_CONFIG') == "production":
app = Flask(__name__)
app.config.update(
SECRET_KEY=os.getenv('SECRET_KEY'),
SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI')
)
else:
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
Bootstrap(app)
db.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login"
migrate = Migrate(app, db)
from app import models
from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
@app.errorhandler(403)
def forbidden(error):
return render_template('errors/403.html', title='Forbidden'), 403
@app.errorhandler(404)
def page_not_found(error):
return render_template('errors/404.html', title='Page Not Found'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('errors/500.html', title='Server Error'), 500
return app