Example #1
1
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_POST_LOGIN_VIEW"] = "/profile"
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            "profile.html",
            content="Profile Page",
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection(),
        )

    return app
Example #2
0
def create_app(_config_file=os.path.join(os.getcwd(), "settings.cfg")):
    # Create Flask app
    global app
    app = Flask("CheshireCat")

    # Load configuration file
    configspec = ConfigObj(os.path.join(os.getcwd(), "configspec.cfg"), list_values=False)
    config = ConfigObj(_config_file, configspec=configspec)
    test = config.validate(Validator(), copy=True)
    for key in config["CORE"]:
        app.config[key] = config["CORE"][key]

    # Change the session interface to be more secure and portalble than the default
    # which is provided by Werkzeug.
    # These break the engine currently. I don't know why.
    # app.session_interface = RedisSignedSessionInterface()
    # app.session_interface = ItsdangerousSessionInterface()

    # Flask-Login manages user sessions for us, but we need to set it up first, so
    # we'll do so here.
    global login_manager
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Initialize CheshireCat
    # Import the views, to apply the decorators which use the global app object.
    from . import views
Example #3
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.testing = True
    app.config["SECRET_KEY"] = "so secret"

    for key, value in config.items():
        app.config[key] = value

    @app.route("/")
    def index():
        return render_template("index.html")

    return app
Example #4
0
def create_app(package_name, settings_override=None):
    app = Flask(package_name)
    app.config.from_object("rtbtc.settings")
    app.config.from_pyfile(
        os.environ.get("SETTINGS_FILE", os.path.join(app.config["BASE_DIR"], "instance", "settings.cfg")), silent=True
    )
    if settings_override:
        for key, value in six.iteritems(settings_override):
            if key.isupper():
                app.config[key] = value

    influxdb.init_app(app)

    return app
def create_app(_config_dir=None, _config_filename="settings.cfg", _configspec_filename="configspec.cfg"):
    # Create Flask app
    global app
    app = Flask("CheshireCat")

    if _config_dir is not None:
        default_config_dirs.insert(0, _config_dir)

    configspec_path = get_first_file_that_exists(default_config_dirs, _configspec_filename)
    config_path = get_first_file_that_exists(default_config_dirs, _config_filename)

    if configspec_path is None:
        raise FileNotFound("configspec", default_config_dirs, _configspec_filename)
    if config_path is None:
        raise FileNotFound("config", default_config_dirs, _config_filename)

    # Load configuration file
    configspec = ConfigObj(configspec_path, list_values=False)
    config = ConfigObj(config_path, configspec=configspec)
    test = config.validate(Validator(), copy=True)
    for key in config["CORE"]:
        app.config[key] = config["CORE"][key]

    # Change the session interface to be more secure and portalble than the default
    # which is provided by Werkzeug.
    # These break the engine currently. I don't know why.
    # app.session_interface = RedisSignedSessionInterface()
    # app.session_interface = ItsdangerousSessionInterface()

    # Flask-Login manages user sessions for us, but we need to set it up first, so
    # we'll do so here.
    global login_manager
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Initialize our database
    dbconfig = config["CORE"]["DATABASE"]
    db = MongoDBWrapper(dbconfig["HOST"], int(dbconfig["PORT"]), dbconfig["DB_NAME"])
    db.init_db()
    if len(db.get_all_users_with_role("administrator")) == 0:
        db.create_user("admin", hash_password("admin"), "admin@example.com", "administrator")

    # Initialize CheshireCat
    # Import the views, to apply the decorators which use the global app object.
    from . import views
Example #6
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.config["SECRET_KEY"] = "secret"
    app.config["SECURITY_POST_LOGIN"] = "/profile"

    try:
        from example.config import Config

        app.config.from_object(Config)
    except ImportError:
        print "Unable to load social configuration file. To run the example " "application you'll need to create a file name `config.py` in " "the example application folder. See the Flask-Social " "documentation for more information"
        sys.exit()

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/login")
    def login():
        if current_user.is_authenticated():
            return redirect("/")

        return render_template("login.html", content="Login Page", form=LoginForm())

    @app.route("/profile")
    @login_required
    def profile():
        return render_template(
            "profile.html",
            content="Profile Page",
            twitter_conn=current_app.social.twitter.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
        )

    return app
