示例#1
0
def database(app, request):
    """Session-wide test database."""
    def teardown():
        if db.engine.dialect.name == 'sqlite':
            # since sqlite was created in a temp file we skip the drops.
            return
        try:
            db.engine.execute('DROP TABLE vulnerability CASCADE')
        except Exception:
            pass
        try:
            db.engine.execute('DROP TABLE vulnerability_template CASCADE')
        except Exception:
            pass
        db.drop_all()

    # Disable check_vulnerability_host_service_source_code constraint because
    # it doesn't work in sqlite
    vuln_constraints = db.metadata.tables['vulnerability'].constraints
    try:
        vuln_constraints.remove(
            next(constraint for constraint in vuln_constraints
                 if constraint.name ==
                 'check_vulnerability_host_service_source_code'))
    except StopIteration:
        pass
    db.init_app(app)
    db.create_all()

    request.addfinalizer(teardown)
    return db
示例#2
0
def create_app(config_mode):
    app = Flask(__name__, static_url_path='', static_folder='build')
    app.config.from_object(config_by_mode[config_mode])

    cors = CORS(app)

    db.init_app(app)
    init_db(app)

    login_manager.init_app(app)

    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(home_bp, url_prefix='/api/home')
    app.register_blueprint(new_project_bp, url_prefix='/api/new_project')
    app.register_blueprint(project_change_status_bp,
                           url_prefix='/api/project_change_status')

    if config_mode == 'prod':

        @app.route('/')
        def index():
            return app.send_static_file('index.html')

        @app.errorhandler(404)
        def not_found(e):
            return app.send_static_file('index.html')

    return app
示例#3
0
def create_app() -> Flask:
    """Creates and returns the Flask WSGI application
    and initializes helping components"""
    # Initialize json support for wtforms
    wtforms_json.init()

    # Define the WSGI Application object
    app = Flask(__name__,
                template_folder="../../",
                static_folder="../../static")

    # Configurations
    app.config.from_object('server.config')

    # Initialize database with application
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # Initialize login manager with application
    login_manager.init_app(app)

    # Setup the routes
    define_routes(app)

    return app
示例#4
0
def _init_database(app):
    db_path = os.path.join(app.instance_path, "server.sqlite")
    app.config.from_mapping(SECRET_KEY='SECRET_KEY',
                            SQLALCHEMY_DATABASE_URI='sqlite:///' + db_path,
                            SQLALCHEMY_TRACK_MODIFICATIONS=False)

    with app.app_context():
        db.init_app(app)
        db.create_all()
示例#5
0
def create_app(test_config=None):
    app = Flask(__name__)

    CORS(app)  # add CORS

    # check environment variables to see which config to load
    env = os.environ.get("FLASK_ENV", "dev")
    if test_config:
        # ignore environment variable config if config was given
        app.config.from_mapping(**test_config)
    else:
        app.config.from_object(config[env])

    # logging
    formatter = Log_Formatter(
        "%(asctime)s %(remote_addr)s: requested %(url)s: %(levelname)s in [%(module)s: %(lineno)d]: %(message)s"
    )

    # Set stream logger
    stream = logging.StreamHandler()
    stream.setLevel(logging.DEBUG)
    stream.setFormatter(formatter)

    app.logger.addHandler(stream)
    app.logger.setLevel(logging.DEBUG)

    # Set Logging to file
    if app.config.get("LOG_FILE"):
        file_handler = logging.FileHandler(app.config.get("LOG_FILE"))
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)

    # if not prod recreate db every-run
    if env != "prod":
        db_url = app.config["SQLALCHEMY_DATABASE_URI"]
        if not database_exists(db_url):
            create_database(db_url)

    # register sqlalchemy to this app
    db.init_app(app)
    Migrate(app, db)

    # Register blueprints
    app.register_blueprint(main)
    app.register_blueprint(key)
    app.register_blueprint(user)

    # register error Handler
    app.register_error_handler(Exception, all_exception_handler)

    return app
示例#6
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('server.config.DevelopmentConfig')
    app.config['BUNDLE_ERRORS'] = True
    app.url_map.strict_slashes = False

    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    register_flask_blueprints(app)

    from server.models import db
    db.init_app(app)

    return app
示例#7
0
def setup_app(app):
    # Create tables if they do not exist already
    @app.before_first_request
    def create_tables():
        db.create_all()

    db.init_app(app)
    setup_oauth(app)
    app.register_blueprint(home, url_prefix='')
    app.register_blueprint(courses, url_prefix='')
    app.register_blueprint(exercises, url_prefix='')
    app.register_blueprint(hooks, url_prefix='')
    app.register_blueprint(embed, url_prefix='')
