def configure_db(app): from app.database import db, db_session, init_db init_db(app) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
def create_app(): app = Flask(__name__) app.config.from_object('app.config.Config') init_db(app) return app
def init(args): init_db(app.config['ADMIN_USER']) indexDir = app.config['INDEX_PATH'] if os.path.exists(indexDir): shutil.rmtree(indexDir)
def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.database import init_db from app.loginmanager import init_login_manager from app.workforceapp.controller import regular_api_blueprint, regular_html_blueprint from app.workforceapp.controller import admin_html_blueprint, admin app = Flask(__name__, **kwargs) try: app.config.from_pyfile('../config.py') except ImportError: raise Exception('Invalid Config') app.register_blueprint(regular_api_blueprint, url_prefix='/api/v1/') app.register_blueprint(regular_html_blueprint, url_prefix='/') app.register_blueprint(admin_html_blueprint, url_prefix='/admin/') init_db(app) init_login_manager(app) admin.init_app(app) return app
def create_app(): """ Create and configure the app """ app = Flask(__name__) CORS(app) # Initialize database from app.database import db_session, init_db init_db() # Flask will automatically remove database sessions at the end # See http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/#declarative @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() # Initialize routes from app.main_page import main_page app.register_blueprint(main_page) # Support debug with VSCODE if app.debug: import ptvsd ptvsd.enable_attach(os.getenv('SECRET_DEBUG'), address=('0.0.0.0', 3000)) return app
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--port', default=50000, type=int) parser.add_argument('--data-json', dest="data", type=argparse.FileType('r', encoding="utf-8"), default="./data/users.json") parser.add_argument('--dump-json', dest="data_out", type=argparse.FileType('w', encoding="utf-8"), default="./data/users2.json") parser.add_argument('--dblogin', default='postgres') parser.add_argument('--dbpassword', default='asdf') parser.add_argument('--dbhost', default='127.0.0.1') parser.add_argument('--dbport', default='5432') parser.add_argument('--dbname', default='chatdb1') args = parser.parse_args() import settings settings.DB_URL = \ f'postgresql+psycopg2://{args.dblogin}:{args.dbpassword}@{args.dbhost}:{args.dbport}/{args.dbname}' from app.database import init_db, dump_db import json import app.routes_api init_db(json.loads(args.data.read())) app.app.run('::', args.port, debug=True, threaded=True) dump_db(args.data_out)
def setUpClass(cls): # Initialize the database from app.database import init_db init_db() # Create the application from app import create_app middleware = [] cls.app = webtest.TestApp(create_app().wsgifunc(*middleware))
def initalize_database(app): from app.database import db_session, init_db init_db() # Flask will automatically remove database sessions at the end # See http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/#declarative @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
def create_app(config_name='default', db_path=None): # initialize application DEV_CONF = 'config.DevelopmentConfig' config = { 'production' : 'config.ProductionConfig', 'development' : DEV_CONF, 'testing' : 'config.TestingConfig', 'default' : DEV_CONF } app = Flask(__name__, instance_relative_config=True) app.config.from_object(config.get(config_name, DEV_CONF)) app.config.from_pyfile('sensitive_data.cfg') if db_path: app.config['SQLALCHEMY_DATABASE_URI'] = db_path # initialize logger with open('config.yaml') as file: conf_dict = yaml.safe_load(file) logging.config.dictConfig(conf_dict) # initialize database init_db(app) # register blueprints from app.views import common app.register_blueprint(common.app) from app.views import web app.register_blueprint(web.app) from app.views import api app.register_blueprint(api.app, url_prefix='/api') from app.views import auth app.register_blueprint(auth.app, url_prefix='/auth') # from app.views import oauth # app.register_blueprint(oauth.app, url_prefix='/oauth') from app.views import user app.register_blueprint(user.app, url_prefix='/user') from app.views import bot app.register_blueprint(bot.app, url_prefix='/bot') from app.views import uploads app.register_blueprint(uploads.app) app.add_url_rule('/', endpoint='index') # register cli commands from app.jobs import job app.cli.add_command(job) # check exist instance directory try: os.makedirs(app.instance_path) except OSError: pass return app
def testCreate(self): init_db() user_datastore = SQLAlchemyUserDatastore(db_session, User, Role) security = Security(app, user_datastore) user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') db_session.commit()
def create_app(): app = Flask(__name__) app.config.from_object('app.config.Config') init_db(app) from . import tasks app.register_blueprint(tasks.bp) app.add_url_rule('/', endpoint='index') app.register_error_handler(404, page_not_found) return app;
def create_app(config_name): app = Flask(Config.APP_NAME, instance_relative_config=True) app.config.from_object(app_config[config_name]) print('Database path is: %s' % app.config['DATABASE_PATH']) app.register_blueprint(example) init_db() return app
def create_app() -> Flask: """ Flaskアプリケーションの初期化 """ _app: Flask = Flask(__name__) CORS(_app) # Flaskのconfigが 設定ファイルを読み込む処理 _app.config.from_object(Config) # DBセッションの暗号化のため _app.secret_key = os.urandom(24) # DB初期化 init_db(_app) return _app
def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.database import init_db from app.loginmanager import init_login_manager from app.crypt import init_crypt from app.admin import init_admin from app.mail import init_mail from app.workforce.api import api_blueprint from app.workforce.web import html_blueprint from app.workforce.verify import verify_blueprint from app.admin import admin_html_blueprint import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration app = Flask(__name__, **kwargs) try: app.config.from_pyfile('../config.py') except ImportError: raise Exception('Invalid Config') app.register_blueprint(api_blueprint, url_prefix='/api/v1/') app.register_blueprint(admin_html_blueprint, url_prefix='/admin/') app.register_blueprint(verify_blueprint, url_prefix='/verify') app.register_blueprint(html_blueprint, url_prefix='/') init_db(app) init_login_manager(app) init_crypt(app) init_mail(app) init_admin(app) sentry_sdk.init(dsn=app.config['SENTRY_DSN'], integrations=[FlaskIntegration()]) from flask_cors import CORS cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) print(app.url_map) print("Database Reset:", app.config['SQLALCHEMY_DATABASE_RESET']) SAMPLE_DATA = app.config['SQLALCHEMY_DATABASE_RESET'] if SAMPLE_DATA: add_data(app) return app
def _create_app(config_mode='development'): app = Flask(Config.APP_NAME) app.config.from_object(Config) CORS(app) init_db(app) app.register_blueprint(user_api, url_prefix='/api/') app.register_blueprint(auth_api, url_prefix='/api/') app.register_blueprint(note_api, url_prefix='/api/') app.register_blueprint(file_api, url_prefix='/api/') FlaskInjector(app=app, modules=[_bind]) return app
def create_app(config=None): # App Initializtion app = Flask(__name__) app.config.from_object(config) # Database Initialization init_engine(app.config['SQLALCHEMY_DATABASE_URI']) init_db() # Initialize any extension and bind blueprint from .main.views import main as main_blueprint app.register_blueprint(main_blueprint) from .event.views import event as event_blueprint app.register_blueprint(event_blueprint) return app
def app(): """Create and configure a new app instance for each test.""" # create the app with common test config if os.getenv("TRAVIS") or False: config_name = "travis" else: config_name = "testing" app = create_app(config_name) # reset the database drop_db(config_name) init_db(config_name) # override dependencies app.dependency_overrides[get_db] = override_get_db yield app
def create_app(): #I remove sqlAlchemy object db. Instead we have init_db() give us tables class for use. init_db() # app = Flask(__name__) bootstrap = Bootstrap(app) moment = Moment(app) login_manager = LoginManager(app) # toolbar = DebugToolbarExtension(app) cache.init_app(app) compress.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') return app
def app(): db_fd, db_path = tempfile.mkdtemp() app = create_app('test', { 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': db_path }) with app.app_context(): init_db() print(app) yield app os.close(db_fd) os.unlink(db_path)
def create_app(config_name=None, **kwargs): FLASK_RUN_PORT = os.environ['SERVE_PORT'] os.environ['FLASK_RUN_PORT'] = FLASK_RUN_PORT if FLASK_RUN_PORT: app = Flask(__name__, **kwargs) try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') app.register_blueprint(happy_birthday, url_prefix='/hello') init_db(app) else: print('SERVE_PORT not defined') raise Exception return app
def create_app(config): app = Flask(__name__) app.register_blueprint(api) app.config.from_object(config) if app.debug is not True: import logging handler = logging.FileHandler('log.txt') handler.setLevel(logging.ERROR) app.logger.addHandler(handler) db = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=db)) Base.query = session.query_property() app.db_session = session init_db(db) return app
def create_app(): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.secret_key = "ECE1779" app.register_blueprint(manager.bp) app.register_blueprint(auto_scaler.bp) database.init_db() # initialize during app creation manager.app_initialization() # start the auto-scaler as the background thread thread = Thread(target=auto_scaler.start) thread.daemon = True thread.start() return app
def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.database import init_db from app.contacts.views import contacts_api app = Flask(__name__, **kwargs) try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') app.register_blueprint(contacts_api, url_prefix='/api/contacts/') init_db(app) return app
def create_app(settings_module=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ if settings_module is None: settings_module = 'app.settings' app = Flask(__name__, **kwargs) try: app.config.from_object(settings_module) except ImportError: raise ImportError( f'The app settings file cannot import from {settings_module}') app.register_blueprint(users_api, url_prefix='/api/users/') app.register_blueprint(products_api, url_prefix='/api/products/') app.register_blueprint(lists_api, url_prefix='/api/lists/') init_db(app) return app
def create_app(): dictConfig({ 'version': 1, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', } }, 'handlers': { 'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' } }, 'root': { 'level': 'INFO', 'handlers': ['wsgi'] } }) web_app = Flask(__name__) CORS(web_app) root = "/projects/battleship/" from app.routes import game, lobby, index, search web_app.register_blueprint(index.start_page, url_prefix=root) web_app.register_blueprint(lobby.lobby_page, url_prefix=root + "/lobby") web_app.register_blueprint(game.game_page, url_prefix=root + "/game") web_app.register_blueprint(search.search_page, url_prefix=root + "/search") web_app.config['TESTING'] = True web_app.config["DATABASE"] = "./battleship.db" web_app.secret_key = open("app/static/secret.txt").readline() with web_app.app_context(): database.init_db() from app import shared shared.socketio = SocketIO(web_app, logger=True) return web_app, shared.socketio
def create_app(): # create and configure the app app = Flask(__name__, instance_relative_config=True) # initialize the database connection based on the environment variable from app import database database.init_db(app.config["ENV"]) # use a constant secret key for database for now # for real case, probably use the CMK stored in AWS SSM Parameter Store and retrieve from there app.secret_key = "ECE1779" # register the blueprint to associate with a separate file and path from app import api app.register_blueprint(api.bp) from app import login app.register_blueprint(login.bp) from app import detection app.register_blueprint(detection.bp) from app import user app.register_blueprint(user.bp) from app import history app.register_blueprint(history.bp) # auto forward the root index to login @app.route("/") def root_index(): return redirect(url_for("login.login")) # start the auto-scaler as the background thread instance_id = aws_helper.get_instance_id() thread = Thread(target=aws_helper.collect_requests_count, args=(instance_id, )) thread.daemon = True thread.start() return app
def create_app(): app = Flask( __name__, static_url_path = "/public/", static_folder = os.path.join(APP_PATH, "dist"), template_folder = os.path.join(APP_PATH, "dist") ) # app.static_url_path = "/public/" # app.static_folder = os.path.join(APP_PATH, "dist") # app.template_folder = os.path.join(APP_PATH, "dist") app.url_map.strict_slashes = False # Set Environment Variables dotenv.load_dotenv(dotenv_path=".env") # Set Configuration Default FLASK_ENV = os.environ.get("FLASK_ENV", "production").lower() if FLASK_ENV == "development": app.config.from_object("app.config.flask.DevelopmentConfig") else: app.config.from_object("app.config.flask.ProductionConfig") # Set Configuration for SECRET_KEY SECRET_KEY = app.config.get("SECRET_KEY") or os.environ.get("SECRET_KEY", None) if not SECRET_KEY: raise ValueError("No SECRET_KEY set for Flask application") app.config["SECRET_KEY"] = SECRET_KEY # Set Database init_db() with app.app_context(): handle_middleware() init_route() return app
def create_app() -> Flask: locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8') server = Flask( __name__, static_folder=Defaults.FRONTEND_DIR, template_folder=Defaults.FRONTEND_DIR, ) server.json_encoder = DefaultJSONEncoder setup_logging() setup_errors(server) add_views(server) setup_db(server) init_db(server) @server.after_request def log_access(response): data = "<not printable>" if response.headers.get("Content-Type") == "application/json": try: data = response.get_data().decode("utf-8") except UnicodeDecodeError: pass log_message = None try: log_message = json.loads(data) except json.JSONDecodeError: log_message = data structlog.get_logger("access").info("RESPONSE", status=response.status_code, data=log_message) return response init_plotly_dash(server) return server
from app import create_app, celery from app.database import init_db import os settings_module = os.getenv('APP_SETTINGS_MODULE') app = create_app(settings_module, celery=celery) with app.app_context(): init_db() if __name__ == '__main__': app.run()
#!flask/bin/python # -*- coding: utf-8 -*- from app import app from app.database import init_db, db_session from app.models import Book, Author init_db() q_author = Author(name=u'Фрэнк Херберт') q_author.books.append(Book(name=u'Дюна')) db_session.add(q_author) q_author = Author(name=u'Толкин') q_author.books.append(Book(name=u'Властелин колец')) db_session.add(q_author) q_author = Author(name=u'Макс Фрай') q_author.books.append(Book(name=u'Лабиринты Эхо')) db_session.add(q_author) q_author = Author(name=u'Ник Перумов') q_author.books.append(Book(name=u'Алмазный меч, деревянный меч')) db_session.add(q_author) q_author = Author(name=u'Фридрих Ницше') q_author.books.append(Book(name=u'Так говорил Заратустра.')) db_session.add(q_author) db_session.commit()
def setUp(self): #Base.metadata.drop_all(bind=engine) #Base.metadata.create_all(bind=engine) init_db()
#!/usr/bin/env python #script to run from command line to create db from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import database import os.path database.init_db() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) else: api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
def setUp(self): self.db_fd, app.config["DATABASE"] = tempfile.mkstemp() app.config["TESTING"] = True self.app = app.test_client() database.init_db()
def connect_db(): init_db()
def setUp(self): """Setup flask app for testing.""" self.app = app.test_client() init_db()
if not telomere.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler(telomere.config['SMTP_SERVER'], telomere.config['APPLICATION_EMAIL_ADDRESSES'], telomere.config['ADMIN_EMAIL_ADDRESSES'], telomere.config['ERROR_EMAIL_SUBJECT']) mail_handler.setLevel(logging.ERROR) telomere.logger.addHandler(mail_handler) @telomere.errorhandler(500) @telomere.errorhandler(Exception) def internal_error(exception): print(traceback.format_exc()) telomere.logger.error(traceback.format_exc()) return render_template('500.html'), 500 db = SQLAlchemy(telomere) import app.database database.init_db() @telomere.before_request def set_date(): g.year = datetime.datetime.now().year import app.helpers.templateFilters from app.views import *
def setup(): print("generating " + settings.SQLALCHEMY_DATABASE_URI) database.init_db()
def setUp(self): self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() app.config['TESTING'] = True self.app = app.test_client() init_db()