Example #7
0
def create_app(config_files=None, envvars_files=None, *envvars, **other):
    app = Flask(__name__)

    for i in iterable(config_files):
        app.config.from_pyfile(i)

    for i in iterable(envvars_files):
        app.config.from_envvar(i)

    for i in iterable(envvars):
        app.config[i] = os.environ[i]

    for key, value in other.items():
        app.config[key] = value

    DB.init_app(app)

    API.init_app(app)

    return app
Example #8
0
def create_app(name, path, settings_override=None, register_security_blueprint=True):
    """Returns a Flask application object"""

    app = Flask(name, instance_relative_config=True)
    app.config.from_object("linkedlist.config")  # public config
    app.config.from_pyfile("config.py", silent=True)  # instance config
    app.config.from_object(settings_override)  # argument override

    # patch in envvar config
    environ_config_override = find_environ_config_vars()
    for key, value in environ_config_override.iteritems():
        app.config[key] = value

    db.init_app(app)
    security.init_app(app, SQLAlchemyUserDatastore(db, User, Role), register_blueprint=register_security_blueprint)
    register_blueprints(app, name, path)

    # create database tables
    with app.app_context():
        db.create_all()

    return app
Example #9
0
def create_app(ignore_exceptions=None, debug=False, **config):
    import os

    app = Flask(__name__)
    app.config["SECRET_KEY"] = os.urandom(40)
    for key, value in config.items():
        app.config[key] = value

    app.debug = debug

    if ignore_exceptions:
        app.config["RAVEN_IGNORE_EXCEPTIONS"] = ignore_exceptions

    @app.route("/an-error/", methods=["GET", "POST"])
    def an_error():
        raise ValueError("hello world")

    @app.route("/capture/", methods=["GET", "POST"])
    def capture_exception():
        try:
            raise ValueError("Boom")
        except:
            current_app.extensions["sentry"].captureException()
        return "Hello"

    @app.route("/message/", methods=["GET", "POST"])
    def capture_message():
        current_app.extensions["sentry"].captureMessage("Interesting")
        return "World"

    @app.route("/login/", methods=["GET", "POST"])
    def login():
        login_user(User())
        return "hello world"

    return app
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + ".ConfigClass")

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object("local_settings")
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [str(translation) for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)

    # Define the User-Roles pivot table
    user_roles = db.Table(
        "user_roles",
        db.Column("id", db.Integer(), primary_key=True),
        db.Column("user_id", db.Integer(), db.ForeignKey("user.id", ondelete="CASCADE")),
        db.Column("role_id", db.Integer(), db.ForeignKey("role.id", ondelete="CASCADE")),
    )

    # Define Role model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        username = db.Column(db.String(50), nullable=True, unique=True)
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())
        password = db.Column(db.String(255), nullable=False, default="")
        reset_password_token = db.Column(db.String(100), nullable=False, default="")
        # Relationships
        roles = db.relationship("Role", secondary=user_roles, backref=db.backref("users", lazy="dynamic"))

    app.User = User

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username == "user007").first():
        user1 = User(
            username="user007",
            email="user007@example.com",
            active=True,
            password=user_manager.hash_password("Password1"),
        )
        user1.roles.append(Role(name="secret"))
        user1.roles.append(Role(name="agent"))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route("/")
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    # The '/profile' page requires a logged-in user
    @app.route("/profile")
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route("/special")
    @roles_required("secret", ["sauce", "agent"])  # Use of @roles_required decorator
    def special_page():
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """
        )

    return app
Example #11
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.openid import OpenID
from flask_mail import Mail

app = Flask(__name__)
try:
    app.config.from_envvar("CONFIG")
except RuntimeError:
    from config import CONFIG, SECRET_KEY

    for key in CONFIG:
        app.config[key] = CONFIG[key]
    app.secret_key = SECRET_KEY

oid = OpenID(app, "/tmp")

db = SQLAlchemy(app)
mail = Mail(app)

import views
Example #12
0
def make_app():
    app = Flask(__name__)
    SSLify(app)

    try:
        app.config.from_object("papertalk.config")
    except:
        app.config["SERVER_NAME"] = "papertalk.org"
        app.config["SESSION_COOKIE_DOMAIN"] = "papertalk.org"
        app.config.from_object("papertalk.config_sample")
        for key, value in app.config.iteritems():
            app.config[key] = os.environ.get(key)

    app.secret_key = app.config["SECRET_KEY"]
    app.config["DEBUG"] = os.environ.get("DEBUG", True)
    app.session_cookie_name = "session"
    sentry = Sentry(app)

    # Function to easily find your assets
    # In your template use <link rel=stylesheet href="{{ static('filename') }}">
    app.jinja_env.globals["static"] = lambda filename: url_for("static", filename=filename)

    @app.before_request
    def before_request():
        g.db = connect_db()

    @app.after_request
    def add_header(response):
        """
        Add headers to both force latest IE rendering engine or Chrome Frame
        """
        response.headers["X-UA-Compatible"] = "IE=Edge,chrome=1"
        return response

    @app.context_processor
    def inject_context():
        try:
            context = {"current_user": current_user}
        except AttributeError:
            context = {"current_user": None}

        context["ga_id"] = app.config["GA_ID"]

        return context

    register_blueprints(app)
    init_login(app)

    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        from logging import FileHandler

        mail_handler = SMTPHandler(
            "127.0.0.1", "server-error@papertalk.org", ["support@papertalk.org"], "Papertalk error"
        )
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

        file_handler = FileHandler("/tmp/papertalk.log")
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler)

    return app
Example #13
0
app = Flask(__name__)


@app.before_first_request
def setup_logging():
    if not app.debug:
        # In production mode, add log handler to sys.stderr.
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)


import cfg

# Set flask config files
for key in cfg.cfg.config.flask_cfg:
    app.config[key] = cfg.cfg.config.flask_cfg[key]

app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# import gnupg

# gpg = gnupg.GPG(gnupghome=cfg.config.pgp_keyring_path)
# Disable strict encoding errors
# gpg.decode_errors = "ignore"

cache = redis.StrictRedis(host=cfg.redis_host, port=cfg.cfg.config.redis.port, db=cfg.cfg.config.redis.db)

compress = Compress(app)  # yay!

init.init(app)
Example #14
0
def create_app(auth_config):
    app = Flask(__name__)
    app.debug = True
    app.config["SECRET_KEY"] = "f\x91yx_\xb0\x8d\x9b!`+h\xf5\xb1x:\xf2\x033\xfd\xb3\x948\x97"
    app.config["SECURITY_REGISTERABLE"] = True

    mail = Mail(app)
    app.extensions["mail"] = mail

    if auth_config:
        for key, value in auth_config.items():
            app.config[key] = value

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        return render_template("index.html", content="Profile Page")

    @app.route("/post_login")
    @login_required
    def post_login():
        return render_template("index.html", content="Post Login")

    @app.route("/http")
    @http_auth_required
    def http():
        return render_template("index.html", content="HTTP Authentication")

    @app.route("/http_custom_realm")
    @http_auth_required("My Realm")
    def http_custom_realm():
        return render_template("index.html", content="HTTP Authentication")

    @app.route("/token")
    @auth_token_required
    def token():
        return render_template("index.html", content="Token Authentication")

    @app.route("/post_logout")
    def post_logout():
        return render_template("index.html", content="Post Logout")

    @app.route("/post_register")
    def post_register():
        return render_template("index.html", content="Post Register")

    @app.route("/admin")
    @roles_required("admin")
    def admin():
        return render_template("index.html", content="Admin Page")

    @app.route("/admin_and_editor")
    @roles_required("admin", "editor")
    def admin_and_editor():
        return render_template("index.html", content="Admin and Editor Page")

    @app.route("/admin_or_editor")
    @roles_accepted("admin", "editor")
    def admin_or_editor():
        return render_template("index.html", content="Admin or Editor Page")

    @app.route("/unauthorized")
    def unauthorized():
        return render_template("unauthorized.html")

    @app.route("/coverage/add_role_to_user")
    def add_role_to_user():
        ds = app.security.datastore
        u = ds.find_user(email="joe@lp.com")
        r = ds.find_role("admin")
        ds.add_role_to_user(u, r)
        return "success"

    @app.route("/coverage/remove_role_from_user")
    def remove_role_from_user():
        ds = app.security.datastore
        u = ds.find_user(email="matt@lp.com")
        ds.remove_role_from_user(u, "admin")
        return "success"

    @app.route("/coverage/deactivate_user")
    def deactivate_user():
        ds = app.security.datastore
        u = ds.find_user(email="matt@lp.com")
        ds.deactivate_user(u)
        return "success"

    @app.route("/coverage/activate_user")
    def activate_user():
        ds = app.security.datastore
        u = ds.find_user(email="tiya@lp.com")
        ds.activate_user(u)
        return "success"

    @app.route("/coverage/invalid_role")
    def invalid_role():
        ds = app.security.datastore
        try:
            ds.find_role("bogus")
        except RoleNotFoundError:
            return "success"

    return app
Example #15
0
def create_app(config="/application.json"):
    global app

    # initialize our flask application
    app = Flask(__name__, static_folder="../static", static_url_path="/static")

    # set our template path and configs
    app.jinja_loader = FileSystemLoader(os.path.join(root, "templates"))
    config_vars = json.load(open(root + config))
    # merge the public and private keys
    public = list(six.iteritems(config_vars["public"]))
    private = list(six.iteritems(config_vars["private"]))
    config_vars = dict(private + public)
    for key, val in config_vars.items():
        app.config[key] = val
    app.config["github"] = dict(
        consumer_key=app.config["github_consumer_key"],
        consumer_secret=app.config["github_consumer_secret"],
        request_token_params={"scope": "user:email"},
        base_url="https://api.github.com/",
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://github.com/login/oauth/access_token",
        authorize_url="https://github.com/login/oauth/authorize",
    )
    app.config["twitter"] = dict(
        consumer_key=app.config["twitter_consumer_key"],
        consumer_secret=app.config["twitter_consumer_secret"],
        base_url="https://api.twitter.com/1.1/",
        request_token_url="https://api.twitter.com/oauth/request_token",
        access_token_url="https://api.twitter.com/oauth/access_token",
        authorize_url="https://api.twitter.com/oauth/authenticate",
    )
    app.config["google"] = dict(
        consumer_key=app.config["google_consumer_key"],
        consumer_secret=app.config["google_consumer_secret"],
        request_token_params={"scope": "email profile"},
        base_url="https://www.googleapis.com/oauth2/v1/",
        request_token_url=None,
        access_token_method="POST",
        access_token_url="https://accounts.google.com/o/oauth2/token",
        authorize_url="https://accounts.google.com/o/oauth2/auth",
    )

    # add the debug toolbar if we're in debug mode...
    if app.config["DEBUG"]:
        from flask_debugtoolbar import DebugToolbarExtension

        DebugToolbarExtension(app)
        app.logger.handlers[0].setFormatter(
            logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(filename)s:%(lineno)d]")
        )

    # register all our plugins
    db.init_app(app)
    lm.init_app(app)
    oauth_lib.init_app(app)

    # Setup the anonymous user to register a single role
    class AnonymousUser(object):
        id = -100
        gh_token = None
        tw_token = None
        go_token = None

        def is_anonymous(self):
            return True

        def global_roles(self):
            return ["anonymous"]

        def is_authenticated(self):
            return False

        def get(self):
            return self

    lm.anonymous_user = AnonymousUser

    # Route registration
    # =========================================================================
    from . import api, views, oauth, models, monkey_patch

    app.register_blueprint(api.api, url_prefix="/api")
    app.register_blueprint(views.main)

    # tell the session manager how to access the user object
    @lm.user_loader
    def user_loader(id):
        try:
            return models.User.query.filter_by(id=id).one()
        except sqlalchemy.orm.exc.NoResultFound:
            return None

    return app
Example #16
0
#!/usr/bin/env python

from base64 import b64encode
from datetime import datetime, timedelta
from json import dumps
from os import environ
from uuid import uuid4
import hmac
import sha

from flask import Flask, render_template, jsonify

app = Flask(__name__)
for key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_S3_BUCKET_URL"):
    app.config[key] = environ[key]


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/params")
def params():
    def make_policy():
        policy_object = {
            "expiration": (datetime.now() + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
            "conditions": [
                {"bucket": "ajax-cors-s3-upload"},
                {"acl": "public-read"},
                ["starts-with", "$key", "uploads/"],
Example #17
0
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + ".ConfigClass")

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object("local_settings")
    except:
        pass

    # Over-write app config                         # For automated tests
    if test_config:
        for key, value in test_config.items():
            app.config[key] = value

    # Setup Flask-Mail, Flask-Babel and Flask-SQLAlchemy
    app.mail = Mail(app)
    app.babel = babel = Babel(app)
    app.db = db = SQLAlchemy(app)

    @babel.localeselector
    def get_locale():
        translations = [str(translation) for translation in babel.list_translations()]
        return request.accept_languages.best_match(translations)

    # Define User model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=True, unique=True)
        password = db.Column(db.String(255), nullable=False, default="")
        username = db.Column(db.String(50), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())
        reset_password_token = db.Column(db.String(100), nullable=False, default="")

    app.User = User

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)  # Select database adapter
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # The '/' page is accessible to anyone
    @app.route("/")
    def home_page():
        if current_user.is_authenticated():
            return profile_page()
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    # The '/profile' page requires a logged-in user
    @app.route("/profile")
    @login_required  # Use of @login_required decorator
    def profile_page():
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
                <h2>{%trans%}Profile Page{%endtrans%}</h2>
                <p> {%trans%}Hello{%endtrans%}
                    {{ current_user.username or current_user.email }},</p>
                <p> <a href="{{ url_for('user.change_username') }}">
                    {%trans%}Change username{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.change_password') }}">
                    {%trans%}Change password{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                    {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    return app
Example #18
0
TEXTURE_EXTENSIONS = set(["jpg", "jpeg", "png"])

app = Flask(__name__)
app.debug = "DEBUG" in os.environ

app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

app.config["TEXTURE_DIR"] = TEXTURE_DIR
app.config["BITS_DIR"] = BITS_DIR
app.config["TEMP_DIR"] = TEMP_DIR
app.config["COMPOSITION_DIR"] = COMPOSITION_DIR
app.config["TEXTURE_EXTENSIONS"] = TEXTURE_EXTENSIONS

for key in ["MONGODB_HOST", "MONGODB_PORT", "MONGODB_DB", "MONGODB_USERNAME", "MONGODB_PASSWORD"]:
    if key in os.environ:
        app.config[key] = os.environ[key]


def register_blueprints():
    # Prevent circular imports.
    from views import textures

    app.register_blueprint(textures)


register_blueprints()


@app.route("/")
def index():
    return "Hello world!"
Example #19
0
from logging.handlers import SMTPHandler

credentials = None

mysql = MySQL()
# create our little application :)

app = Flask(__name__)

# Managing Bills Position
UPLOAD_FOLDER = "bills/"
ALLOWED_EXTENSIONS = set(["pdf", "png", "tiff", "jpg", "jpeg", "gif"])
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

for key in config:
    app.config[key] = config[key]

mail = Mail(app)
# Mail
mail.init_app(app)

if MAIL_USERNAME or MAIL_PASSWORD:
    credentials = (MAIL_USERNAME, MAIL_PASSWORD)
    mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), "no-reply@" + MAIL_SERVER, ADMINS, "resetpass", credentials)
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

mysql.init_app(app)
app.config.from_object(__name__)

Example #20
0
_THEMES_PATH = os.path.join(app.config.root_path, "themes")

DEBUG = False
PRESENTATIONS_PATHS = [os.path.join(app.config.root_path, "presentations")]
THEMES_PATHS = [_THEMES_PATH]
SECRET_KEY = "secret_key_that_must_be_changed"


app.config.from_object(__name__)
app.config.from_pyfile(os.path.expanduser(os.path.join("~", ".config", "bobslide")), silent=True)
app.config.from_envvar("BOBSLIDE_SETTINGS", silent=True)

# Turn relative paths into absolute for variables coming from the config file
for key in ("PRESENTATIONS_PATHS", "THEMES_PATHS"):
    app.config[key] = [os.path.join(app.config.root_path, os.path.expanduser(path)) for path in app.config[key]]


class MetaHTMLParser(HTMLParser):
    """Retrieve the name of theme in the file meta.html."""

    def __init__(self, *args, **kwargs):
        super(MetaHTMLParser, self).__init__(*args, **kwargs)
        self._active_tag = None
        self.theme = None
        self.title = None

    def handle_starttag(self, tag, attrs):
        self._active_tag = tag
        if tag == "meta" and dict(attrs).get("name") == "theme":
            meta_theme = dict(attrs).get("content")
Example #21
0

import_folder(folder_name="bands", base_path=project_root)

app = Flask(__name__)
app.config.from_pyfile("app.cfg")

for key in app.config.keys():
    if os.environ.has_key(key):
        type_of_config = type(app.config[key])
        if type_of_config is bool:
            if os.environ[key] == "False":
                app.config[key] = False
            else:
                app.config[key] = True
        elif type_of_config is int:
            app.config[key] = int(os.environ[key])
        else:
            app.config[key] = os.environ[key]

oauth = OAuth()

facebook = oauth.remote_app(
    "facebook",
    base_url="https://graph.facebook.com/",
    request_token_url=None,
    access_token_url="/oauth/access_token",
    authorize_url="https://www.facebook.com/dialog/oauth",
    consumer_key=app.config["FACEBOOK_APP_ID"],
    consumer_secret=app.config["FACEBOOK_APP_SECRET"],
    request_token_params={"scope": "email"},
Example #22
0
ALLOWED_EXTENSIONS = set(["jpg", "jpeg", "png", "gif", "bmp"])

flask_app = Flask(__name__)
flask_app.config.from_object("config")
flask_app.debug = os.getenv("DEBUG") == "True"
for key in (
    "AWS_SEEDOKU_WRITE_KEY",
    "AWS_SEEDOKU_WRITE_SECRET",
    "AWS_S3_BUCKET_URL",
    "AWS_SEEDOKU_READ_KEY",
    "AWS_SEEDOKU_READ_SECRET",
    "AWS_SEEDOKU_S3_BUCKET",
    "CELERY_BROKER_URL",
    "CELERY_RESULT_BACKEND",
):
    flask_app.config[key] = environ[key]

celery_app = make_celery(flask_app)

su = Sudoku()

seedoku = SeedokuTask(flask_app.config, "SVM.p.gz")


@celery_app.task(name="tasks.async_image_to_puzzle")
def async_image_to_puzzle(key):
    return seedoku.aws_upload_key_to_puzzle(key)


@flask_app.route("/", methods=["GET", "POST"])
def upload_to_s3():
Example #23
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.config["SECRET_KEY"] = "secret"
    app.config["TESTING"] = True

    for key, value in config.items():
        app.config[key] = value

    mail = Mail(app)
    app.extensions["mail"] = mail

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        return render_template("index.html", content="Profile Page")

    @app.route("/post_login")
    @login_required
    def post_login():
        return render_template("index.html", content="Post Login")

    @app.route("/http")
    @http_auth_required
    def http():
        return "HTTP Authentication"

    @app.route("/http_custom_realm")
    @http_auth_required("My Realm")
    def http_custom_realm():
        return render_template("index.html", content="HTTP Authentication")

    @app.route("/token")
    @auth_token_required
    def token():
        return render_template("index.html", content="Token Authentication")

    @app.route("/multi_auth")
    @auth_required("session", "token", "basic")
    def multi_auth():
        return render_template("index.html", content="Session, Token, Basic auth")

    @app.route("/post_logout")
    def post_logout():
        return render_template("index.html", content="Post Logout")

    @app.route("/post_register")
    def post_register():
        return render_template("index.html", content="Post Register")

    @app.route("/admin")
    @roles_required("admin")
    def admin():
        return render_template("index.html", content="Admin Page")

    @app.route("/admin_and_editor")
    @roles_required("admin", "editor")
    def admin_and_editor():
        return render_template("index.html", content="Admin and Editor Page")

    @app.route("/admin_or_editor")
    @roles_accepted("admin", "editor")
    def admin_or_editor():
        return render_template("index.html", content="Admin or Editor Page")

    @app.route("/unauthorized")
    def unauthorized():
        return render_template("unauthorized.html")

    @app.route("/coverage/add_role_to_user")
    def add_role_to_user():
        u = ds.find_user(email="joe@lp.com")
        r = ds.find_role("admin")
        ds.add_role_to_user(u, r)
        return "success"

    @app.route("/coverage/remove_role_from_user")
    def remove_role_from_user():
        u = ds.find_user(email="matt@lp.com")
        ds.remove_role_from_user(u, "admin")
        return "success"

    @app.route("/coverage/deactivate_user")
    def deactivate_user():
        u = ds.find_user(email="matt@lp.com")
        ds.deactivate_user(u)
        return "success"

    @app.route("/coverage/activate_user")
    def activate_user():
        u = ds.find_user(email="tiya@lp.com")
        ds.activate_user(u)
        return "success"

    @app.route("/coverage/invalid_role")
    def invalid_role():
        return "success" if ds.find_role("bogus") is None else "failure"

    return app
Example #24
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.config["SECRET_KEY"] = "secret"

    app.config.from_object(TestConfig)
    app.config.from_envvar("PROJECT_SETTINGS", silent=True)
    app.config.from_pyfile("local_settings.py", silent=True)

    for key, value in config.items():
        app.config[key] = value

    app.template_folder = os.path.join(os.path.abspath(__file__ + "/../../../../"), "templates")

    mail = Mail(app)
    app.extensions["mail"] = mail

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @login_required
    def profile():
        return render_template("index.html", content="Profile Page")

    @app.route("/post_login")
    @login_required
    def post_login():
        return render_template("index.html", content="Post Login")

    @app.route("/http")
    @http_auth_required
    def http():
        return "HTTP Authentication"

    @app.route("/http_custom_realm")
    @http_auth_required("My Realm")
    def http_custom_realm():
        return render_template("index.html", content="HTTP Authentication")

    @app.route("/token")
    @auth_token_required
    def token():
        return render_template("index.html", content="Token Authentication")

    @app.route("/post_logout")
    def post_logout():
        return render_template("index.html", content="Post Logout")

    @app.route("/post_register")
    def post_register():
        return render_template("index.html", content="Post Register")

    @app.route("/admin")
    @roles_required("admin")
    def admin():
        return render_template("index.html", content="Admin Page")

    @app.route("/admin_and_editor")
    @roles_required("admin", "editor")
    def admin_and_editor():
        return render_template("index.html", content="Admin and Editor Page")

    @app.route("/admin_or_editor")
    @roles_accepted("admin", "editor")
    def admin_or_editor():
        return render_template("index.html", content="Admin or Editor Page")

    @app.route("/unauthorized")
    def unauthorized():
        return render_template("unauthorized.html")

    @app.route("/coverage/add_role_to_user")
    def add_role_to_user():
        u = ds.find_user(email="joe@lp.com")
        r = ds.find_role("admin")
        ds.add_role_to_user(u, r)
        return "success"

    @app.route("/coverage/remove_role_from_user")
    def remove_role_from_user():
        u = ds.find_user(email="matt@lp.com")
        ds.remove_role_from_user(u, "admin")
        return "success"

    @app.route("/coverage/deactivate_user")
    def deactivate_user():
        u = ds.find_user(email="matt@lp.com")
        ds.deactivate_user(u)
        return "success"

    @app.route("/coverage/activate_user")
    def activate_user():
        u = ds.find_user(email="tiya@lp.com")
        ds.activate_user(u)
        return "success"

    @app.route("/coverage/invalid_role")
    def invalid_role():
        return "success" if ds.find_role("bogus") is None else "failure"

    def _get_imported_stuff_by_path(path):
        mo_pa = path.split(".")
        module_name = ".".join(mo_pa[:-1])
        objNam = mo_pa[-1]
        module = __import__(module_name, fromlist=[objNam])

        return module, objNam

    def _bind_extensions(app):
        for ext_path in app.config.get("EXTENSIONS", []):
            module, e_name = _get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, "init_app", False):
                ext.init_app(app)
            else:
                ext(app)

    def _register_context_processors(self):
        for processor_path in app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = _get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in app.config.get("BLUEPRINTS", []):
            module, b_name = _get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))

    _bind_extensions(app)
    _register_blueprints(app)
    _register_context_processors(app)

    return app
Example #25
0
    environment = os.environ["FLASK_ENV"].title()
    app.config.from_object(".".join(["config", environment]))
except KeyError:
    app.config.from_object(".".join(["config", DEFAULT_ENV]))


try:
    # Load the JSON preferences
    preferences_path = os.path.join(app.config["ROOT"], "preferences.json")
    with open(preferences_path) as preferences_file:
        preferences = json.load(preferences_file)
except (ValueError, IOError):
    preferences = {"INSTALL_TYPE": "full"}

for key, value in preferences.items():
    app.config[key] = value

"""
===============
Database Set Up
===============
"""

from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)
from app.models import *

"""
Authentication setup
"""
Example #26
0
def init(config):
    global app
    global babel
    global login_manager
    global db

    # Main application object
    app = Flask(__name__)
    if config is None:
        app.config.from_pyfile("config.cfg")
    else:
        for key in config:
            app.config[key] = config[key]

    # Load any environment-specific configuration file
    if os.environ.get("ONOC_CONFIG") is not None:
        app.config.from_envvar("ONOC_CONFIG")

    # Logging
    logfile = app.config.get("LOGGING", None)
    if logfile is not None:
        import logging

        handler = logging.FileHandler(logfile)
        handler.level = logging.DEBUG
        app.logger.addHandler(handler)

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Babel
    babel = Babel(app)

    @babel.localeselector
    def babel_locateselector():
        # Fall back to configuration
        return None

    @babel.timezoneselector
    def babel_timezoneselector():
        # Fall back to configuration
        return None

    # Livestatus connector
    if app.config.get("LIVESTATUS_SOCKET", None) is not None:
        livestatus.set_server_address(app.config["LIVESTATUS_SOCKET"])
    else:
        livestatus.set_server_address(
            (app.config.get("LIVESTATUS_HOST", "127.0.0.1"), int(app.config.get("LIVESTATUS_PORT", 50000)))
        )

    # Security session manager
    login_manager = LoginManager()
    login_manager.init_app(app, add_context_processor=True)
    login_manager.login_message = gettext("Please log in to access this page")
    login_manager.login_view = "login"

    # A useful route converter that filters a URL using a regular expression
    # It can be used like this in a rule : blah/<regex([a-z]):data>
    class RegexConverter(BaseConverter):
        def __init__(self, map, *items):
            super(RegexConverter, self).__init__(map)
            self.regex = items[0]

    app.url_map.converters["regex"] = RegexConverter

    # Assets manager
    # assets = Environment(app)
    # register_all(app, assets)

    # Include views
    import user  # User management (incl. login)
    import grapher  # Graph screens (logical & physical)
    import dashboard  # Dashboard page
    import widgetsloader  # Dashboard widgets tools
    import structureservice
    import graphiteservice  # Graphites services
    import livestatusservice  # Livestatus services
    import predictservice  # predictation tools
    import reports  # logs screens

    # Starting point
    @app.route("/")
    @login_required
    def index():
        return render_template("main.html")

    init_db(user.User)