コード例 #1
0
ファイル: application.py プロジェクト: amanchoudhri/bio2bel
def create_application(connection: Optional[str] = None) -> Flask:
    """Create a Flask application."""
    app = Flask(__name__)

    flask_bootstrap.Bootstrap(app)
    Admin(app)

    connection = connection or config.connection
    engine, session = build_engine_session(connection)

    for name, add_admin in add_admins.items():
        url = f'/{name}'
        add_admin(app, session, url=url, endpoint=name, name=name)
        log.debug('added %s - %s to %s', name, add_admin, url)

    app.register_blueprint(ui)

    return app
コード例 #2
0
def create_app_from_config(config):
    """ Create a new application based on the given configuration
    """
    app = flask.Flask(__name__)
    app.cli.add_command(manage.mailu)

    # Bootstrap is used for basic JS and CSS loading
    # TODO: remove this and use statically generated assets instead
    app.bootstrap = flask_bootstrap.Bootstrap(app)

    # Initialize application extensions
    config.init_app(app)
    models.db.init_app(app)
    KVSessionExtension(
        RedisStore(redis.StrictRedis().from_url('redis://{0}/3'.format(
            config['REDIS_ADDRESS']))), app).cleanup_sessions(app)
    utils.limiter.init_app(app)
    utils.babel.init_app(app)
    utils.login.init_app(app)
    utils.login.user_loader(models.User.get)
    utils.proxy.init_app(app)
    utils.migrate.init_app(app, models.db)

    # Initialize debugging tools
    if app.config.get("DEBUG"):
        debug.toolbar.init_app(app)
        # TODO: add a specific configuration variable for profiling
        # debug.profiler.init_app(app)

    # Inject the default variables in the Jinja parser
    # TODO: move this to blueprints when needed
    @app.context_processor
    def inject_defaults():
        signup_domains = models.Domain.query.filter_by(
            signup_enabled=True).all()
        return dict(signup_domains=signup_domains, config=app.config)

    # Import views
    from mailu import ui, internal
    app.register_blueprint(ui.ui, url_prefix='/ui')
    app.register_blueprint(internal.internal, url_prefix='/internal')

    return app
コード例 #3
0
ファイル: server.py プロジェクト: cnetedu/butterflyone
def create_app(config, debug=False, testing=False):

    app = flask.Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    # Configure logging
    if not app.testing:
        logging.basicConfig(level=logging.INFO)

    # Setup the data model.
    with app.app_context():
        # I hate this and need to figure out how to not have the db as a context of things.
        bfly.db.init_app(app)

    # Register our apis
    # app.register_blueprint(bfly.job_match.api.job_match)
    app.register_blueprint(bfly.jobs.api.jobs)
    app.register_blueprint(bfly.majors.api.majors)
    app.register_blueprint(bfly.users.api.users, url_prefix='/users')
    app.register_blueprint(bfly.job_match.api.job_match,
                           url_prefix='/job_match')
    flask_bootstrap.Bootstrap(app)
    from bfly.users import models
    # Add an error handler. This is useful for debugging the live application,
    # however, you should disable the output of the exception for production
    # applications.
    @app.errorhandler(500)
    def server_error(e):
        return """
        An internal error occurred: <pre>{}</pre>
        See logs for full stacktrace.
        """.format(e), 500

    return app
コード例 #4
0
    # Host settings
    'HOST_IMAP': 'imap',
    'HOST_POP3': 'imap',
    'HOST_SMTP': 'smtp',
    'HOST_WEBMAIL': 'webmail',
    'HOST_FRONT': 'front',
    'HOST_AUTHSMTP': os.environ.get('HOST_SMTP', 'smtp'),
    'POD_ADDRESS_RANGE': None
}

# Load configuration from the environment if available
for key, value in default_config.items():
    app.config[key] = os.environ.get(key, value)

# Base application
flask_bootstrap.Bootstrap(app)
db = flask_sqlalchemy.SQLAlchemy(app)
migrate = flask_migrate.Migrate(app, db)
limiter = flask_limiter.Limiter(app, key_func=lambda: current_user.username)

