Example #1
1
def test_gravatar_url():
    """Test that the gravatar url is generated correctly"""
    app = Flask(__name__)

    with app.test_request_context("/"):
        app.debug = True
        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        url = gravatar_url("test@test.com", 200)
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?s=200&d=mm")

        app.debug = False

        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        app.config["SITE_URL"] = "http://www.site.com"

        url = gravatar_url("test@test.com")
        eq_(
            url,
            "http://www.gravatar.com/avatar/"
            "b642b4217b34b1e8d3bd915fc65c4452"
            "?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2Fdefault-avatar.png",
        )
Example #2
1
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class User(object):
        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        name = "name&required&default='world'"
        date_in = {"validater": "datetime", "input": True, "default": datetime.utcnow}
        date_out = "datetime&required&output"
        schema_inputs = {"get": {"name": name}, "get_user": {"name": name}, "post": {"date": date_in}}
        schema_outputs = {
            "get": {"hello": "unicode&required"},
            "get_user": {"user": {"name": name}},
            "post": {"date": date_out},
        }
        output_types = [User]

        def get(self, name):
            return {"hello": name}

        def get_user(self, name):
            return {"user": User(name)}

        def post(self, date):
            return {"date": date}

    api.add_resource(Hello)
    return app
    def setUp(self):
        TB_URI = "http://data.perseus.org/rdfvocab/treebank"

        app = Flask("Nemo")
        app.debug = True
        self.interface = SimpleQuery(
            [
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.1", "treebanks/treebank1.xml", TB_URI),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:1.5", "treebanks/treebank2.xml", TB_URI),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.1", "images/N0060308_TIFF_145_145.tif", "dc:image"),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.2", "images/N0060308_TIFF_145_145.tif", "dc:image")
            ],
            resolver=Resolver(LocalRetriever(path="./tests/test_data/"))
        )
        self.arethusa = Arethusa(queryinterface=self.interface)
        app.debug = True
        nemo = Nemo(
            app=app,
            base_url="",
            retriever=NautilusDummy,
            chunker={"default": lambda x, y: level_grouper(x, y, groupby=30)},
            plugins=[self.arethusa]
        )
        self.interface.process(nemo)
        self.client = app.test_client()
Example #4
0
def get_application(generate_css=True, debug=False):
	app = Flask(__name__,
			template_folder='templates',
			static_folder='static',
			static_url_path='',
	)

	from views.index import index_bp
	app.register_blueprint(index_bp)

	if generate_css:
		# force debug because we don't deploy css
		app.debug = True
		app_dir = os.path.dirname(app.static_folder)
		scss.Scss(app,
				static_dir=app.static_folder,
				asset_dir=os.path.join(app_dir, 'assets')
		)

	app.debug = debug

	@app.context_processor
	def context_globals():
		return dict(
			css=css,
		)

	return app
Example #5
0
    def test_gravatar_url(self):
        """Test that the gravatar url is generated correctly"""
        # Note: We make a fake Flask app for this.
        app = Flask(__name__)

        with app.test_request_context('/'):
            app.debug = True
            url = gravatar_url('test@example.com')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?d=mm')

            url = gravatar_url('test@example.com', 200)
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?s=200&d=mm')

            app.debug = False

            url = gravatar_url('test@example.com')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?d=mm')

            app.config['SITE_URL'] = 'http://www.site.com'

            url = gravatar_url('test@example.com')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0'
                '?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2F'
                'default-avatar.png')
