예제 #1
0
def create_app():
    app = Flask("librium")

    app.secret_key = os.getenv("SECRET_KEY")
    app.config.from_object(os.getenv("CONFIGURATION"))
    app.config["VERSION"] = __version__

    app.jinja_env.add_extension("jinja2.ext.do")

    pony = Pony()
    pony.init_app(app)

    assets.init_app(app)

    @app.route("/favicon.ico")
    def send_favicon():
        return app.send_static_file("img/favicon.ico")

    def url_for_self(**args):
        return url_for(request.endpoint, **dict(request.args, **args))

    app.jinja_env.globals["url_for_self"] = url_for_self
    app.jinja_env.filters["parse_read_arg"] = parse_read_arg

    app.register_blueprint(main.bp)
    app.register_blueprint(book.bp)
    app.register_blueprint(api.bp)
    app.register_blueprint(covers.bp)

    return app
예제 #2
0
def create_app():
    app = Flask(__name__, **CONFIG['FLASK'])
    app.config["SECRET_KEY"] = "vnkdjnfjknfl1232#"
    socketio.init_app(app)

    @app.errorhandler(404)
    def page_not_found(path):
        return app.send_static_file("index.html")

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

    from controllers.game_events_controller import attach_controller as attach_game_controller
    attach_game_controller(socketio)

    from controllers.word_events_controller import attach_controller as attach_word_controller
    attach_word_controller(socketio)

    from controllers.user_events_controller import attach_controller as attach_user_controller
    attach_user_controller(socketio)

    if config.APP_ENV == "development":
        set_sql_debug(True)
    db.generate_mapping(create_tables=True)

    login_manager.init_app(app)
    login_manager.login_view = 'login'

    Pony(app)

    seed_database_for_development()

    return app
예제 #3
0
def setup_app(app):
    Pony(app)

    db.bind(**app.config.get('DB'))
    db.generate_mapping(create_tables=app.config.get('db', 'create_tables'))

    config_oauth(app)
    app.register_blueprint(bp, url_prefix='')
예제 #4
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='dev',
                            PONY={
                                'provider': 'sqlite',
                                'filename': 'flaskr.sqlite',
                                'create_db': True
                            })
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(403, forbidden)
    app.register_error_handler(500, internal_server_error)

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

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

    Pony(app)

    @app.route("/hello")
    def hello():
        return 'Hello, World'

    from . import auth
    app.register_blueprint(auth.bp)

    from . import index
    app.register_blueprint(index.bp)
    app.add_url_rule('/', endpoint='index')

    from . import tournaments
    app.register_blueprint(tournaments.bp)

    from . import jumpers
    app.register_blueprint(jumpers.bp)

    from . import ranking
    app.register_blueprint(ranking.bp)

    @app.context_processor
    def inject_news_feed():
        news_feed = get_news()
        return news_feed

    return app
예제 #5
0
def create_app(config=None):
    app = Flask(__name__)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = TimedRotatingFileHandler('app/logs/application.log',
                                            when="midnight",
                                            backupCount=7)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.DEBUG)
    app.logger.removeHandler(default_handler)
    app.logger.addHandler(file_handler)

    if config is None:
        config = 'config.TestingConfig'
    app.config.from_object(config)

    db.bind(env_json(app.config['PONY']))
    db.generate_mapping(create_tables=True)
    Pony(app)

    login_manager.init_app(app)
    principals.init_app(app)

    fetcher.init_config(env_json(app.config['HTTP_HEADER']))

    engine = engine_from_config(env_json(app.config['SQLALCHEMY']),
                                prefix='sqlalchemy.')
    jobstores = {
        'default':
        SQLAlchemyJobStore(engine=engine,
                           tablename=app.config['JOBSTORES']['default']),
        'service_jobs':
        SQLAlchemyJobStore(engine=engine,
                           tablename=app.config['JOBSTORES']['service_jobs'])
    }
    scheduler.init_config(fetcher)

    scheduler.configure(jobstores=jobstores,
                        executors=app.config['EXECUTORS'],
                        job_defaults=app.config['JOB_DEFAULTS'])
    scheduler.start()

    atexit.register(lambda: scheduler.shutdown())

    from .main import main as main_blueprints, bp_filters

    app.register_blueprint(main_blueprints)
    app.register_blueprint(bp_filters)
    return app
예제 #6
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)

    session.init_app(app)

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

    from .main.models import TASK_ORDER
    tasks.add_task_order(TASK_ORDER)

    db.bind(**app.config['PONY'])
    db.generate_mapping(create_tables=True)
    Pony(app)

    return app
예제 #7
0
def create_app():

    app = Flask(__name__)
    app.config.from_object(Config)
    Pony(app)

    with app.app_context():

        from . import routes

        db.bind(provider='mysql',
                host='0.0.0.0',
                user='******',
                passwd=password,
                db='to_do_app')
        db.generate_mapping(create_tables=True)

        return app