示例#8
0
def initApiServer(conf):
    # load config
    app.config.from_object(conf)

    # init flask sqlalchemy
    db.app = app
    db.init_app(app)
    db.create_all()

    # init API endpoints
    manager = APIManager(app, flask_sqlalchemy_db=db)
    createApi(manager)

    return app
示例#9
0
def create_app(config_name):
    from server.models import db
    app = Flask(__name__)
    rq.init_app(app)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    login_manager.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
示例#10
0
文件: __init__.py 项目: swnim/madup
def create_app():
    """flask application generator

    :return: flask application
    """
    app = Flask(__name__)
    config.init_app(app)
    db.init_app(app)
    Swagger(app)

    with app.app_context():
        """ application blueprints """
        from server.api_1_0.views import api as api_blueprint

        app.register_blueprint(api_blueprint, url_prefix='/api/v1')

    return app
示例#11
0
def database(app, request):
    """Session-wide test database."""

    # Disable check_vulnerability_host_service_source_code constraint because
    # it doesn't work in sqlite
    vuln_constraints = db.metadata.tables['vulnerability'].constraints
    try:
        vuln_constraints.remove(
            next(constraint for constraint in vuln_constraints
                 if constraint.name ==
                 'check_vulnerability_host_service_source_code'))
    except StopIteration:
        pass
    db.init_app(app)
    db.create_all()

    return db
示例#12
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(AppConfig())
    db.init_app(app)

    with app.app_context():
        for blueprint in blueprints:
            app.register_blueprint(blueprint)

        app.register_error_handler(KeyError, handle_key_error)
        app.register_error_handler(IntegrityError, handle_integrity_error)
        app.register_error_handler(ValueError, handle_value_error)
        app.register_error_handler(
            StatementError,
            handle_value_error)  # StatementError is a subclass of ValueError
        app.register_error_handler(NotFound, handle_not_found)
        app.register_error_handler(BadRequest, handle_bad_request)

    return app
示例#13
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.py')

    # db
    db.init_app(app)
    migrate.init_app(app, db)
    marshmallow.init_app(app)

    # CORS
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    cors.init_app(app)

    # blueprint apps
    app.register_blueprint(books_blueprint, url_prefix='/api/books')

    # static files for dev

    return app
示例#14
0
def create_app(instance_path=None, static_folder='../frontend/build'):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__,
                instance_path=instance_path,
                static_url_path='/',
                static_folder=static_folder,
                instance_relative_config=True)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    db_path = os.path.join(app.instance_path, "server.sqlite")
    app.config.from_mapping(SECRET_KEY='SECRET_KEY',
                            SQLALCHEMY_DATABASE_URI='sqlite:///' + db_path,
                            SQLALCHEMY_TRACK_MODIFICATIONS=False)

    db.init_app(app)
    # apply the blueprints to the app
    from server import auth, api
    app.register_blueprint(auth.bp)
    app.register_blueprint(api.bp)

    @app.errorhandler(ValueError)
    def http_error_handler(error):
        return jsonify(code=400, message=str(error)), 400

    @app.errorhandler(HTTPException)
    def http_error_handler(error):
        return jsonify(code=error.code, message=error.description), error.code

    @app.route('/')
    def home():
        return redirect('/index.html', code=302)

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

    return app
示例#15
0
def create_app(object_name, env="prod"):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. server.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config['ENV'] = env
    cors = CORS(app)
    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
示例#16
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    from server.main import main
    app.register_blueprint(main)

    from server.api import api
    app.register_blueprint(api, url_prefix="/api")

    from server.replays import replays
    app.register_blueprint(replays, url_prefix="/replays")

    from server.server import server
    app.register_blueprint(server, url_prefix="/servers")

    from server.maps import maps
    app.register_blueprint(maps, url_prefix="/maps")

    db.init_app(app)

    return app
示例#17
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. server.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)

    return app