# Debugging toolbar
if app.config.get("DEBUG"):
    import flask_debugtoolbar
    toolbar = flask_debugtoolbar.DebugToolbarExtension(app)

# Profiler
if app.config.get("DEBUG"):
    app.wsgi_app = profiler.ProfilerMiddleware(app.wsgi_app, restrictions=[30])

# Manager commnad
manager = flask_script.Manager(app)
コード例 #5
0
ファイル: __init__.py プロジェクト: ltltlt/better_flask
  > File Name:		__init__.py
  > Created Time:	2016-12-14 Wed 08:36
''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' ''''''

import flask_moment
import os, sys
import flask_bootstrap
import flask_mail
import flask_sqlalchemy
import flask
import flask_login

moment = flask_moment.Moment()
db = flask_sqlalchemy.SQLAlchemy()
mail = flask_mail.Mail()
bootstrap = flask_bootstrap.Bootstrap()
login_manager = flask_login.LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'


def create_app(config_name):
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
    import config

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

    moment.init_app(app)
    db.init_app(app)
コード例 #6
0
import flask_bootstrap as bt
import flask_compress as cmp
from flask import Flask, render_template, redirect, url_for, request
from database import (createDB, getSearchedArticles, getSearchedTweets,
                      getGeneratedTweet, getGeneratedArticle, tech_tweets, tech_articles)

app = Flask(__name__)
cmp.Compress(app)
app.secret_key = b"SECRET_KEY"
bt.Bootstrap(app)


@app.route("/")
def start():
    return redirect(url_for("index"))
    # if it isn't already on index it loads onto index page


@app.route("/index", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        if request.get("new_article") == "Generate new Article":
            # if generate new article button is pressed
            return redirect(url_for("index"))
            # reloads page because it each time it happens a random article is chosen
        if request.get("new_tweet") == "Generate New Tweet":
            return redirect(url_for("index"))
            # reloads the page because each time a new page is loaded a new tweet is loaded anyway

    return render_template("index.html",
                           title=getGeneratedArticle()[0],
コード例 #7
0
ファイル: app.py プロジェクト: wesleyit/python_safesite
import sqlalchemy as db
import flask_bootstrap as fb


commands = []
commands.append('df -h')
commands.append('free -g')
commands.append('uname -a')
commands.append('ps -ef')
commands.append('cat /proc/cpuinfo')
commands.append('mount')
commands.append('netstat -tlnp')
commands.append('iptables -nL')
engine = db.create_engine('sqlite:///database.sqlite')
app = f.Flask('py_vulnerable_site')
fb.Bootstrap(app)


def query(text):
    conn = engine.connect()
    res = conn.execute(text)
    res = res.fetchall()
    return res


def execsql(text):
    conn = engine.connect()
    return conn.execute(text)


def hash(text):
コード例 #8
0
#!venv/bin/python
from flask import Flask
import logging
import sys
import flask_bootstrap

flask_app = Flask(__name__)
flask_app.logger.addHandler(logging.StreamHandler(sys.stdout))
flask_app.logger.setLevel(logging.ERROR)
flask_app.config.from_object('config')
flask_app.config['SECRET_KEY'] = 'super-secret-key-that-noone-can-guess'
bootstrap = flask_bootstrap.Bootstrap(flask_app)
from citycompare import views
コード例 #9
0
import flask
import flask_sqlalchemy
import flask_migrate
import flask_bootstrap
import flask_login
import flask_mail
import flask_moment

import werkzeug

from app import config
# ~ from app import forms

bazadanych = flask_sqlalchemy.SQLAlchemy()
migracje = flask_migrate.Migrate()
stylista = flask_bootstrap.Bootstrap()
zalogowany = flask_login.LoginManager()
wysylacz = flask_mail.Mail()
momencik = flask_moment.Moment()

# ~ from app import models

# ~ aplikacja = flask.Flask( __name__ )
# ~ aplikacja.config.from_object( config.Config )

# ~ bazadanych.init_app( aplikacja )
# ~ migracje.init_app( aplikacja, bazadanych )
# ~ stylista.init_app( aplikacja )
# ~ zalogowany.init_app( aplikacja )

# ~ from app.auth import auth as bp_auth
コード例 #10
0
from sirius.models import db
from sirius.models import user
from sirius.models import hardware
from sirius.models import messages

from sirius.web import landing
from sirius.web import twitter
from sirius.web import login
from sirius.web import admin
from sirius.web import printer_print
from sirius.web import printer_overview
from sirius.web import external_api
from sirius.web import print_key_api

logger = logging.getLogger(__name__)
bootstrap = bootstrap.Bootstrap()
sockets = flask_sockets.Sockets()


def create_app(config_name):
    app = flask.Flask(__name__)
    app.config.from_object(config.config[config_name])
    config.config[config_name].init_app(app)

    # Allow the printkey API to be browser accessible
    CORS(app, resources={r"/printkey/*": {"origins": "*"}})

    # Configure various plugins and logging
    bootstrap.init_app(app)
    db.db.init_app(app)
    sockets.init_app(app)
コード例 #11
0
ファイル: __init__.py プロジェクト: rbnis/Mailu
def create_app_from_config(config):
    """ Create a new application based on the given configuration
    """
    app = flask.Flask(__name__,
                      static_folder='static',
                      static_url_path='/static')
    app.cli.add_command(manage.mailu)

    # Bootstrap is used for error display and flash messages
    app.bootstrap = flask_bootstrap.Bootstrap(app)

    # Initialize application extensions
    config.init_app(app)
    models.db.init_app(app)
    utils.session.init_app(app)
    utils.limiter.init_app(app)
    utils.babel.init_app(app)
    utils.login.init_app(app)
    utils.login.user_loader(models.User.get)
    utils.proxy.init_app(app)
    utils.migrate.init_app(app, models.db)

    app.device_cookie_key = hmac.new(bytearray(app.secret_key, 'utf-8'),
                                     bytearray('DEVICE_COOKIE_KEY', 'utf-8'),
                                     'sha256').digest()
    app.temp_token_key = hmac.new(bytearray(app.secret_key, 'utf-8'),
                                  bytearray('WEBMAIL_TEMP_TOKEN_KEY', 'utf-8'),
                                  'sha256').digest()
    app.srs_key = hmac.new(bytearray(app.secret_key, 'utf-8'),
                           bytearray('SRS_KEY', 'utf-8'), 'sha256').digest()

    # Initialize list of translations
    app.config.translations = {
        str(locale): locale
        for locale in sorted(utils.babel.list_translations(),
                             key=lambda l: l.get_language_name().title())
    }

    # Initialize debugging tools
    if app.config.get("DEBUG"):
        debug.toolbar.init_app(app)
        # TODO: add a specific configuration variable for profiling
        # debug.profiler.init_app(app)

    # Inject the default variables in the Jinja parser
    # TODO: move this to blueprints when needed
    @app.context_processor
    def inject_defaults():
        signup_domains = models.Domain.query.filter_by(
            signup_enabled=True).all()
        return dict(
            signup_domains=signup_domains,
            config=app.config,
        )

    # Jinja filters
    @app.template_filter()
    def format_date(value):
        return utils.flask_babel.format_date(value) if value else ''

    @app.template_filter()
    def format_datetime(value):
        return utils.flask_babel.format_datetime(value) if value else ''

    # Import views
    from mailu import ui, internal, sso
    app.register_blueprint(ui.ui, url_prefix=app.config['WEB_ADMIN'])
    app.register_blueprint(internal.internal, url_prefix='/internal')
    app.register_blueprint(sso.sso, url_prefix='/sso')
    return app
コード例 #12
0
app.config['CSRF_ENABLED'] = True

#load databases
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL',
                                                       "sqllite://")
#app.config['SQLALCHEMY_MIGRATE_REPO'] = os.path.join(os.path.abspath(os.path.split(os.path.dirname(__file__))[0]),'migrations')
app.config['REDIS_URL'] = os.environ.get('REDISTOGO_URL')
db = flask.ext.sqlalchemy.SQLAlchemy(app)

#load secure token
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')

#other flask extensions
sslify = flask_sslify.SSLify(app)  #requires SSL
bcrypt = flaskext.bcrypt.Bcrypt(app)  #password digests
bootstrap = flask_bootstrap.Bootstrap(
    app)  #make bootstrap templates and helpers available.
login_manager = flask.ext.login.LoginManager(app)  #login manager
redis = flask_redis.Redis(app)  #redis

#import models, views and helpers
import einit.views
import einit.models

app.config['status_list'] = einit.models.status_list
app.config['status_map'] = einit.models.status_details

#set login manager options:
login_manager.login_message_category = 'warning'
login_manager.anonymous_user = einit.models.AnonymousUser
login_manager.login_view = "signin"
コード例 #13
0
def create_app_from_config(configApp, configAuth, configMail):
  """ Create a new application based on the given configuration
      - initialises flask app as 'app'
      - adds flask cli management commands: manage.pymailadmin
      - uses bootstrap to load js and css: flask_bootstrap
      - initialises application configuration
      - initialises authentication configuration
      - initialises mail configuration
      - initialises utilities
        - models.db
        - utils.babel
        - utils.limiter
        - utils.login
        - utils.login.user_loader
        - utils.migrate
        - utils.proxy
      - initialises debugging
      - import views
  """

  # Initialise flask framework
  app = flask.Flask(__name__)
  app.cli.add_command(manage.pymailadmin)

  # Bootstrap is used for basic JS and CSS loading
  # TODO: remove this and use statically generated assets instead
  app.bootstrap = flask_bootstrap.Bootstrap(app)

  # Initialise application configuration
  configApp.init_app(app)

  # Initialise authentcation configuration
  configAuth.init_auth(app)

  # Initialise mail configuration
  configMail.init_mail(app)

  # Initialise utility; models
  models.db.init_app(app)
  utils.babel.init_app(app)
  utils.limiter.init_app(app)
  utils.login.init_app(app)
  utils.login.user_loader(models.User.get)
  utils.migrate.init_app(app, models.db)
  utils.proxy.init_app(app)
  
  # Initialize debugging tools
  if app.configApp.get("DEBUG"):
    debug.toolbar.init_app(app)
    if app.configApp.get("DEBUG_WSGI"):
      debug.profiler.init_app(app)

  # Inject the default variables in the Jinja parser
  # TODO: move this to blueprints when needed
  @app.context_processor
  def inject_defaults():
    """ Uses Jinja parser to set signup domain.
        SET VAR: configuration.configMail.MAIL_CONFIG[DOMAIN]
        FOR: app.configMail[MAIL_DOMAIN]
    """
    
    signup_domains = models.Domain.query.filter_by(signup_enabled=True).all()
    return dict(
      signup_domains=signup_domains,
      config=app.configMail
    )

  # Import views
  from pymailadmin import ui, authentication
  app.register_blueprint(ui.ui, url_prefix='/ui')
  app.register_blueprint(authentication.authentication, url_prefix='/authentication')

  return app
コード例 #14
0
ファイル: index.py プロジェクト: arberx/arber-web
import flask_bootstrap
from flask_mail import Mail, Message

# get EMAIL and PASS from environment
EMAIL = os.environ.get("EMAIL")
PASS = os.environ.get("PASS")

arberweb.app.config['MAIL_SERVER'] = 'smtp.gmail.com'
arberweb.app.config['MAIL_PORT'] = 465
arberweb.app.config['MAIL_USERNAME'] = EMAIL
arberweb.app.config['MAIL_PASSWORD'] = PASS
arberweb.app.config['MAIL_USE_TLS'] = False
arberweb.app.config['MAIL_USE_SSL'] = True

# set up bootstap for main route
flask_bootstrap.Bootstrap(arberweb.app)

# set up Flask Mail
mail = Mail(arberweb.app)


@arberweb.app.route('/')
def main_led_route():
    """ Main route, serves index.html """
    return flask.render_template('index.html')


@arberweb.app.route('/consult', methods=["GET"])
def tutor_route():
    """ Route is the entry point for REACT app """
    return flask.render_template('tutor.html')