Example #6
0
def start():
    """start the flask service"""

    # create app
    app = Flask(__name__)
    app.debug = True


    #Data comes into this method:
    #'sessionStartTime' is the number of seconds since 1970 when the experiment started
    #'data' is the latest raw data, served up as a csv (each line contains up to 8 channels)
    @app.route('/data', methods=['POST'])
    def saveRatingsToGene():
        print "starting"
        print request.form

        data = request.form['data']
        sessionStartTime = request.form['sessionStartTime']

        #Do we already have a DB entry for this?
        experiment_obj = db.experiments.find_one({"sessionStartTime": sessionStartTime})

        #The data is coming in as a text CSV.
        rows = data.split('\n')
        for row in rows:
            channels = row.split(',')
            #somehow put this data into a mongo object


        return "OK"

    #This server must expose URLs to allow the user to dload the csv from the server
    #Flask gives us what we need to dload files. This sample code might be overly complicated
    #As it is built for streaming large files, which we don't necessarily need
    #http://flask.pocoo.org/docs/patterns/streaming/
    @app.route('/large.csv')
    def generate_large_csv():
        def generate():
            for row in iter_all_rows():
                yield ','.join(row) + '\n'
        return Response(generate(), mimetype='text/csv')

    # This is where we should be able to display a list of all experiments in the mongodb
    # And use them to fill in a template (.tpl file) to allow either dloaded files
    # or perhaps, even visualized on the screen
    # Very excited about this plotting library (if it's easy to implement):
    # http://code.shutterstock.com/rickshaw/
    @app.route('/', methods=['GET'])
    def hello_world():

        experiments = db.experiments.find() #get all

        for experiment in experiments:
            print "Yep we see an experiment"

        print "yep working"


    # let's go!
    app.run()
def create_app(config, debug=False, testing=False, config_overrides=None):
  app = Flask(__name__)
  app.config.from_object(config)

  app.debug = debug
  app.testing = testing

  if config_overrides:
    app.config.update(config_overrides)

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

  #Setup the data model
  with app.app_context():
    model = get_model()
    model.init_app(app)

  from .app import appview
  app.register_blueprint(appview, url_prefix='')

  @app.errorhandler(500)
  def server_error(e):
    return """
    An internal error occurred:<pre>{}</pre>
    """.format(e), 500

  return app
Example #8
0
def app_init(cfg='../config.py'):
    ''' Initialises the flask app. '''

    app        = Flask( __name__, static_folder=os.path.abspath('static'))
    app.register_blueprint(API, url_prefix='/api')
    app.config.from_pyfile(cfg)
    app.debug      =   app.config.get('DEBUG')
    app.secret_key = app.config.get('SECRET_KEY')
    oauth = OAuth()

    '''GOOGLE_CLIENT_ID = conf.GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET = conf.GOOGLE_CLIENT_SECRET
    '''

    google = oauth.remote_app('google',
      base_url='https://www.google.com/accounts/',
      authorize_url='https://accounts.google.com/o/oauth2/auth',
      request_token_url=None,
      request_token_params={
        'scope': 'https://www.googleapis.com/auth/userinfo.email',
        'response_type': 'code'},
      access_token_url='https://accounts.google.com/o/oauth2/token',
      access_token_method='POST',
      access_token_params={'grant_type': 'authorization_code'},
      consumer_key=app.config.get('GOOGLE_CLIENT_ID'),
      consumer_secret=app.config.get('GOOGLE_CLIENT_SECRET'))

    return app, google
Example #9
0
def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    if app.config.from_pyfile("settings.conf", silent=True):
        print "Settings loaded from local instance"
    if app.config.from_envvar("RSVP_CONF", silent=True):
        print "Settings loaded from ENVVAR"
    if app.config["DEBUG"]:
        app.debug = True

    log_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
    root_logger = logging.getLogger("werkzeug")
    if app.config["DEBUG"]:
        root_logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler("{}/{}".format(app.config["LOGDIR"], "rsvp.log"))
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    from extensions import db
    import models
    db.init_app(app)
    models.create_all(app)

    from views import views_bp
    app.register_blueprint(views_bp)
    return app