예제 #8
0
def create_app():

    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object(DevelopmentConfig)
    Pony(app)
    login_manager = LoginManager(app)
    login_manager.login_view = 'login'

    with app.app_context():

        from . import routes
        db.bind(**app.config['PONY'])
        db.generate_mapping(create_tables=True)

        @login_manager.user_loader
        def load_user(user_id):
            return db.User.get(id=user_id)

        return app
예제 #9
0
def create_app(test_config=None):
    
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY = os.urandom(16),
        PONY_CONFIG = {
            'provider': 'sqlite',
            'filename': os.path.join(app.instance_path, 'db.sqlite'),
            'create_db': True} 
    )

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

    from . import db
    db.init_app(app)
    db.db.bind(**app.config['PONY_CONFIG'])
    db.db.generate_mapping()

    from flaskapp import orcamentos
    from flaskapp import authentication

    app.register_blueprint(orcamentos.bluep)
    app.register_blueprint(authentication.bluep)
    app.add_url_rule('/', endpoint='index')

    Pony(app)
    login_manager = LoginManager(app)
    login_manager.login_view = 'authentication.login'

    @login_manager.user_loader
    def load_user(user_id):
        return db.db.User.get(id=user_id)

    
    return app
예제 #10
0
def create_app(config_path='config.ProductionConfig'):
    app = Flask(__name__)
    app.config.from_object(config_path)
    app.logger.addHandler(handler)

    bootstrap = Bootstrap(app)
    # extensions
    if app.debug:
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(app)

    # database
    db.bind(**app.config['PONY'])
    db.generate_mapping(create_tables=True)
    Pony(app)

    login_manager.init_app(app)

    app.register_blueprint(users, url_prefix='/users')
    app.register_blueprint(collect, url_prefix='/collection')

    return app
예제 #11
0
def create_app():
    codepetitor = Flask(__name__)
    codepetitor.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

    codepetitor.before_request(auth)

    Pony(codepetitor)
    from codepetitor.models import db

    from codepetitor.blueprints.login.login import blueprint_login
    from codepetitor.blueprints.signup.signup import blueprint_signup
    from codepetitor.blueprints.hub.hub import blueprint_hub
    from codepetitor.blueprints.collaborator.collaborator import blueprint_collaborator

    codepetitor.register_blueprint(blueprint_login, url_prefix='/login')
    codepetitor.register_blueprint(blueprint_signup, url_prefix='/signup')
    codepetitor.register_blueprint(blueprint_hub, url_prefix='/hub')
    codepetitor.register_blueprint(blueprint_collaborator,
                                   url_prefix='/collaborator',
                                   app=socketio)

    socketio.init_app(codepetitor)

    return codepetitor
예제 #12
0
def db_init_app(app):
    """Init Pony in Flask app."""
    Pony(app)
예제 #13
0
파일: index.py 프로젝트: dbvv/cli-crm
             'provider': 'sqlite',
             'filename': 'db.db3',
             'create_db': True,
         }))


@db.on_connect(provider='sqlite')
def sqlite_case_sensitivity(db, connection):
    cursor = connection.cursor()
    cursor.execute('PRAGMA case_sensitive_like = OFF')


db.bind(**api.config['PONY'])
db.generate_mapping(create_tables=True)

Pony(api)


@api.route("/", methods=['GET'])
def index():
    return api.send_static_file('index.html')


@api.route("/user/friends", methods=['GET'])
def get_friends():
    friends = vk_parser.get_friends(request.args.get('user_id'))
    return json.dumps(friends)


api.register_blueprint(contacts_api)
예제 #14
0
from pony.flask import Pony

from config import Config
from db import db as mysql

# flask
flask_app = Flask(__name__)
flask_app.config.from_object(Config)
flask_app.jinja_env.add_extension('jinja2.ext.i18n')

CSRFProtect(flask_app)

# mysql
mysql.bind(**flask_app.config['PONY'])
mysql.generate_mapping()
pony = Pony(flask_app)

# redis
redis = FlaskRedis(flask_app)

babel = Babel(flask_app)


@babel.localeselector
def get_locale():
    locale = request.cookies.get('locale', '')
    if locale:
        return locale
    return request.accept_languages.best_match(
        current_app.config['I18N_LANGUAGES'])