示例#18
0
文件: app.py 项目: peval/faraday
def create_app(db_connection_string=None, testing=None):
    app = Flask(__name__)

    try:
        app.config['SECRET_KEY'] = server.config.faraday_server.secret_key
    except Exception:
        save_new_secret_key(app)

    login_failed_message = ("Invalid username or password", 'error')

    app.config.update({
        'SECURITY_PASSWORD_SINGLE_HASH':
        True,
        'WTF_CSRF_ENABLED':
        False,
        'SECURITY_USER_IDENTITY_ATTRIBUTES': ['username'],
        'SECURITY_POST_LOGIN_VIEW':
        '/_api/session',
        'SECURITY_POST_LOGOUT_VIEW':
        '/_api/login',
        'SECURITY_POST_CHANGE_VIEW':
        '/_api/change',
        'SECURITY_CHANGEABLE':
        True,
        'SECURITY_SEND_PASSWORD_CHANGE_EMAIL':
        False,
        'SECURITY_MSG_USER_DOES_NOT_EXIST':
        login_failed_message,

        # The line bellow should not be necessary because of the
        # CustomLoginForm, but i'll include it anyway.
        'SECURITY_MSG_INVALID_PASSWORD':
        login_failed_message,
        'SESSION_TYPE':
        'filesystem',
        'SESSION_FILE_DIR':
        server.config.FARADAY_SERVER_SESSIONS_DIR,
        'SQLALCHEMY_TRACK_MODIFICATIONS':
        False,
        'SQLALCHEMY_RECORD_QUERIES':
        True,
        # app.config['SQLALCHEMY_ECHO'] = True
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt',  # This should be the default value
            # 'des_crypt',
            'pbkdf2_sha1',  # Used by CouchDB passwords
            # 'pbkdf2_sha256',
            # 'pbkdf2_sha512',
            # 'sha256_crypt',
            # 'sha512_crypt',
            'plaintext',  # TODO: remove it
        ],
        'PERMANENT_SESSION_LIFETIME':
        datetime.timedelta(hours=12),
    })

    try:
        storage_path = server.config.storage.path
    except AttributeError:
        logger.warn(
            'No storage section or path in the .faraday/server.ini. Setting the default value to .faraday/storage'
        )
        storage_path = setup_storage_path()
    if not DepotManager.get('default'):
        if testing:
            DepotManager.configure('default', {'depot.storage_path': '/tmp'})
        else:
            DepotManager.configure('default',
                                   {'depot.storage_path': storage_path})

    check_testing_configuration(testing, app)

    try:
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = db_connection_string or server.config.database.connection_string.strip(
                "'")
    except AttributeError:
        logger.info(
            'Missing [database] section on server.ini. Please configure the database before running the server.'
        )
    except NoOptionError:
        logger.info(
            'Missing connection_string on [database] section on server.ini. Please configure the database before running the server.'
        )

    from server.models import db
    db.init_app(app)
    #Session(app)

    # Setup Flask-Security
    app.user_datastore = SQLAlchemyUserDatastore(
        db, user_model=server.models.User,
        role_model=None)  # We won't use flask security roles feature
    Security(app, app.user_datastore, login_form=CustomLoginForm)
    # Make API endpoints require a login user by default. Based on
    # https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default
    app.view_functions['security.login'].is_public = True
    app.view_functions['security.logout'].is_public = True

    app.debug = server.config.is_debug_mode()
    minify_json_output(app)

    for handler in LOGGING_HANDLERS:
        app.logger.addHandler(handler)

    register_blueprints(app)
    register_handlers(app)

    return app