Example #10
0
def run_flask():
    root_dir = os.path.join(os.getcwd(), 'web')
    app = Flask(__name__, static_folder=root_dir)
    app.use_reloader = False
    app.debug = False
    app.config["SECRET_KEY"] = "OpenPoGoBot"
    socketio = SocketIO(app, logging=False, engineio_logger=False)

    logging_buffer = []

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

    @app.route('/<path:path>')
    def static_proxy(path):
        return app.send_static_file(path)

    @manager.on("logging")
    def logging_event(event_name, output, color):
        line = {"output": output, "color": color}
        logging_buffer.append(line)
        socketio.emit("logging", [line], namespace="/event")

    @socketio.on("connect", namespace="/event")
    def connect():
        emit("logging", logging_buffer, namespace="/event")
        logger.log("Client connected", "yellow", fire_event=False)

    @socketio.on("disconnect", namespace="/event")
    def disconnect():
        logger.log("Client disconnected", "yellow", fire_event=False)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
Example #11
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
Example #12
0
def test_content_type(sign_func):
    responses.add(responses.GET, "https://flask.atlassian.net/")

    app = Flask(__name__)
    app.secret_key = "anything"
    app.debug = True
    backend = MemoryBackend({
        "oauth_token": "faketoken",
        "oauth_token_secret": "fakesecret",
        "oauth_session_handle": "fakehandle",
        "oauth_expires_in": "157680000",
        "oauth_authorization_expires_in": "160272000",
    })
    jira_bp = make_jira_blueprint(
        "https://flask.atlassian.net",
        consumer_key="fakekey",
        backend=backend,
    )
    app.register_blueprint(jira_bp)

    @app.route("/test")
    def api_request():
        jira_bp.session.get("/")
        return "success"

    resp = app.test_client().get("/test")
    headers = responses.calls[0].request.headers
    assert "Content-Type" in headers
    assert headers["Content-Type"] == "application/json"
    def test(config):
        """Test the given Flask configuration. If configured correctly,
        an error will be tracked by Exceptional for your app. Unlike
        the initialized extension, this test will post data to Exceptional,
        regardless of the configured ``DEBUG`` setting.

        :param config: The Flask application configuration object to test.
                       Accepts either :class:`flask.Config` or the object
                       types allowed by :meth:`flask.Config.from_object`.
        """
        context = getattr(stack.top, "exceptional_context", None)
        app = Flask(__name__)
        exceptional = Exceptional()

        if isinstance(config, Config):
            app.config = config
        else:
            app.config.from_object(config)

        assert "EXCEPTIONAL_API_KEY" in app.config
        app.debug = False
        app.testing = False
        exceptional.init_app(app)
        app.testing = True

        @app.route("/exception")
        def exception():
            setattr(stack.top, "exceptional_context", context)
            message = "Congratulations! Your application is configured for Exceptional error tracking."  # NOQA

            raise Exception(message)

        with app.test_client() as client:
            client.get("/exception")
            json.loads(g.exceptional)
Example #14
0
def app(jwt, user):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'super-secret'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(milliseconds=200)

    jwt.init_app(app)

    @jwt.authentication_handler
    def authenticate(username, password):
        if username == user.username and password == user.password:
            return user
        return None

    @jwt.user_handler
    def load_user(payload):
        if payload['user_id'] == user.id:
            return user

    @app.route('/protected')
    @flask_jwt.jwt_required()
    def protected():
        return 'success'

    return app
Example #15
0
def create_api():
    class Hello(Resource):
        schema_inputs = {
            "get": {"name": ("name&required&default='world'", "name")},
            "post_login": {"date": ("date&required", "date")},
        }
        hello = {"hello": "unicode&required"}
        schema_outputs = {
            "get": hello,
            "get_error": hello,
            "post_login": hello,
        }

        def get(self, name):
            return {"hello": name}

        def get_error(self):
            raise ValueError("get_error")

        def post_login(self, date):
            return {"hello": "world"}

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    return api
Example #16
0
def test_config():
    app = Flask(__name__)
    app.config.from_object("testdata.config")
    app.debug = True
    configs = ["resource_json", "permission_json", "auth_header",
               "auth_token_name", "auth_secret", "auth_alg", "auth_exp",
               "resjs_name", "resdocs_name", "bootstrap"]
    bp = Blueprint("blueprint", __name__)
    api_bp = Api(bp)
    api_app = Api(app)
    api_no_app = Api()
    for k in configs:
        key = "API_" + k.upper()
        assert key in app.config
        assert app.config[key] == key
        assert hasattr(api_app, k)
        assert getattr(api_app, k) == key

        assert getattr(api_no_app, k) != key
        # inited with blue_print can't load configs
        assert getattr(api_bp, k) != key

    api_bp.config(app.config)
    for k in configs:
        key = "API_" + k.upper()
        assert getattr(api_bp, k) == key
