Exemplo n.º 1
0
def main(app):
    global security, jwt, apimanager

    # Setup Flask-Security  =======================================================
    security = Security(app, user_datastore)
    jwt = JWT(app, authenticate, load_user)
    apimanager = APIManager(app, flask_sqlalchemy_db=db)
    init_admin()

    if app.teardown_request_funcs:
        for bp, func_list in app.teardown_request_funcs.items():
            for i, func in enumerate(func_list):
                app.teardown_request_funcs[bp][i] = wrap_teardown_func(func)
    if app.teardown_appcontext_funcs:
        for i, func in enumerate(app.teardown_appcontext_funcs):
            app.teardown_appcontext_funcs[i] = wrap_teardown_func(func)

    mail.init_app(app)
    try:
        db.init_app(app)
        with app.app_context():
            db.create_all()
    except Exception as e:
        print(e)

        # Start server  ===============================================================
        if __name__ == '__main__':
            try:
                app.run()
            except Exception as e:
                traceback.print_exc()
Exemplo n.º 2
0
def init_flask_app():
    """ Main app init function """

    # Initialize file logging
    #########################
    if not app.testing:
        import logging.handlers
        file_handler = logging.handlers.RotatingFileHandler(app.config['APP_LOG_FILE'], maxBytes=8192, backupCount=5)
        if app.debug:  # Log everything in debug mode
            file_handler.setLevel(logging.DEBUG)
        else:
            file_handler.setLevel(logging.WARNING)
        file_handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(levelname)-8s: %(message)s',
                                                    datefmt='%Y-%m-%d %H:%M'))
        app.logger.addHandler(file_handler)

        # Log pre_logger
        for log in pre_logger:
            app.logger.log(log[0], log[1])

    # Set locale for datetime format
    ################################
    import locale

    def try_locale(locale_list):
        """ Recursively try locales from a list """
        if not locale_list:
            app.logger.warning('Locale not found')
            return
        head, tail = locale_list[0], locale_list[1:]
        try:
            locale.setlocale(locale.LC_TIME, head)
            app.logger.info('Locale set to ' + head)
        except locale.Error:
            try_locale(tail)

    our_locales = ('nb_NO.utf8', 'nb_NO', 'no_NO', 'norwegian-bokmal')
    try_locale(our_locales)
    app.logger.debug('Preferred locale encoding: ' + locale.getpreferredencoding())

    # Initialize database and Flask_Security
    ########################################
    init_security()

    # Initialize Flask-Admin
    ########################
    from admin import init_admin
    init_admin(app)

    # Context processors
    ####################
    @app.context_processor
    def inject_year():
        """ Make year available in templates """
        from datetime import datetime
        return dict(year=datetime.now().year)

    # Do last
    #########
    import flask_app.views
Exemplo n.º 3
0
def init_app():
    app_obj = Flask(__name__)
    app_obj.config.from_object('config.BaseConfig')
    app_obj.secret_key = secret_key

    init_db(app_obj)
    init_admin(app_obj)
    add_bp(app_obj)

    return app_obj
Exemplo n.º 4
0
def create_app():
    from database import db
    from admin import SecuredHomeView, init_admin
    from models import User, Role
    import views

    app = Flask(__name__)
    load_config(app)
    db.init_app(app)
    setup_security(app)
    init_admin(app)

    app.register_blueprint(views.bp)

    return app
Exemplo n.º 5
0
def create_app():
    app = Flask(__name__)

    app.debug = True
    app.testing = False

    import config
    app.config.from_object(config)

    app.config['SHELF_PAGES'] = {
        "index": (IndexPage, IndexPageModelView),
        "contact": (ContactPage, ContactPageModelView),
    }

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

        babel = Babel(app)

        shlf = Shelf(app)
        shlf.init_db(db)

        dview = DashboardView()
        shlf.init_admin(index_view=dview)

        shlf.init_security(User, Role)

        shlf.load_plugins((
            "shelf.plugins.dashboard",
            "shelf.plugins.i18n",
            "shelf.plugins.library",
            "shelf.plugins.page",
            "shelf.plugins.preview",
            "shelf.plugins.workflow",
            "shelf.plugins.wysiwyg",
            "shelf.plugins.ecommerce",
        ))
        init_admin(shlf.admin, db.session)
        shlf.setup_plugins()

        page = shlf.get_plugin_by_class(PagePlugin)
        page.register_pages(app, shlf.db)

        init_views(app)
        init_filters(app)

    return app
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = configuration['gmail_username']
app.config['MAIL_PASSWORD'] = configuration['gmail_password']
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Aula Virtual] '
app.config['FLASKY_MAIL_SENDER'] = 'Prof. Sol Famida'