示例#19
0
文件: app.py 项目: infobyte/faraday
def create_app(db_connection_string=None, testing=None):
    app = Flask(__name__)

    try:
        secret_key = server.config.faraday_server.secret_key
    except Exception:
        # Now when the config file does not exist it doesn't enter in this
        # condition, but it could happen in the future. TODO check
        save_new_secret_key(app)
    else:
        if secret_key is None:
            # This is what happens now when the config file doesn't exist.
            # TODO check
            save_new_secret_key(app)
        else:
            app.config['SECRET_KEY'] = secret_key

    login_failed_message = ("Invalid username or password", 'error')

    app.config.update({
        'SECURITY_PASSWORD_SINGLE_HASH': True,
        'WTF_CSRF_ENABLED': False,
        'SECURITY_USER_IDENTITY_ATTRIBUTES': ['username'],
        'SECURITY_POST_LOGIN_VIEW': '/_api/session',
        'SECURITY_POST_LOGOUT_VIEW': '/_api/login',
        'SECURITY_POST_CHANGE_VIEW': '/_api/change',
        'SECURITY_CHANGEABLE': True,
        'SECURITY_SEND_PASSWORD_CHANGE_EMAIL': False,
        'SECURITY_MSG_USER_DOES_NOT_EXIST': login_failed_message,

        # The line bellow should not be necessary because of the
        # CustomLoginForm, but i'll include it anyway.
        'SECURITY_MSG_INVALID_PASSWORD': login_failed_message,

        'SESSION_TYPE': 'filesystem',
        'SESSION_FILE_DIR': server.config.FARADAY_SERVER_SESSIONS_DIR,

        'SQLALCHEMY_TRACK_MODIFICATIONS': False,
        'SQLALCHEMY_RECORD_QUERIES': True,
        # app.config['SQLALCHEMY_ECHO'] = True
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt',  # This should be the default value
            # 'des_crypt',
            'pbkdf2_sha1',  # Used by CouchDB passwords
            # 'pbkdf2_sha256',
            # 'pbkdf2_sha512',
            # 'sha256_crypt',
            # 'sha512_crypt',
            'plaintext',  # TODO: remove it
        ],
        'PERMANENT_SESSION_LIFETIME': datetime.timedelta(hours=12),
    })

    storage_path = server.config.storage.path
    if not storage_path:
        logger.warn('No storage section or path in the .faraday/server.ini. Setting the default value to .faraday/storage')
        storage_path = setup_storage_path()

    if not DepotManager.get('default'):
        if testing:
            DepotManager.configure('default', {
                'depot.storage_path': '/tmp'
            })
        else:
            DepotManager.configure('default', {
                'depot.storage_path': storage_path
            })

    check_testing_configuration(testing, app)

    try:
        app.config['SQLALCHEMY_DATABASE_URI'] = db_connection_string or server.config.database.connection_string.strip("'")
    except AttributeError:
        logger.info('Missing [database] section on server.ini. Please configure the database before running the server.')
    except NoOptionError:
        logger.info('Missing connection_string on [database] section on server.ini. Please configure the database before running the server.')

    from server.models import db
    db.init_app(app)
    #Session(app)

    # Setup Flask-Security
    app.user_datastore = SQLAlchemyUserDatastore(
        db,
        user_model=server.models.User,
        role_model=None)  # We won't use flask security roles feature
    Security(app, app.user_datastore, login_form=CustomLoginForm)
    # Make API endpoints require a login user by default. Based on
    # https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default
    app.view_functions['security.login'].is_public = True
    app.view_functions['security.logout'].is_public = True

    app.debug = server.config.is_debug_mode()
    minify_json_output(app)

    for handler in LOGGING_HANDLERS:
        app.logger.addHandler(handler)

    register_blueprints(app)
    register_handlers(app)

    return app
示例#20
0
def create_app(default_config_path=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, reads from
    default_config_path instead. This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    config_path = os.getenv('OK_SERVER_CONFIG', default_config_path)
    if config_path is None:
        raise ValueError('No configuration file found'
            'Check that the OK_SERVER_CONFIG environment variable is set.')
    app.config.from_pyfile(config_path)

    # Set REMOTE_ADDR for proxies
    num_proxies = app.config.get('NUM_PROXIES', 0)
    if num_proxies:
        app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=num_proxies)

    # Sentry Error Reporting
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug and sentry_dsn:
        sentry.init_app(app, dsn=sentry_dsn)

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                event_id=g.sentry_event_id,
                public_dsn=sentry.client.get_public_dsn('https')
            ), 500

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    @app.route("/healthz")
    def health_check():
        return 'OK'

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)


    # Flask-Login manager
    login_manager.init_app(app)

    # Set up logging
    logging.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils': utils,
        'debug': app.debug,
        'instantclick': app.config.get('INSTANTCLICK', True),
        'CSRFForm': CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app
示例#21
0
def create_app(default_config_path=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, reads from
    default_config_path instead. This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    config_path = os.getenv('OK_SERVER_CONFIG', default_config_path)
    if config_path is None:
        raise ValueError(
            'No configuration file found'
            'Check that the OK_SERVER_CONFIG environment variable is set.')
    app.config.from_pyfile(config_path)

    # Senty Error Reporting & Other Prod Changes
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug:
        app.wsgi_app = ProxyFix(app.wsgi_app)
        if sentry_dsn:
            sentry.init_app(app, dsn=sentry_dsn)

            @app.errorhandler(500)
            def internal_server_error(error):
                return render_template(
                    'errors/500.html',
                    event_id=g.sentry_event_id,
                    public_dsn=sentry.client.get_public_dsn('https')), 500

        # In production mode, add log handler to sys.stderr.
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.INFO)

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    # Flask-Login manager
    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils':
        utils,
        'debug':
        app.debug,
        'instantclick':
        app.config.get('INSTANTCLICK', True),
        'CSRFForm':
        CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app