Example #17
0
def create_app(debug=False):

    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'secret'

    @app.route('/')
    def index():
        doc = BootstrapDocument()
        # add socket-io client to the doc and our custom js.
        doc.scripts.add(script(
            src='//cdn.socket.io/socket.io-1.4.5.js',
            type='text/javascript'),
            script(src='/static/my.js',
                type='text/javascript'))

        doc.body.children.insert(0, Div(h1('Advanced Example'), 
            Div(h3('Flashes'), Div(id='flashes')))) 
        
        # add buttons below the content of the document
        doc.body.add(Button(
            'Table',
            onclick="user_socket.emit('table');"),
            Button('Form',
                onclick="user_socket.emit('form');"))

        return doc.render()


    io.init_app(app)
    user_io.init_io(io)
    return app
Example #18
0
def create_app(config_name):
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    db = SQLAlchemy(app)
    bootstrap = Bootstrap(app)
    moment = Moment(app)
    manager = Manager(app)
    mail = Mail(app)
    migrate = Migrate(app, db)
    manager.add_command('db', MigrateCommand)

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

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api_1_0 import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    return app
Example #19
0
def test_parse_schema():
    hello = {"hello": "safestr&required"}
    sche_inputs = {
        "get": {"name": "name&default='world'"},
        "post_login": {
            "name": "name&default='world'",
            "password": "password&required"
        }
    }
    sche_outputs = {
        "get": hello,
        "post_login": hello
    }

    class Hello(Resource):

        schema_inputs = sche_inputs
        schema_outputs = sche_outputs
        output_types = [Flask]

        def get(self, name):
            pass

        def post_login(self, name, password):
            pass

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    assert Hello.schema_inputs == validater.parse(sche_inputs)
    assert Hello.schema_outputs == validater.parse(sche_outputs)
    assert Hello.output_types == [Flask]
def create_app():
    app = Flask(__name__,
        static_folder=os.path.join(PROJECT_ROOT, 'public'),
        static_url_path='/public')

    app.config.update(os.environ)

    #TODO: read in right hand side from HT config vars
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
    app.config['MONGODB_DB'] = 'flask_security_test'
    app.config['MONGODB_HOST'] = 'localhost'
    app.config['MONGODB_PORT'] = 27017

    app.debug = app.config['X_HT_DEBUG'] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, 
        {'/': os.path.join(os.path.dirname(__file__), 'public') })

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    SecuritySetup(app)

    # import & register blueprints here:
    #===================================
    from hero_tmpl.views.security import security
    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc
    app.register_blueprint(misc)

    return app