print(app.config['SQLALCHEMY_DATABASE_URI'])

from mail import init_mail
mail = init_mail(app)

from flask_bootstrap import Bootstrap
Bootstrap(app)

from admin import init_admin
admin = init_admin(app)

# ORM - Object Relational Mapping -Magico que se conecta a casi cualquiera base de datos.
from models import init_db, User
db = init_db(app)

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

from flask_login import LoginManager
login_manager = LoginManager()  # Creando el objeto de la clase Login
login_manager.init_app(app)  # Asociando el login a la app
login_manager.login_view = 'login'  # Donde voy si no estoy loggeado

apimanager = APIManager(app, flask_sqlalchemy_db=db)
apimanager.create_api(SomeStuff,
    methods=['GET', 'POST', 'DELETE', 'PUT'],
    url_prefix='/api/v1',
    collection_name='free_stuff',
    include_columns=['id', 'data1', 'data2', 'user_id'])
apimanager.create_api(SomeStuff,
    methods=['GET', 'POST', 'DELETE', 'PUT'],
    url_prefix='/api/v1',
    preprocessors=dict(GET_SINGLE=[auth_func], GET_MANY=[auth_func]),
    collection_name='protected_stuff',
    include_columns=['id', 'data1', 'data2', 'user_id'])


# Setup Admin  ================================================================
init_admin()


# Bootstrap  ==================================================================
def create_test_models():
    user_datastore.create_user(email='test', password=encrypt_password('test'))
    user_datastore.create_user(email='test2', password=encrypt_password('test2'))
    stuff = SomeStuff(data1=2, data2='toto', user_id=1)
    db.session.add(stuff)
    stuff = SomeStuff(data1=5, data2='titi', user_id=1)
    db.session.add(stuff)
    db.session.commit()


@app.before_first_request
def bootstrap_app():
Exemplo n.º 8
0
import rest
from flask import render_template, request, redirect, jsonify, g
from models import *

import json

app.register_blueprint(blueprints.user_bp, url_prefix='/user')
app.register_blueprint(blueprints.image_bp, url_prefix='/image')
app.register_blueprint(blueprints.video_bp, url_prefix='/video')
app.register_blueprint(blueprints.audio_bp, url_prefix='/audio')
app.register_blueprint(blueprints.shortcut_bp, url_prefix='/shortcut')
app.register_blueprint(blueprints.shortcut_sd, url_prefix='/definitions')

rest.ReSTManager.init_rest(app)

admin.init_admin()


@app.route('/')
def index():
    return render_template('index.html', config=app.config)


@app.route('/statistic')
def statistic():
    worker_accuracy = []
    return render_template('statistic.html', worker_accuracy=worker_accuracy)
    pass


@app.route('/test')
Exemplo n.º 9
0
app.add_url_rule(
    '/graphql',
    view_func=GraphQLView.as_view(
        'graphql',
        schema=schema,
        graphiql=True  # for having the GraphiQL interface
    ))
app.secret_key = os.environ['SECRET_KEY']
CORS(app)

root_password = os.environ['ROOT_PASSWORD']
Base.metadata.create_all(engine)

init_login(app)
init_admin(app, db_session)


@app.route('/images/<path:path>')
def send_image(path):
    return send_from_directory('static/images', path)


@app.route('/ops/new/card', methods=['POST'])
def new_support_card():
    params = request.get_json()
    uri = params.get('new_card_uri')
    input_password = params.get('root_password')
    if not input_password == root_password:
        return 'field: root_password is missing or do not correct', 401
    if not uri:
Exemplo n.º 10
0
def gunicorn():
    from admin import init_admin
    init_admin(app)

    return app
Exemplo n.º 11
0
def main():
    from admin import init_admin
    init_admin(app)

    app.run(host=settings.HOST, port=settings.PORT, debug=settings.DEBUG)