示例#22
0
from argparse import ArgumentParser

from flask import Flask

from server.app import AppConfig
from server.models import db
"""
Creates the database if it does not already exist and creates all the tables inside if it
Can be run with the --delete command line flag to empty the existing database
"""
if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument(
        '--delete',
        help="DELETES ALL DATA in the database and starts over",
        action='store_true')

    drop_all = parser.parse_args().delete

    app = Flask(__name__)
    app.config.from_object(AppConfig())
    db.init_app(app)
    with app.app_context():
        if drop_all:
            db.drop_all()

        db.create_all()
示例#23
0
from flask import Flask, render_template, jsonify, request
from server.models import db, Entry, EntrySchema, EntryFactory
from datetime import datetime
import os
from pprint import pprint

app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, 'flaskstream.db')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['DEBUG'] = True

db.init_app(app)

entry_schema = EntrySchema()
entries_schema = EntrySchema(many=True, only=('posted', 'text'))

@app.route('/')
def index():
    # create_entry()
    return render_template('index.html', text='Hello world')


@app.route('/entries', methods=['GET'])
def entries():
    entries = Entry.query.order_by(Entry.posted.desc()).all()
    result = entries_schema.dump(entries)
    out = jsonify({'entries': result.data})
    pprint(out.response)
示例#24
0
def create_app(environment_name=None):
    """Create and return a Flask application. Reads a config file path from the
    OK_SERVER_CONFIG environment variable. If it is not set, it imports and reads 
    from the config module (using environment_name). This is so we can default to a development
    environment locally, but the app will fail in production if there is no
    config file rather than dangerously defaulting to a development environment.
    """

    app = Flask(__name__)

    env_module_path = os.getenv('OK_SERVER_CONFIG',
                                'server.settings.{}'.format(environment_name))

    if '/' in env_module_path:
        env_module_path = env_module_path.replace('/', '.')
        env_module_path = env_module_path.replace('.py', '')

    app.config.from_object(env_module_path  + '.Config')

    # Set REMOTE_ADDR for proxies
    num_proxies = app.config.get('NUM_PROXIES', 0)
    if num_proxies:
        app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=num_proxies)

    # Sentry Error Reporting
    sentry_dsn = os.getenv('SENTRY_DSN')
    if not app.debug and sentry_dsn:
        sentry.init_app(app, dsn=sentry_dsn)

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                event_id=g.sentry_event_id,
                public_dsn=sentry.client.get_public_dsn('https')
            ), 500

    # Azure Application Insights request and error tracking
    appinsights.init_app(app)

    @app.errorhandler(404)
    def not_found_error(error):
        if request.path.startswith("/api"):
            return api.handle_error(error)
        return render_template('errors/404.html'), 404

    @app.route("/healthz")
    def health_check():
        return 'OK'

    @app.after_request
    def flush_appinsights_telemetry(response):
        appinsights.flush()
        return response

    @app.context_processor
    def inject_root_url():
        return {'index_url': app.config['APPLICATION_ROOT']}

    # initialize the cache
    cache.init_app(app)

    # initialize redis task queues
    RQ(app)

    # Protect All Routes from csrf
    csrf.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    # Flask-Login manager
    login_manager.init_app(app)

    # initalize cloud storage
    storage.init_app(app)
    # Set up logging
    logging.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # custom URL handling
    converters.init_app(app)

    # custom Jinja rendering
    app.jinja_env.globals.update({
        'utils': utils,
        'debug': app.debug,
        'instantclick': app.config.get('INSTANTCLICK', True),
        'CSRFForm': CSRFForm
    })

    app.jinja_env.filters.update({
        'markdown': utils.convert_markdown,
        'pluralize': utils.pluralize,
    })

    # register our blueprints
    # OAuth should not need CSRF protection
    csrf.exempt(auth)
    app.register_blueprint(auth)

    csrf.exempt(oauth)
    app.register_blueprint(oauth)
    app.register_blueprint(files)

    app.register_blueprint(student)

    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(about, url_prefix='/about')

    # Redis Queue dashboard
    csrf.exempt(queue)
    app.register_blueprint(queue, url_prefix='/rq')

    # API does not need CSRF protection
    csrf.exempt(api_endpoints)
    app.register_blueprint(api_endpoints, url_prefix=API_PREFIX)

    return app