예제 #15
0
def create_app():
    """
	Create the basic Flask application.

	Following the factory patter, this function creates a Flask application an runs it.
	Theoretically, multiple instances could be run, however for this example only
	a single one will.

	Returns:
	app: a flask app object
	"""

    app = Flask(__name__,
                template_folder='templates',
                static_folder='../frontend/public',
                static_url_path='/frontend/public')
    CORS(app)

    # disable native startup logs of Flask
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

    # initialize ORM
    print(' * Initializing database...')
    initialize_db()
    Pony(app)

    print(' * Setting up routes...')
    # error pages
    @app.errorhandler(404)
    def handle_404(error):
        """
		Signal Not Found errors to the client.
		"""
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def handle_500(error):
        """
		Signal internal server errors to the client.
		"""
        return render_template('500.html'), 500

    @app.route('/admin')
    def serve_admin():
        """
		The route which serves the Svelte SPA with the User administration
		widget. The SPA files need to be in a compiled form already and are
		served statically.
		"""
        return send_from_directory(app.static_folder, 'index.html')

    @app.route('/user', methods=['GET', 'POST'])
    def user():
        """
		The basic User route for a simple JSON-CRUD-API. At the moment only supports
		READ all users and CREATE a single user but could be extended easily.

		Returns:
		{data: [User]}: a JSON object containing a list of all users on GET
		or
		{data: User}: a JSON object containing the single user that was just created on POST
		"""
        if request.method == 'GET':
            try:
                with db_session:
                    users = select(u for u in User)[:]
                    return dict(data=[u.dictify() for u in users])
            except Exception as e:
                abort(
                    Response('Error: could not get user list from database.'))
        if request.method == 'POST':
            try:
                body = request.json
                with db_session:
                    u = User(first_name=body['first_name'],
                             last_name=body['last_name'],
                             user_name=body['user_name'],
                             street=body['street'],
                             city=body['city'],
                             zip=body['zip'],
                             telephone=body['telephone'])
                    db.commit()
                    return dict(data=u.dictify())

            except ValueError as err:
                app.logger.error(
                    'Some requirements for user fields are violated:', err)
                abort(Response('Error: Properties for user object invalid'))
            except Exception as err:
                app.logger.error('Error creating user object:', err)
                abort(
                    Response(
                        'Error: Could not create user object in database.'))

    print("""
	*** Please open: localhost:5000/admin in your browser. ***
	""")
    return app
예제 #16
0
    dict(DEBUG=False,
         PONY={
             "provider": "postgres",
             "host": config.get("host", ""),
             "user": config.get("user", ""),
             "password": config.get("password", ""),
             "dbname": config.get("database", "")
         }))

db = Database()
db.bind(**application.config['PONY'])

from bot.models import Stats
db.generate_mapping(create_tables=True)

Pony(application)

if config:
    user = u.User(config.get('host', ''), config.get('database', ''),
                  config.get('user', ''), config.get('password', ''))
    osmbot = OsmBot(config)
    telegram_api = TBot(config['token'])

api = OsmApi()
nom = pynominatim.Nominatim()

osmbot_blueprint = Blueprint('osmbot',
                             __name__,
                             template_folder='templates',
                             static_folder='static')
예제 #17
0
파일: __init__.py 프로젝트: rolixer/Trollo
from flask import Flask
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from pony.flask import Pony
from pony import orm
from config import Config

login = LoginManager()
db = orm.Database()
pony = Pony()
login.login_view = 'auth.login'
login.login_message = "Please log in"
bootstrap = Bootstrap()


def create_app(config_class=Config):
    app = Flask(__name__)

    app.config.from_object(config_class)

    db.bind(app.config['PONY'])

    pony.init_app(app)
    login.init_app(app)
    bootstrap.init_app(app)

    from trollo.main import bp as main_bp
    app.register_blueprint(main_bp)

    from trollo.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')
예제 #18
0
db.generate_mapping(create_tables=True)

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']
    }
})

app = connexion.FlaskApp(__name__, specification_dir='openapi/', debug=True)
app.add_api('spec.yaml', resolver=FixedRestyResolver('endpoints'))
# add pony wrapper on flask views
CORS(app.app)
Pony(app.app)

if __name__ == "__main__":
    app.run(port=8080, host='localhost')
예제 #19
0
from flask import Flask
from pony.flask import Pony
from pony.orm import Database

app = Flask(__name__)
Pony(app)

db = Database()
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)

import views

db.generate_mapping(create_tables=True)
예제 #20
0
        email = input('Email: ').strip()
        password = getpass('Password: '******'First Name(optional): ').strip()
        last_name = input('Last Name(optional): ').strip()
        with db_session:
            created = create_super_user(
                email, decode(bcrypt.generate_password_hash(password),
                              'utf-8'), first_name, last_name)
        if created:
            print('[+] Super user created.')
        else:
            print('[-] Super user already exists.')

    if args.panel:
        option_flag = True
        Pony(panelapp)

        panelapp.run(host=GLOBAL_SETTINGS['panel']['host'],
                     port=GLOBAL_SETTINGS['panel']['port'],
                     debug=GLOBAL_SETTINGS['debug'])

    if args.landpage:
        option_flag = True
        Pony(landapp)

        landapp.run(host=GLOBAL_SETTINGS['landpage']['host'],
                    port=GLOBAL_SETTINGS['landpage']['port'],
                    debug=GLOBAL_SETTINGS['debug'])

    if args.proxy:
        option_flag = True