Exemplo n.º 12
0
def register_plugins(app: Flask) -> Manager:
    "Register all the plugins to Haldis"
    # pylint: disable=W0612
    # Register Airbrake and enable the logrotation
    if not app.debug:
        timedFileHandler = TimedRotatingFileHandler(
            app.config["LOGFILE"], when="midnight", backupCount=100
        )
        timedFileHandler.setLevel(logging.DEBUG)

        loglogger = logging.getLogger("werkzeug")
        loglogger.setLevel(logging.DEBUG)
        loglogger.addHandler(timedFileHandler)
        app.logger.addHandler(timedFileHandler)

        airbrakelogger = logging.getLogger("airbrake")

        # Airbrake
        airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"],
                            api_key=app.config["AIRBRAKE_KEY"])
        # ugly hack to make this work for out errbit
        airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format(  # pylint: disable=W0212
            airbrake.project_id
        )

        airbrakelogger.addHandler(AirbrakeHandler(airbrake=airbrake))
        app.logger.addHandler(AirbrakeHandler(airbrake=airbrake))

    # Initialize SQLAlchemy
    db.init_app(app)

    # Initialize Flask-Migrate
    migrate = Migrate(app, db)
    app_manager = Manager(app)
    app_manager.add_command("db", MigrateCommand)
    app_manager.add_command("runserver", Server(port=8000))

    # Add admin interface
    init_admin(app, db)

    # Init login manager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.anonymous_user = AnonymouseUser
    init_login(app)

    # Add oauth
    zeus = init_oauth(app)
    app.zeus = zeus

    # Load the bootstrap local cdn
    Bootstrap(app)
    app.config["BOOTSTRAP_SERVE_LOCAL"] = True

    # use our own bootstrap theme
    app.extensions["bootstrap"]["cdns"]["bootstrap"] = StaticCDN()

    # Load the flask debug toolbar
    toolbar = DebugToolbarExtension(app)

    # Make cookies more secure
    app.config.update(
        SESSION_COOKIE_HTTPONLY=True,
        SESSION_COOKIE_SAMESITE='Lax',
    )

    if not app.debug:
        app.config.update(SESSION_COOKIE_SECURE=True)

    return app_manager
Exemplo n.º 13
0
#mail
mail = Mail(app)


@app.context_processor
def inject_profiler():
    return dict(profiler_includes=templatetags.profiler_includes())


#register blueprints
from visitor import visitor
from exhibitor import exhibitor
from admin import admin, init_admin

app.register_blueprint(visitor, url_prefix='/visitors')
app.register_blueprint(exhibitor, url_prefix='/exhibitors')
app.register_blueprint(admin, url_prefix='/admin')

# Pull in URL dispatch routes
import urls

# Flask-DebugToolbar (only enabled when DEBUG=True)
# Werkzeug Debugger (only enabled when DEBUG=True)
if app.debug:
    app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)
    toolbar = DebugToolbarExtension(app)
    init_admin()
# GAE Mini Profiler (only enabled on dev server)
app.wsgi_app = profiler.ProfilerWSGIMiddleware(app.wsgi_app)
Exemplo n.º 14
0
    celery.Task = ContextTask

    app.celery = celery
    return celery


security = flask_security.Security()
toolbar = flask_debugtoolbar.DebugToolbarExtension()
migrate = flask_migrate.Migrate()
assets = flask_assets.Environment()
celery = celery_lib.Celery()

assets.init_app(app)
toolbar.init_app(app)
migrate.init_app(app, db)
admin.init_admin(app, db)
make_celery(app, celery)

import tasks

# User model
class ExtendedRegisterForm(flask_security.forms.ConfirmRegisterForm):
    name = wtforms.StringField('Name', [wtforms.validators.Required()])
    organization_name = wtforms.StringField(
        'Organization', [wtforms.validators.Required()])

# Setup Flask-Security
user_datastore = flask_security.SQLAlchemyUserDatastore(
    db, model.User, model.Role)
security._state = security.init_app(
    app, user_datastore,
Exemplo n.º 15
0
import rest
from flask import render_template, request, redirect, jsonify, g
from models import *

import json

app.register_blueprint(blueprints.user_bp, url_prefix='/user')
app.register_blueprint(blueprints.image_bp, url_prefix='/image')
app.register_blueprint(blueprints.video_bp, url_prefix='/video')
app.register_blueprint(blueprints.audio_bp, url_prefix='/audio')
app.register_blueprint(blueprints.shortcut_bp, url_prefix='/shortcut')
app.register_blueprint(blueprints.shortcut_sd, url_prefix='/definitions')

rest.ReSTManager.init_rest(app)

admin.init_admin()


@app.route('/')
def index():
    return render_template('index.html', config=app.config)


@app.route('/statistic')
def statistic():
    worker_accuracy = []
    return render_template('statistic.html', worker_accuracy=worker_accuracy)
    pass


@app.route('/test')