Example #21
0
def main():
    app = Flask(__name__)
    app.config.update(DB_CONNECTION_STRING=':memory:', SQLALCHEMY_DATABASE_URI='sqlite://')
    app.debug = True

    injector = Injector([AppModule(app)])
    configure_views(app=app)

    FlaskInjector(app=app, injector=injector)

    client = app.test_client()

    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.post('/', data={'key': 'foo', 'value': 'bar'})
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
Example #22
0
def serve(py_exec=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")

    @app.route("/<name>")
    @app.route("/<name>/<season>/<episode>")
    def redirect_to(name, season=None, episode=None):
        interface = get_interface()
        command = "%s touchandgo.py \"%s\" " % (py_exec, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        command += "--daemon"
        print command
        process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
        sleep(10)
        port = 8888
        return redirect("http://%s:%s" % (interface, port))

    app.debug = True
    app.run(host="0.0.0.0")
Example #23
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
Example #24
0
def app(urs, user):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'super-secret'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(milliseconds=600)
    app.config['JWT_EXPIRATION_LEEWAY'] = timedelta(milliseconds=5)

    urs.init_app(app)

    @app.route('/protected')
    @flask_urs.jwt_required()
    def protected():
        return 'success'

    @app.route("/authorize")
    def authorize():
        return jsonify({
            "access_token": "asdf",
            "refresh_token": "asdf",
            "endpoint": "/endpoint"
        })

    @app.route("/endpoint")
    def endpoint():
        return jsonify(user)

    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    return app
Example #25
0
def create_app(config_name = 'default'):
    app = Flask(__name__, static_folder='static', static_url_path='')
    app.config.from_object(config[config_name])
    app.debug = True
    config[config_name].init_app(app)

    db.init_app(app)

    # attach routes and custom error pages here
    from hacer.api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

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

    # start discovery server
    with app.app_context():
        from discovery import run_discovery_server
        app.discovery_thread = Thread(target=run_discovery_server, kwargs={ "Session": scoped_session(sessionmaker(bind=db.engine)) })
        app.discovery_thread.daemon = True
        app.discovery_thread.start()

    app.before_request(create_before_request(app))
    return app
Example #26
0
File: main.py Project: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

    app.debug = app.config['DEBUG']
    app.secret_key = app.config['SECRET_KEY']

    # init flask extensions
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    app.context_processor(inject_roles)

    # init my modules
    upload.init_app(app)
    filters.init_app(app)
    views.init_app(app)

    # register routes
    app.register_blueprint(views.bp_basic)
    app.register_blueprint(views.bp_responsable)
    app.register_blueprint(views.bp_activite)
    app.register_blueprint(views.bp_brn)

    return app
Example #27
0
def create_app(config, debug=False):
    app = Flask(__name__)
    app.debug = debug
    config_module.init_app(app, config)

    logging.basicConfig(level=logging.DEBUG)

    if app.debug:
        app.config['DEBUG_TB_PROFILER_ENABLED'] = True
        app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
        app.config['DEBUG_TB_PANELS'] = app.config.get('DEBUG_TB_PANELS', [
            'flask_debugtoolbar.panels.versions.VersionDebugPanel',
            'flask_debugtoolbar.panels.timer.TimerDebugPanel',
            'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
            'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
            'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
            'flask_debugtoolbar.panels.template.TemplateDebugPanel',
            'flask_debugtoolbar.panels.logger.LoggingPanel',
            'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
        ])
        app.toolbar = DebugToolbarExtension(app)

    for blueprint in blueprints:
        blueprint.init_app(app)

    if app.debug:
        run_bower_list()

    return app
Example #28
0
def create_app():
    app = Flask(__name__)
    app.debug = os.getenv('DEBUG') == 'True'
    if os.getenv('SENTRY_DSN'):
        sentry = Sentry()
        sentry.init_app(app)
    return app
Example #29
0
def main():
    app = Flask(__name__)
    app.config.update(
        DB_CONNECTION_STRING=':memory:',
        CACHE_TYPE='simple',
        SQLALCHEMY_DATABASE_URI='sqlite://',
    )
    app.debug = True
    injector = init_app(app=app, modules=[AppModule])

    configure_views(app=app, cached=injector.get(Cache).cached)

    post_init_app(app, injector)

    client = app.test_client()

    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.post('/', data={'key': 'foo', 'value': 'bar'})
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
Example #30
0
def app():
    app = Flask(__name__)
    app.debug = True
    app.testing = True

    @app.context_processor
    def expose_current_timestamp():
        return {
            'now': datetime.now(),
        }

    @app.route('/naturalday')
    def naturalday():
        return render_template_string("{{ now|humanize('naturalday') }}")

    @app.route('/naturaltime')
    def naturaltime():
        return render_template_string("{{ now|humanize('naturaltime') }}")

    @app.route('/naturaldelta')
    def naturaldelta():
        return render_template_string("{{ value|humanize('naturaldelta') }}",
                                      value=timedelta(days=7))

    return app