Beispiel #1
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 app(request):
    app = Flask(__name__)

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

    JWTManager(app)

    @app.route('/jwt', methods=['POST'])
    def create_token_endpoint():
        access_token = create_jwt('username')
        return jsonify(jwt=access_token)

    @app.route('/protected')
    @jwt_required
    def protected():
        return jsonify(foo='bar')

    @app.route('/optional')
    @jwt_optional
    def optional():
        if get_jwt_identity():
            return jsonify(foo='bar')
        else:
            return jsonify(foo='baz')

    return app
Beispiel #3
0
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/profile'

    from tests.test_app.config import Config
    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
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
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

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

    return app
Beispiel #6
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
Beispiel #7
0
def create_app(config):
    app = Flask(__name__)

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

    database.init_app(app)

    from flask_musers import MUsers
    MUsers(app)

    # register blueprints
    from flask_musers.views import musers
    app.register_blueprint(musers)

    return app
Beispiel #8
0
def create_app(auth_config):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'secret'
    
    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('/login')
    def login():
        return render_template('login.html', content='Login Page', form=LoginForm())
    
    @app.route('/custom_login')
    def custom_login():
        return render_template('login.html', content='Custom Login Page', form=LoginForm())
    
    @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('/post_logout')
    def post_logout():
        return render_template('index.html', content='Post Logout')
    
    @app.route('/admin')
    @roles_required('admin')
    def admin():
        return render_template('index.html', content='Admin Page')
    
    @app.route('/admin_or_editor')
    @roles_accepted('admin', 'editor')
    def admin_or_editor():
        return render_template('index.html', content='Admin or Editor Page')
    
    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
Beispiel #10
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
Beispiel #11
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
Beispiel #12
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
Beispiel #13
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
Beispiel #14
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/"],
                { "success_action_status": "201" }
            ]
Beispiel #15
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)
Beispiel #16
0
TEMP_DIR = os.path.dirname(os.path.abspath(__file__)) + '/temp'
BITS_DIR = os.path.dirname(os.path.abspath(__file__)) + '/static/bits'
COMPOSITION_DIR = os.path.dirname(os.path.abspath(__file__)) + '/static/compositions'
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!'

Beispiel #17
0
import init

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!
Beispiel #18
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 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)
        # Flask-User fields
        active = db.Column(db.Boolean(), nullable=False, default=False)
        email = db.Column(db.String(255), nullable=False, default='')
        password = db.Column(db.String(255), nullable=False, default='')
        # Application fields
        first_name = db.Column(db.String(50), nullable=False, default='')
        last_name = db.Column(db.String(50), nullable=False, default='')
        # Relationships
        roles = db.relationship('Role', secondary=user_roles,
                backref=db.backref('users', lazy='dynamic'))

    # Reset all the database tables
    db.create_all()

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

    # 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.first_name }},</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
Beispiel #19
0
from run_celery import make_celery
from SeedokuCeleryTask import SeedokuTask
from celery.exceptions import TimeoutError


_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
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():
Beispiel #20
0
import config
from flask import Flask, redirect, url_for,render_template
__author__="Hassan"
__date__ ="$Sep 24, 2014 1:55:19 PM$"
#__name__ = 'mhreader_app'
app = Flask(__name__)
print __name__
mode = 'local'
DB_CONFIG = {}
if mode=='local':
    DB_CONFIG = config.LOCAL_DB
else:
    DB_CONFIG = config.REMOTE_DB

for key in DB_CONFIG:
    app.config[key] = DB_CONFIG[key]
#app.config['APPLICATION_ROOT'] = config.APPLICATION_ROOT
#app.config['SERVER_NAME'] = config.SERVER_NAME
app.config['IP_ADDRESS'] = config.IP_ADDRESS
app.config['PORT'] = config.PORT
print app.config['APPLICATION_ROOT'], app.config['PORT']

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

from models import *


from mhreader import mhreader, views
print app.config['APPLICATION_ROOT'], app.config['SERVER_NAME']
app.register_blueprint(mhreader.mhrbp, url_prefix='%s%s'%(config.APPLICATION_ROOT, '/mhreader'))
Beispiel #21
0
import hashlib
import os


_ROOT = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
auth_users = {}


with contextlib.nested(open(os.path.join(_ROOT, 'credentials.txt'), 'r'),
                       open(os.path.join(_ROOT, 'logs/%s.log'% \
                               datetime.strftime(datetime.now(), '%m-%d-%Y')), 'a+')) as (credentials_file, log_file):
    for line in credentials_file:
        if line[:len('MONGODB')] == 'MONGODB':
            key, value = line.strip().split('=')
            app.config[key] = value

            log_file.write('(%s) [+] app.config[%s]=%s\n' % (datetime.now(), key, value))


with contextlib.nested(open(os.path.join(_ROOT, 'users.txt'), 'r'),
                       open(os.path.join(_ROOT, 'logs/%s.log'% \
                               datetime.strftime(datetime.now(), '%m-%d-%Y')), 'a+')) as (users_file, log_file):
    for line in users_file:
        if '=' in line:
            key, value = line.strip().split('=')
            auth_users[key] = hashlib.sha1(value).hexdigest()
            log_file.write('(%s) [+] %s:%s to authorized users\n' % \
                            (datetime.now(), key, hashlib.sha1(value).hexdigest()))

def is_default():
Beispiel #22
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
Beispiel #23
0
    full_path = os.path.join(base_path, folder_name)
    folder = os.path.abspath(full_path)
    sys.path.insert(0, folder)


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"],
Beispiel #24
0
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')
Beispiel #25
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
Beispiel #26
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
Beispiel #27
0
import os,binascii
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
from flaskext.mysql import MySQL
from config import config, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD

app = Flask(__name__)

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

mysql = MySQL()

def get_cursor():
	return mysql.connect().cursor()

def logintest():
	db = get_cursor()
	for i in range(1,100):
		EmpID=i
		UserName = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)])
		Password = binascii.b2a_hex(os.urandom(15))
		Occupation = i%5
		sql = 'insert into Login values ("%s","%s",MD5("%s"),"%s")'
		db.execute(sql%(EmpID,UserName,Password,Occupation))
		db.execute("Commit")

logintest()
Beispiel #28
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():
        return request.accept_languages.best_match(['en', 'nl'])

    # 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
Beispiel #29
0
import docker


# Create application
app = Flask(__name__)

default_config = {
    'SQLALCHEMY_DATABASE_URI': 'sqlite:////data/freeposte.db',
    'SQLALCHEMY_TRACK_MODIFICATIONS': False,
    'SECRET_KEY': 'changeMe',
    'DOCKER_SOCKET': 'unix:///var/run/docker.sock',
    'DEBUG': False
}

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

# Setup components
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = flask_login.LoginManager()
login_manager.init_app(app)

# Connect to the Docker socket
dockercli = docker.Client(base_url=app.config['DOCKER_SOCKET'])

# Finally setup the blueprint
from freeposte import admin
app.register_blueprint(admin.app, url_prefix='/admin')
Beispiel #30
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'secret'

    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('/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