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("*****@*****.**") eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm") url = gravatar_url("*****@*****.**", 200) eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?s=200&d=mm") app.debug = False url = gravatar_url("*****@*****.**") eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm") app.config["SITE_URL"] = "http://www.site.com" url = gravatar_url("*****@*****.**") eq_( url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452" "?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2Fdefault-avatar.png", )
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.register_blueprint(main_blueprint) Misaka(app, tables=True, wrap=True) cache.init_app(app) return app
def create_app(database): global app # create our little application :) app = Flask(__name__) app.config.from_object(config) app.secret_key = config.SECRET_KEY # db import from libs.db import init_connection # db setup if database: init_connection(database) # presenters from presenters.home import home # register modules app.register_blueprint(home) # template filters @app.template_filter('test_format') def test_format(input): return input[::-1] return app
def setUp(self): self.engine = Engine("op1", "op2") self.engine.op1.setup(in_name="in", out_name="middle", required=False) self.engine.op2.setup(in_name="middle", out_name="out") self.engine.op1.set(OptProductEx()) foisdouze = OptProductEx("foisdouze") foisdouze.force_option_value("factor", 12) self.engine.op2.set(foisdouze, OptProductEx()) egn_view = EngineView(self.engine, name="my_egn") egn_view.add_input("in", Numeric(vtype=int, min=-5, max=5)) egn_view.add_input("middle", Numeric(vtype=int)) print(self.engine.needed_inputs()) egn_view.add_output("in") egn_view.add_output("middle") egn_view.add_output("out") api = ReliureAPI() api.register_view(egn_view) app = Flask(__name__) app.config['TESTING'] = True app.register_blueprint(api, url_prefix="/api") self.app = app.test_client()
def create_app(name='davesite', configuration='Default'): """ Overview: Factory method that is responsible for the following. Returns the configured Flask app object. * Reading the configuration. The configuration is kept in config.py * Registering the blueprints. Any blueprints to be added to the application are be added here. * Logging: DaveSite uses the built-in python logging module to provide console and file logging. All errors are logged to the console while only warnings and above are logged to the file. Parameters: name: package that davesite currently resides under. configuration: string that points to one of the classes in config.py Returns: A properly configured Flask application """ app = Flask(name) initialize_logging() try: app.config.from_object('davesite.app.config.{config}'.format(config=configuration)) initialize_blueprints(app) except Exception: app.logger.exception("Error while starting app:") sys.exit(-1) add_file_logging(app.config.get('ERROR_LOG_FILE', 'error.log'), logging.WARN) app.wsgi_app = URLPrefixMiddleware(app.wsgi_app, app.config.get('SCRIPT_NAME', '/')) return app
def lte(app: Flask): for blueprint in app.blueprints.values(): blueprint.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(os.path.join(get_root_path('flask_admin_lte'), 'templates/lte')), blueprint.jinja_loader, ]) app.register_blueprint(Blueprint('admin_lte', __name__, static_folder='static', static_url_path='/static/lte'))
def setUp(self): app = Flask(__name__) Funnel(app) app.config['CSS_BUNDLES'] = { 'css-bundle': ( 'css/test.css', 'less/test.less', 'scss/test.scss', 'stylus/test.styl', ), } app.config['JS_BUNDLES'] = { 'js-bundle': ( 'js/test1.js', 'js/test2.js', 'coffee/test.coffee', ), } @app.route('/') def index(): return render_template_string( "{{ css('css-bundle') }} {{ js('js-bundle') }}") self.app = app self.client = app.test_client()
def create_app(app=None, config_file=None): if not app: app = Flask(__name__, template_folder="views") # Config files app.config.from_pyfile("config/base.py") if config_file: app.config.from_pyfile("config/{}.py".format(config_file)) # Extensions Foundation(app) admin = Admin(app, name='Bolsa de Trabajo', template_mode='bootstrap3') """ CONTROLADORES """ # Blueprints app.register_blueprint(frontend) # Admin Views admin.add_view(AdminSkillView(Skill, db.session)) admin.add_view(AdminStudentView(Student, db.session)) admin.add_view(AdminCompanyView(Company, db.session)) return app
def create_app(): setup_config(sys.argv[1], 'dnsdb-updater', conf_dir=os.path.dirname(os.path.dirname(__file__))) log.error('This host belong to host group %s' % CONF.host_group) app = Flask(__name__) app.config['SECRET_KEY'] = CONF.etc.secret_key from dns_updater.utils.updater_util import check_necessary_options check_necessary_options() @app.route("/healthcheck.html", methods=['GET']) def health_check(): try: return render_template('healthcheck.html') except TemplateNotFound: abort(404) @app.context_processor def default_context_processor(): result = {'config': {'BASE_URL': CONF.web.base_url}} return result from dns_updater import api app.register_blueprint(api.bp, url_prefix='/api') return app
def test_whitelisting(self): app = Flask(__name__) limiter = Limiter(app, global_limits=["1/minute"], headers_enabled=True) @app.route("/") def t(): return "test" @limiter.request_filter def w(): if request.headers.get("internal", None) == "true": return True return False with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: self.assertEqual(cli.get("/").status_code, 200) self.assertEqual(cli.get("/").status_code, 429) timeline.forward(60) self.assertEqual(cli.get("/").status_code, 200) for i in range(0,10): self.assertEqual( cli.get("/", headers = {"internal": "true"}).status_code, 200 )
def test_custom_headers_from_config(self): app = Flask(__name__) app.config.setdefault(C.HEADER_LIMIT, "X-Limit") app.config.setdefault(C.HEADER_REMAINING, "X-Remaining") app.config.setdefault(C.HEADER_RESET, "X-Reset") limiter = Limiter(app, global_limits=["10/minute"], headers_enabled=True) @app.route("/t1") @limiter.limit("2/second; 10 per minute; 20/hour") def t(): return "test" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(11): resp = cli.get("/t1") timeline.forward(1) self.assertEqual( resp.headers.get('X-Limit'), '10' ) self.assertEqual( resp.headers.get('X-Remaining'), '0' ) self.assertEqual( resp.headers.get('X-Reset'), str(int(time.time() + 49)) )
def test_headers_breach(self): app = Flask(__name__) limiter = Limiter(app, global_limits=["10/minute"], headers_enabled=True) @app.route("/t1") @limiter.limit("2/second; 10 per minute; 20/hour") def t(): return "test" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(11): resp = cli.get("/t1") timeline.forward(1) self.assertEqual( resp.headers.get('X-RateLimit-Limit'), '10' ) self.assertEqual( resp.headers.get('X-RateLimit-Remaining'), '0' ) self.assertEqual( resp.headers.get('X-RateLimit-Reset'), str(int(time.time() + 49)) )
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'my secret' digest_auth_my_realm = HTTPDigestAuth(realm='My Realm') @digest_auth_my_realm.get_password def get_digest_password_3(username): if username == 'susan': return 'hello' elif username == 'john': return 'bye' else: return None @app.route('/') def index(): return 'index' @app.route('/digest-with-realm') @digest_auth_my_realm.login_required def digest_auth_my_realm_route(): return 'digest_auth_my_realm:' + digest_auth_my_realm.username() self.app = app self.client = app.test_client()
def test_url_absolute(self): app = Flask(__name__) app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x) field = fields.Url("foobar", absolute=True) with app.test_request_context("/"): self.assertEquals("http://localhost/3", field.output("hey", Foo()))
def test_url_invalid_object(self): app = Flask(__name__) app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x) field = fields.Url("foobar") with app.test_request_context("/"): self.assertRaises(MarshallingException, lambda: field.output("hey", None))
def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True): """Returns a :class:`Flask` application instance configured with common functionality for the _app_name_ platform. :param package_name: application package name :param package_path: application package path :param settings_override: a dictionary of settings to override :param register_security_blueprint: flag to specify if the Flask-Security Blueprint should be registered. Defaults to `True`. """ app = Flask(package_name, instance_relative_config=True) app.config.from_object('_app_name_.settings') app.config.from_pyfile('settings.cfg', silent=True) app.config.from_object(settings_override) db.init_app(app) mail.init_app(app) security.init_app(app, SQLAlchemyUserDatastore(db, User, Role), register_blueprint=register_security_blueprint) register_blueprints(app, package_name, package_path) app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app) return app
def make_json_app(import_name, **kwargs): """ Creates a JSON-oriented Flask app. All error responses that you don't specifically manage yourself will have application/json content type, and will contain JSON like this (just an example): { "message": "405: Method Not Allowed" } http://flask.pocoo.org/snippets/83/ """ def make_json_error(ex): response = jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response app = Flask(import_name, **kwargs) for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) # 初始化一些flask扩展库,依赖于flask的app上下文环境 db.init_app(app) # 初始化bootstrap bootstrap.init_app(app) # 初始化登陆管理 login_manager.init_app(app) # 初始化邮件 mail.init_app(app) # 初始化moment moment.init_app(app) # 附加路由和自定义的错误页面 app_dir = os.path.join(root_dir, 'app') # 逐个执行各个路由映射脚本,添加到route_list中 for routes in os.listdir(app_dir): rou_path = os.path.join(app_dir, routes) if (not os.path.isfile(rou_path)) and routes != 'static' and routes != 'templates': __import__('app.' + routes) # 从route_list中引入蓝图 for blueprints in route_list: if blueprints[1] != None: app.register_blueprint(blueprints[0], url_prefix = blueprints[1]) else: app.register_blueprint(blueprints[0]) #返回app实例,让外部模块继续使用 return app
def create_app(_name_=None, root=root, config='DevelopmentConfig', **configs): """ App factory :param config: name of Config class from config.py """ # Create and set app config app = Flask(_name_ or __name__) app.config.from_object('%s.config.%s' % (root, config)) app.config.update(**configs) # initialize Flask-Login with app login_manager.init_app(app) # initialize hash mechanism hashing.init_app(app) # setup blueprints def reload_blueprints(): """Loads all LIVE blueprints""" mod = lambda view: importlib.import_module('%s.%s.views' % (root, view)) return [getattr(mod(view), view) for view in app.config['LIVE']] # Setup blueprints def register_blueprints(*blueprints): """Registers all passed-in blueprints""" blueprints = list(blueprints) + reload_blueprints() for blueprint in blueprints: app.register_blueprint(blueprint) app.register_blueprints = register_blueprints app.register_blueprints() return app
def test_flask(self): app = Flask(__name__) db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' class Cities(db.Model): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) population = Column(Integer) def __init__(self, name, population): self.name = name self.population = population app.config['TESTING'] = True app = app.test_client() db.create_all() city = Cities("Cordoba", 1000000) db.session.add(city) city = Cities("Rafaela", 99000) db.session.add(city) db.session.commit() query_string = '{ "sort": { "population" : "desc" } }' results = elastic_query(Cities, query_string) assert(results[0].name == 'Cordoba')
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))
def create_cartographer(args): app = Flask(__name__) app.config["SECRET_KEY"] = "map the soul" @app.route("/") def hi(): return render_template("index.html") @app.route("/getPoints", methods=["POST"]) def getPoints(): print(request.json) zoom = int(request.json.get("zoom", 1)) seen = request.json.get("seen", []) ensure(seen).is_a_list_of(str) points = POI.objects( at__geo_within_box=(request.json["SW"], request.json["NE"]), min_zoom=zoom, name__nin=request.json["seen"] ) return jsonify( { "points": [ { "name": p.name, "lat": p.at["coordinates"][1], "lng": p.at["coordinates"][0], "abstract": lz4.decompress(p.abstract).decode() if p.abstract else "", "img": p.img, } for p in points ] } ) return app
def create_app(self): app = Flask(__name__) app.config.from_object(config['unit_test']) app.add_url_rule('/test', view_func=test_route) app.add_url_rule('/', view_func=index) #print "app.view_functions: {}".format(app.view_functions) return app
class RootREST: def __init__(self, host, run_flask, port): self.host = host self.port = port self.run_flask = run_flask self.app = Flask(__name__) CORS(self.app, resources={ r'/*': { 'origins': '*', 'headers': ['Content-Type'] } } ) #blueprintRest = BlueprintRest() self.app.register_blueprint(bp, url_prefix='/blueprint') #self.app.register_blueprint(Blueprint('blueprint', __name__), url_prefix='/blueprint') # Root service. @self.app.route('/') def landing(): return core.landing_message() # Run Flask. if self.run_flask: self.app.run(host=self.host, port=self.port)
def create_app(config): """create flaks app object""" # Initialize the App: app = Flask(__name__) from config import configurations app.config.from_object(configurations[config]) configurations[config].init_app(app) app.logger.addHandler(app.config.get('LOG_HANDLER')) app.logger.info('App is starting!') db.init_app(app) # Register the Main Views: from .views import api app.register_blueprint(api, url_prefix='/api/v1') @app.after_request def after_request(resp): for q in get_debug_queries(): if q.duration > app.config.get('DB_QUERY_TIMEOUT'): app.logger.warning( 'SLOW DB STATEMENT: {0}\n\tParameters: {1}\n\tDuration: {2}\n\tContext: {3}'. format(q.statement, q.parameters, q.duration, q.context)) return resp return app
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app_ = Flask(__name__, instance_path=instance_path) app_.config.update( FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type( 'Allow', (object, ), {'can': lambda self: True} )(), SECRET_KEY='CHANGE_ME', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, ) app_.register_blueprint(files_rest_blueprint) InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioIndexer(app_) search = InvenioSearch(app_) search.register_mappings('records-files', 'data') with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def script_info(request): """Get ScriptInfo object for testing CLI.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( ACCOUNTS_USE_CELERY=False, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, ) FlaskCLI(app) Babel(app) Mail(app) InvenioDB(app) InvenioAccounts(app) with app.app_context(): if not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.drop_all() db.create_all() def teardown(): with app.app_context(): drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) return ScriptInfo(create_app=lambda info: app)
def test_flask_sqlalchemy(): from flask.ext.sqlalchemy import SQLAlchemy as FlaskSQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' db = FlaskSQLAlchemy(app) class UserMixin(object): email = db.Column(db.Unicode(300)) def __init__(self, login, email): self.login = login self.email = email self.password = '******' class RoleMixin(object): description = db.Column(db.UnicodeText) auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin) authcode.setup_for_flask(auth, app) User = auth.User db.create_all() user = User(u'meh', u'*****@*****.**') db.session.add(user) db.session.commit() assert user.login == u'meh' assert user.email == u'*****@*****.**' assert hasattr(user, 'password') assert hasattr(user, 'last_sign_in') assert repr(user) == '<User meh>'
def test_menu_render(): menu = decorators.menu menu.clear() app = Flask(__name__) app.testing = True @menu("Hello World", group_name="admin") class Hello(object): @menu("Index") def index(self): pass @menu("Page 2") def index2(self): pass @menu("Monster") class Monster(object): @menu("Home") def maggi(self): pass with app.test_client() as c: c.get("/") assert len(menu.render()) == 2
def create_app(**config): """Application Factory You can create a new He-Man application with:: from heman.config import create_app app = create_app() # app can be uses as WSGI application app.run() # Or you can run as a simple web server """ app = Flask(__name__, static_folder=None) if "MONGO_URI" in os.environ: app.config["MONGO_URI"] = os.environ["MONGO_URI"] app.config["LOG_LEVEL"] = "DEBUG" app.config["SECRET_KEY"] = "2205552d13b5431bb537732bbb051f1214414f5ab34d47" configure_logging(app) configure_sentry(app) configure_api(app) configure_mongodb(app) configure_login(app) return app