def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( TESTING=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', ) Babel(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioCollections(app) InvenioRecords(app) app.register_blueprint(blueprint) with app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() def teardown(): with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) request.addfinalizer(teardown) with app.app_context(): db.create_all() return app
def base_app(): """Flask application fixture.""" instance_path = tempfile.mkdtemp() base_app = Flask(__name__, instance_path=instance_path) base_app.config.update( ACCOUNTS_USE_CELERY=False, LOGIN_DISABLED=False, SECRET_KEY='testing_key', SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), TEST_USER_EMAIL='*****@*****.**', TEST_USER_PASSWORD='******', TESTING=True, WTF_CSRF_ENABLED=False, ) Babel(base_app) Mail(base_app) Menu(base_app) InvenioDB(base_app) InvenioAccounts(base_app) base_app.register_blueprint(accounts_blueprint) with base_app.app_context(): if str(db.engine.url) != "sqlite://" and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() yield base_app with base_app.app_context(): drop_database(str(db.engine.url)) shutil.rmtree(instance_path)
def test_init(): """Test extension initialization.""" app = Flask('testapp') FlaskCLI(app) app.url_map.converters['pid'] = PIDConverter ext = InvenioDeposit(app) assert 'invenio-deposit' in app.extensions app = Flask('testapp') FlaskCLI(app) app.url_map.converters['pid'] = PIDConverter # check that current_deposit cannot be resolved with app.app_context(): with pytest.raises(KeyError): current_deposit.init_app ext = InvenioDeposit() assert 'invenio-deposit' not in app.extensions ext.init_app(app) assert 'invenio-deposit' in app.extensions # check that current_deposit resolves correctly with app.app_context(): current_deposit.init_app
def test_client_reference(): """Test client reference.""" client1 = {'name': 'client1'} client2 = {'name': 'client2'} app1 = Flask('testapp1') FlaskCLI(app1) app2 = Flask('testapp2') FlaskCLI(app2) ext = InvenioSearch() assert 'invenio-search' not in app1.extensions assert 'invenio-search' not in app2.extensions ext.init_app(app1, elasticsearch=client1) assert 'invenio-search' in app1.extensions ext.init_app(app2, elasticsearch=client2) assert 'invenio-search' in app2.extensions with app1.app_context(): assert current_search_client == client1 with app2.app_context(): assert current_search_client == client2
def get_app( database_uri, exclude_tables=None, user_models=None, reflect_all=True): """Return an application instance connected to the database described in *database_uri*. :param str database_uri: The URI connection string for the database :param list exclude_tables: A list of tables to exclude from the API service :param list user_models: A list of user-defined models to include in the API service :param bool reflect_all: Include all database tables in the API service """ app = Flask('sandman2') app.config['SQLALCHEMY_DATABASE_URI'] = database_uri db.init_app(app) admin = Admin(app, base_template='layout.html') _register_error_handlers(app) if user_models: with app.app_context(): _register_user_models(user_models, admin) elif reflect_all: with app.app_context(): _reflect_all(exclude_tables, admin) return app
class TestFlaskWhooshWriter(unittest.TestCase): def setUp(self): self.root_dir = tempfile.mkdtemp() schema = Schema(path=ID(stored=True), content=TEXT) self.index = create_in(self.root_dir, schema=schema) self.app = Flask(__name__) self.whoosh = Whoosh() self.whoosh.init_app(self.app) self.app.config['WHOOSH_INDEX_ROOT'] = self.root_dir def test_writer_is_usable(self): with self.app.app_context(): writer = self.whoosh.writer writer.add_document(path=u'/blah/hello', content=u'this is awesome content') writer.commit() qp = QueryParser("content", schema=self.index.schema) q = qp.parse(u"awesome") with self.index.searcher() as s: results = s.search(q) self.assertEquals(1, len(results)) self.assertEquals('/blah/hello', results[0]['path']) def test_same_writer_returned_in_multiple_calls(self): with self.app.app_context(): writer1 = self.whoosh.writer writer2 = self.whoosh.writer self.assertEquals(writer1, writer2) def tearDown(self): assert self.root_dir != '/tmp/' and self.root_dir.startswith('/tmp/') shutil.rmtree(self.root_dir)
class ZmqWorkflowResultsReceiver(object): def __init__(self, message_converter=ProtobufWorkflowResultsConverter, current_app=None): """Initialize a Receiver object, which will receive callbacks from the ExecutionElements. Args: current_app (Flask.App, optional): The current Flask app. If the Receiver is not started separately, then the current_app must be included in the init. Otherwise, it should not be included. message_converter (WorkflowResultsConverter): Class to convert workflow results """ import walkoff.server.workflowresults # Need this import ctx = zmq.Context.instance() self.message_converter = message_converter self.thread_exit = False self.workflows_executed = 0 self.results_sock = ctx.socket(zmq.PULL) self.results_sock.curve_secretkey = walkoff.config.Config.SERVER_PRIVATE_KEY self.results_sock.curve_publickey = walkoff.config.Config.SERVER_PUBLIC_KEY self.results_sock.curve_server = True self.results_sock.bind(walkoff.config.Config.ZMQ_RESULTS_ADDRESS) if current_app is None: self.current_app = Flask(__name__) self.current_app.config.from_object(walkoff.config.Config) self.current_app.running_context = context.Context(init_all=False) else: self.current_app = current_app def receive_results(self): """Keep receiving results from execution elements over a ZMQ socket, and trigger the callbacks""" while True: if self.thread_exit: break try: message_bytes = self.results_sock.recv(zmq.NOBLOCK) except zmq.ZMQError: gevent.sleep(0.1) continue with self.current_app.app_context(): self._send_callback(message_bytes) self.results_sock.close() return def _send_callback(self, message_bytes): event, sender, data = self.message_converter.to_event_callback(message_bytes) if sender is not None and event is not None: if self.current_app: with self.current_app.app_context(): event.send(sender, data=data) else: event.send(sender, data=data) if event in [WalkoffEvent.WorkflowShutdown, WalkoffEvent.WorkflowAborted]: self._increment_execution_count() def _increment_execution_count(self): self.workflows_executed += 1
class ModelizeTest(unittest.TestCase): def setUp(self): self.app = Flask(__name__) self.app.config.from_object(flask_stub_config) self.mongo = PyMongo(self.app) self.modelize = Modelize(self.mongo) class TestBaseModel(self.modelize.Model): __collection_name__ = 'test1' __fields__ = ['base_1', 'base_2'] class TestModel1(TestBaseModel): __collection_name__ = 'test1' __type_identifier__ = {'type': 'いち'} __fields__ = ['name', 'age'] class TestModel2(TestBaseModel): __collection_name__ = 'test1' __type_identifier__ = {'type': 'に'} __fields__ = ['color', 'shape'] self.TestModel1 = TestModel1 self.TestModel2 = TestModel2 with self.app.app_context(): self.mongo.db.test1.drop() model11 = TestModel1(name='完犊子', age=250) model12 = TestModel1(name='狗史', age=None) model21 = TestModel2(color='红', shape='S形') model22 = TestModel2(color='黄', shape='B形') TestModel1.query.insert(model11) TestModel1.query.insert(model12) TestModel2.query.insert(model21) TestModel2.query.insert(model22) def test_modelize_find_and_find_one(self): with self.app.app_context(): new_model11 = self.TestModel1.query.find_one({'age': 250}) self.assertIsNotNone(new_model11) self.assertIsInstance(new_model11, self.TestModel1) self.assertIsNone(new_model11.base_1) self.assertEqual(new_model11.name, '完犊子') none_model20 = self.TestModel2.query.find_one({'age': 250}) self.assertIsNone(none_model20) models_with_ages = self.TestModel1.query.find({'age': {'$ne': None}}) self.assertEqual(len(models_with_ages), 1) def test_modelize_update(self): # TODO: This is crappy. We should use change tracker or something, and # the user should be able to simple run update() to flush all changes. with self.app.app_context(): model11 = self.TestModel1.query.find_one({'name': '狗史'}) self.TestModel1.query.update(model11, {'$set': {'age': 500}}) model11 = self.TestModel1.query.find_one({'name': '狗史'}) self.assertEqual(model11.age, 500) def tearDown(self): pass
def get_app( database_uri, exclude_tables=None, user_models=None, reflect_all=True, read_only=False): """Return an application instance connected to the database described in *database_uri*. :param str database_uri: The URI connection string for the database :param list exclude_tables: A list of tables to exclude from the API service :param list user_models: A list of user-defined models to include in the API service :param bool reflect_all: Include all database tables in the API service :param bool read_only: Only allow HTTP GET commands for all endpoints """ app = Flask('sandman2') app.config['SQLALCHEMY_DATABASE_URI'] = database_uri app.config['SANDMAN2_READ_ONLY'] = read_only db.init_app(app) admin = Admin(app, base_template='layout.html', template_mode='bootstrap3') _register_error_handlers(app) if user_models: with app.app_context(): _register_user_models(user_models, admin) elif reflect_all: with app.app_context(): _reflect_all(exclude_tables, admin, read_only) return app
class TestSession: def setup(self): utils.unload_modules('alchemist') self.app = Flask('alchemist') def test_unbound(self): from alchemist import db assert not db.session def test_acquire_no_database(self): from alchemist import db, exceptions with raises(exceptions.ImproperlyConfigured), self.app.app_context(): assert db.session def test_acquire_default(self): from alchemist import db config = {'default': 'sqlite:///:memory:'} with settings(self.app, DATABASES=config), self.app.app_context(): assert db.session def test_repr(self): from alchemist import db config = {'default': 'sqlite:///:memory:'} with settings(self.app, DATABASES=config), self.app.app_context(): text = '<Session(bind=%r)>' % db.engine['default'] assert repr(db.session) == text
def create_app(script_info=None): """Create app.""" app = Flask(__name__) # logging if not os.path.exists(user_data_dir): os.makedirs(user_data_dir) log_dir = os.path.join(user_data_dir, 'log') if not os.path.exists(log_dir): os.makedirs(log_dir) peewee_logger = logging.getLogger('peewee') peewee_logger.setLevel(logging.INFO) chardet_logger = logging.getLogger('chardet') chardet_logger.setLevel(logging.INFO) default_log_file = os.path.join(log_dir, 'iqdb_tagger_server.log') file_handler = TimedRotatingFileHandler(default_log_file, 'midnight') file_handler.setLevel(logging.WARNING) file_handler.setFormatter(logging.Formatter('<%(asctime)s> <%(levelname)s> %(message)s')) app.logger.addHandler(file_handler) app.logger.addHandler(peewee_logger) app.logger.addHandler(chardet_logger) # reloader reloader = app.config['TEMPLATES_AUTO_RELOAD'] = \ bool(os.getenv('IQDB_TAGGER_RELOADER')) or app.config['TEMPLATES_AUTO_RELOAD'] # NOQA if reloader: app.jinja_env.auto_reload = True app.config['SECRET_KEY'] = os.getenv('IQDB_TAGGER_SECRET_KEY') or os.urandom(24) app.config['WTF_CSRF_ENABLED'] = False # debug debug = app.config['DEBUG'] = bool(os.getenv('IQDB_TAGGER_DEBUG')) or app.config['DEBUG'] if debug: app.config['DEBUG'] = True app.config['LOGGER_HANDLER_POLICY'] = 'debug' logging.basicConfig(level=logging.DEBUG) pprint.pprint(app.config) print('Log file: {}'.format(default_log_file)) print('script info:{}'.format(script_info)) db_path = os.getenv('IQDB_TAGGER_DB_PATH') or default_db_path init_program() init_db(db_path) # app and db app.app_context().push() @app.shell_context_processor def shell_context(): # pylint: disable=unused-variable return {'app': app} # flask-admin app_admin = Admin( app, name='IQDB Tagger', template_mode='bootstrap3', index_view=views.HomeView(name='Home', template='iqdb_tagger/index.html', url='/')) app_admin.add_view(views.MatchView()) # app_admin.add_view(ModelView(ImageMatch, category='DB')) # app_admin.add_view(ModelView(ImageMatchRelationship, category='DB')) # app_admin.add_view(ModelView(ImageModel, category='DB')) # app_admin.add_view(ModelView(MatchTagRelationship, category='DB')) # routing app.add_url_rule('/thumb/<path:basename>', view_func=thumb) return app
def create_app(): app = Flask(__name__) app.config.from_object('config') db.init_app(app) app.app_context().push() db.Model.metadata.reflect(db.engine) api = Api(app) return app
def create_test_app(db_file): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_file app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False trips_models.db.init_app(app) app.app_context().push() return app
class TestTorrents(unittest.TestCase): def setUp(self): self.app = Flask(__name__) self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.app.config['USER_LIST'] = ['Test Admin'] db.init_app(self.app) d = TempDirectory() d.makedir('dataset') d.write('dataset/files/testfile.jpg', 'abc') d.write('dataset/testfile2.jpg', 'abc') self.directory = d self.app.config['DATASET_ROOT'] = d.path with self.app.app_context(), TempDirectory() as d: db.create_all() lib.models.buildDB() dataset = lib.models.Datasets() dataset.name = 'Test' dataset.path = "dataset" db.session.add(dataset) db.session.commit() def test_add_torrent_to_model(self): with self.app.app_context(): dataset = lib.models.Datasets.query.first() mk = makeTorrent(announce='http://kb.se') mk.multi_file('{}/{}'.format(dataset.path, 'dataset')) torrent_model = lib.models.Torrent() torrent_model.datasetID = dataset.datasetID db.session.add(torrent_model) torrent_model = lib.torrents._add_torrent_to_model( torrent_model, mk ) db.session.commit() self.assertEqual(mk.info_hash(), torrent_model.infoHash) self.assertEqual(torrent_model.datasetID, 1) self.assertEqual(torrent_model.torrentData, mk.getBencoded()) self.assertIsNotNone(torrent_model.updated_at) def test_add_torrent_method_without_announce(self): with self.app.app_context(): torrent_model = lib.models.Torrent() exceptText = "ANNOUNCE is required to create torrents" with self.assertRaisesRegexp(KeyError, exceptText): lib.torrents.add_torrent(torrent_model, 1) def test_add_torrent_method(self): with self.app.app_context(): self.app.config['ANNOUNCE'] = 'http://kb.se' torrent_model = lib.models.Torrent() torrent_model = lib.torrents.add_torrent(torrent_model, 1) self.assertEqual( torrent_model.infoHash, 'cf3010468fd2c2f048d2fd3162bcdcc937fcb06f' ) def tearDown(self): self.directory.cleanup()
def test_login(self): user = '******' passwd = 'supersecret' badpass = '******' email = '*****@*****.**' request = dict( UserName=user, Email=email, Password=passwd ) request_bad = dict( UserName=user, Email=email, Password=badpass ) login = dict( loginUsername=user, loginPassword=passwd ) bad_login = dict( loginUsername=user, loginPassword='******' ) db = psycopg2.connect( database=wps.app.config['DATABASE'], user="******" ) query = "delete from users" with db.cursor() as cur: cur.execute(query) db.commit() app = Flask(__name__) with app.app_context(): g.db = psycopg2.connect( database=wps.app.config['DATABASE'], user="******" ) rv = siteutils.addnewuser(request_bad) assert 'Registration error' in rv rv = siteutils.addnewuser(request) assert 'Registration completed' in rv rv = siteutils.addnewuser(request) assert 'You have already registered with this email' in rv #not sure why needs to do this twice but database fail otherwise with app.app_context(): g.db = psycopg2.connect( database=wps.app.config['DATABASE'], user="******" ) rv = siteutils.userauth(login) assert '"success": true' in rv rv = siteutils.userauth(bad_login) assert '{"success": false}' in rv
def app(): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', JSONSCHEMAS_HOST='inveniosoftware.org', TESTING=True, SECRET_KEY='CHANGE_ME', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SERVER_NAME='app', OAISERVER_RECORD_INDEX='_all', # Disable set signals because the celery tasks cannot be run # synchronously OAISERVER_REGISTER_SET_SIGNALS=False, SEARCH_ELASTIC_KEYWORD_MAPPING={None: ['_all']}, ) if not hasattr(app, 'cli'): from flask_cli import FlaskCLI FlaskCLI(app) InvenioDB(app) FlaskCeleryExt(app) InvenioJSONSchemas(app) InvenioRecords(app) InvenioPIDStore(app) InvenioMARC21(app) client = Elasticsearch(hosts=[os.environ.get('ES_HOST', 'localhost')]) search = InvenioSearch(app, client=client) search.register_mappings('records', 'data') InvenioIndexer(app) InvenioOAIServer(app) app.register_blueprint(blueprint) with app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() list(search.create(ignore=[400])) sleep(5) with app.app_context(): yield app with app.app_context(): db.session.close() if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) list(search.delete(ignore=[404])) shutil.rmtree(instance_path)
class TestFlaskGitFetches(unittest.TestCase): """Flask git extension - fetch commit""" def setUp(self): self.temprepo = setup_repo() self.app = Flask(__name__) self.app.config['GIT_REPOPATH'] = self.temprepo.root_dir def test_fetches_all_commits(self): git = Git() git.init_app(self.app) with self.app.app_context(): commits = git.commits() self.assertEquals(3, len(list(commits))) def test_fetches_all_commits_for_file_in_regular_order(self): git = Git() git.init_app(self.app) with self.app.app_context(): commits = list(git.commits_for_path_recent_first('content/hello.md')) self.assertEquals(2, len(commits)) self.assertEquals('second commit', commits[0].message) self.assertEquals('first commit', commits[1].message) commits = list(git.commits_for_path_recent_first('content/bar.md')) self.assertEquals(1, len(commits)) def test_fetches_all_commits_for_file_in_reverse_order(self): git = Git() git.init_app(self.app) with self.app.app_context(): commits = list(git.commits_for_path_recent_last('content/hello.md')) self.assertEquals(2, len(commits)) self.assertEquals('first commit', commits[0].message) self.assertEquals('second commit', commits[1].message) commits = git.commits_for_path_recent_last('content/bar.md') self.assertEquals(1, len(list(commits))) def test_follows_renames(self): git = Git() git.init_app(self.app) # move bar.md to bar2.md self.temprepo.delete_contents('content/bar.md') self.temprepo.copy_contents('content/bar2.md', medium_sized_content()) self.temprepo.commit('fourth commit', 400) with self.app.app_context(): commits = list(git.commits_for_path_recent_first('content/bar2.md', follow=True)) self.assertEquals(2, len(commits)) self.assertEquals('fourth commit', commits[0].message) self.assertEquals('third commit', commits[1].message) def tearDown(self): self.temprepo.delete()
class KafkaWorkflowResultsReceiver(object): _requires = ['confluent-kafka'] def __init__(self, message_converter=ProtobufWorkflowResultsConverter, current_app=None): import walkoff.server.workflowresults # Need this import self.thread_exit = False kafka_config = walkoff.config.Config.WORKFLOW_RESULTS_KAFKA_CONFIG self.receiver = Consumer(kafka_config) self.topic = walkoff.config.Config.WORKFLOW_RESULTS_KAFKA_TOPIC self.message_converter = message_converter self.workflows_executed = 0 if current_app is None: self.current_app = Flask(__name__) self.current_app.config.from_object(walkoff.config.Config) self.current_app.running_context = context.Context(init_all=False) else: self.current_app = current_app def receive_results(self): """Constantly receives data from the Kafka Consumer and handles it accordingly""" logger.info('Starting Kafka workflow results receiver') self.receiver.subscribe(['{}.*'.format(self.topic)]) while not self.thread_exit: raw_message = self.receiver.poll(1.0) if raw_message is None: gevent.sleep(0.1) continue if raw_message.error(): if raw_message.error().code() == KafkaError._PARTITION_EOF: gevent.sleep(0.1) continue else: logger.error('Received an error in Kafka receiver: {}'.format(raw_message.error())) gevent.sleep(0.1) continue with self.current_app.app_context(): self._send_callback(raw_message.value()) self.receiver.close() return def _send_callback(self, message_bytes): event, sender, data = self.message_converter.to_event_callback(message_bytes) if sender is not None and event is not None: with self.current_app.app_context(): event.send(sender, data=data) if event in [WalkoffEvent.WorkflowShutdown, WalkoffEvent.WorkflowAborted]: self._increment_execution_count() def _increment_execution_count(self): self.workflows_executed += 1
def create_json_app(config): app = Flask(__name__) CORS(app) app.config.from_object(config) for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error db.init_app(app) with app.app_context(): db.create_all() app.app_context().push() return app
class DynamoTest(TestCase): """Test our Dynamo extension.""" def setUp(self): """ Set up a simple Flask app for testing. This will be used throughout our tests. """ self.prefix = uuid4().hex self.app = Flask(__name__) self.app.config['DEBUG'] = True self.app.config['DYNAMO_TABLES'] = [ Table('%s-phones' % self.prefix, schema=[HashKey('number')]), Table('%s-users' % self.prefix, schema=[HashKey('username')]), ] self.dynamo = Dynamo(self.app) with self.app.app_context(): self.dynamo.create_all() sleep(60) def test_settings(self): self.assertEqual(len(self.app.config['DYNAMO_TABLES']), 2) self.assertEqual(self.app.config['AWS_ACCESS_KEY_ID'], environ.get('AWS_ACCESS_KEY_ID')) self.assertEqual(self.app.config['AWS_SECRET_ACCESS_KEY'], environ.get('AWS_SECRET_ACCESS_KEY')) self.assertEqual(self.app.config['AWS_REGION'], environ.get('AWS_REGION') or self.dynamo.DEFAULT_REGION) def test_connection(self): with self.app.app_context(): self.assertIsInstance(self.dynamo.connection, DynamoDBConnection) def test_tables(self): with self.app.app_context(): self.assertEqual(len(self.dynamo.tables.keys()), 2) for table_name, table in self.dynamo.tables.iteritems(): self.assertIsInstance(table, Table) self.assertEqual(table.table_name, table_name) def test_table_access(self): with self.app.app_context(): for table_name, table in self.dynamo.tables.iteritems(): self.assertEqual(getattr(self.dynamo, table_name), table) def tearDown(self): """Destroy all provisioned resources.""" with self.app.app_context(): self.dynamo.destroy_all() sleep(60)
def create_app(config_obj, no_sql=False): """Flask application factory. Initializes and returns the Flask application. Blueprints are registered in here. Modeled after: http://flask.pocoo.org/docs/patterns/appfactories/ Positional arguments: config_obj -- configuration object to load into app.config. Keyword arguments: no_sql -- does not run init_app() for the SQLAlchemy instance. For Celery compatibility. Returns: The initialized Flask application. """ # Initialize app. Flatten config_obj to dictionary (resolve properties). app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder=STATIC_FOLDER) config_dict = dict([(k, getattr(config_obj, k)) for k in dir(config_obj) if not k.startswith('_')]) app.config.update(config_dict) # Import DB models. Flask-SQLAlchemy doesn't do this automatically like Celery does. with app.app_context(): for module in app.config.get('DB_MODELS_IMPORTS', list()): import_module(module) # Setup redirects and register blueprints. app.add_url_rule('/favicon.ico', 'favicon', lambda: app.send_static_file('favicon.ico')) for bp in all_blueprints: import_module(bp.import_name) app.register_blueprint(bp) # Initialize extensions/add-ons/plugins. if not no_sql: db.init_app(app) Statics(app) # Enable Flask-Statics-Helper features. redis.init_app(app) celery.init_app(app) mail.init_app(app) login_manager.init_app(app) with app.app_context(): storage = SQLAStorage(db=db,document=Document) blogging_engine.init_app(app, storage) # Activate middleware. locale.setlocale(locale.LC_ALL, 'eng_US') # For filters inside the middleware file. with app.app_context(): import_module('reco.middleware') # Return the application instance. return app
def test_werkzeug_debugger(): from flask import Flask app = Flask(__name__) with app.app_context(): werkzeug_debugger.werkzeug_debugger() app.debug = True with app.app_context(): with pytest.raises(AssertionError) as excinfo: werkzeug_debugger.werkzeug_debugger() assert 'werkzeug_debugger()' == str(excinfo.value)
def main(argv): from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../database.db' db.init_app(app) if(len(argv) > 0 and argv[0] == 'd'): with app.app_context(): db.drop_all() else: with app.app_context(): db.create_all() test_user = User(login="******", password=generate_password_hash("test")) db.session.add(test_user) db.session.commit()
def create_app(): app = Flask(__name__) app.config.from_object('config') register_extensions(app) register_blueprints(app) register_commands(app) register_errorhandlers(app) # See http://flask.pocoo.org/docs/0.12/appcontext/#creating-an-application-context # and http://flask-sqlalchemy.pocoo.org/2.3/contexts/ app.app_context().push() return app
def test_init(): """Test extension initialization.""" app = Flask('testapp') ext = InvenioCollections(app) assert 'invenio-collections' in app.extensions with app.app_context(): current_collections.unregister_signals() app = Flask('testapp') ext = InvenioCollections() assert 'invenio-collections' not in app.extensions ext.init_app(app) assert 'invenio-collections' in app.extensions with app.app_context(): current_collections.unregister_signals()
class TestShell(CommandTest): patch = 'flask.ext.script.Shell.run' def test_run(self): target = self._run(['shell']) target.assert_called() def test_context(self): utils.unload_modules('alchemist') from alchemist.commands import Shell shell = Shell() self.app = Flask('alchemist.tests.a') self.context = self.app.app_context() with self.context: alchemist.configure(self.app) context = shell.make_context() assert 'db' in context assert 'session' in context assert 'Entity' in context def test_pipe(self): utils.unload_modules('alchemist') self.app = Flask('alchemist.tests.a') self.context = self.app.app_context() with self.context: alchemist.configure(self.app) stdin = sys.stdin sys.stdin = io.StringIO('print(Entity)\nprint(session)') capture = py.io.StdCapture(out=True, in_=False) self._run(['shell', '--pipe']) out, err = capture.done() text = ("<class 'alchemist.tests.a.models.Entity'>\n" "<Session(bind=Engine(sqlite:///:memory:))>\n") assert text == out.read() sys.stdin = stdin
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 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 create_app(config): app = Flask(__name__) app.config.from_pyfile(config) CORS( app, origins=[ 'http://127.0.0.1:5994', 'http://living-with-django.astex.io' ], supports_credentials=True ) from blog.lib.database import db db.init_app(app) from blog import views views.register(app) with app.app_context(): db.create_all() from blog.lib.session import SessionInterface app.session_interface = SessionInterface() return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) 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_v1 import api as api_v1_blueprint app.register_blueprint(api_v1_blueprint, url_prefix='/api/v1') with app.app_context(): db.create_all() db.session.commit() return app
def base_app(): """Flask application fixture without InvenioStats.""" from invenio_stats.config import STATS_EVENTS instance_path = tempfile.mkdtemp() app_ = Flask('testapp', instance_path=instance_path) stats_events = { 'file-download': deepcopy(STATS_EVENTS['file-download']), 'record-view': { 'signal': 'invenio_records_ui.signals.record_viewed', 'event_builders': [ 'invenio_stats.contrib.event_builders' '.record_view_event_builder' ] } } stats_events.update({'event_{}'.format(idx): {} for idx in range(5)}) app_.config.update( dict( CELERY_ALWAYS_EAGER=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_TASK_EAGER_PROPAGATES=True, CELERY_RESULT_BACKEND='cache', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, OAUTH2SERVER_CLIENT_ID_SALT_LEN=64, OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60, OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60, STATS_MQ_EXCHANGE=Exchange( 'test_events', type='direct', delivery_mode='transient', # in-memory queue durable=True, ), SECRET_KEY='asecretkey', SERVER_NAME='localhost', STATS_QUERIES={ 'bucket-file-download-histogram': {}, 'bucket-file-download-total': {}, 'test-query': {}, 'test-query2': {} }, STATS_EVENTS=stats_events, STATS_AGGREGATIONS={'file-download-agg': {}})) FlaskCeleryExt(app_) InvenioAccounts(app_) InvenioAccountsREST(app_) InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioPIDStore(app_) InvenioCache(app_) InvenioQueues(app_) InvenioOAuth2Server(app_) InvenioOAuth2ServerREST(app_) InvenioSearch(app_, entry_point_group=None) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def create_app(config_name): """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ @param config_name: The configuration object to use. """ app = Flask(__name__) app.config.from_object(config[config_name] or config[os.getenv('BG_CONFIG')]) app.config.from_envvar('BG_SETTINGS', silent=True) config[config_name].init_app(app) db.init_app(app) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) from app.users.forms import ExtendedRegisterForm security.init_app(app, user_datastore, register_form=ExtendedRegisterForm) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) migrate.init_app(app, db) md = Markdown(app, output_format='html5', extensions=['fenced_code', 'tables', 'abbr', 'footnotes']) pages.init_app(app) csrf.init_app(app) register_adminviews(app) app.jinja_env.filters['alert_class'] = alert_class_filter # WTForms helpers from .utils import add_helpers add_helpers(app) if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'], fromaddr=app.config['ADMINS_FROM_EMAIL'], toaddrs=app.config['ADMINS_EMAIL'], subject='Application Error Occurred') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) register_blueprints(app) register_commands(app) # Create the bg_interface directory if it does not exist directory = os.path.join(os.path.dirname(BASE_DIR), 'bg_interface') if not os.path.exists(directory): os.makedirs(directory) with app.app_context(): db.create_all() if not User.query.first(): # Create a default admin user if there is no user in the database user_datastore.create_role(name='admin') user_datastore.create_user(name='Administration Account', email='*****@*****.**', password=encrypt_password('password'), roles=['admin']) db.session.commit() app.logger.info('Created admin user [email protected]') return app
def create_app(): logging.basicConfig(stream=sys.stdout, level=logging.INFO) app = Flask(__name__) app.config.from_object(CONFIG_CLASS) # read directory mount based config into Flask config try: with open("/config/config.json", 'r') as f: conf_data = json.load(f) app.config.update(conf_data) except Exception as e: logging.warning("Failed to load config.json") logging.info("Flask CONFIG: %s" % app.config) db.init_app(app) # according to SQLAlchemy will only create tables if they do not exist with app.app_context(): db.create_all() # static file serving @app.route('/public/<path:path>') def send_files(path): return send_from_directory("../static", path) register_views(app, db) if "TELEMETRY_DISABLED" not in app.config: # create thread for analytics scheduler = BackgroundScheduler() # send a ping now analytics_ping(app) # and every 15 minutes scheduler.add_job(analytics_ping, 'interval', minutes=app.config["TELEMETRY_INTERVAL"], args=[app]) scheduler.start() # Start threaded file_permission_watcher # TODO: reconsider file permission approach # Note: process is never cleaned up, this is permissible because it's only # executed inside a container. watcher_file = "/tmp/file_permission_watcher_active" # guarantee no two python file permission watchers are started if not os.path.isfile(watcher_file): with open(watcher_file, "w") as file: file.write("1") file_dir = os.path.dirname(os.path.realpath(__file__)) permission_process = Popen([ os.path.join(file_dir, "scripts", "file_permission_watcher.py"), app.config["USER_DIR"] ]) logging.info("Started file_permission_watcher.py") return app
class Things3API: """API Wrapper for the simple read-only API for Things 3.""" PATH = getcwd() + "/resources/" DEFAULT = "kanban.html" test_mode = "task" host = "localhost" port = 15000 def on_get(self, url=DEFAULT): """Handles other GET requests""" status = 200 filename = self.PATH + url content_type = "application/json" if filename.endswith("css"): content_type = "text/css" if filename.endswith("html"): content_type = "text/html" if filename.endswith("js"): content_type = "text/javascript" if filename.endswith("png"): content_type = "image/png" if filename.endswith("jpg"): content_type = "image/jpeg" if filename.endswith("ico"): content_type = "image/x-ico" try: with open(filename, "rb") as source: data = source.read() except FileNotFoundError: data = "not found" content_type = "text" status = 404 return Response(response=data, content_type=content_type, status=status) def mode_selector(self): """Switch between project and task mode""" try: mode = request.args.get("mode") except RuntimeError: mode = "task" if mode == "project" or self.test_mode == "project": self.things3.mode_project() def config_get(self, key): """Read key from config""" data = self.things3.get_config(key) return Response(response=data) def config_set(self, key): """Write key to config""" value = request.get_data().decode("utf-8").strip() if value: self.things3.set_config(key, value) return Response() def seinfeld(self, tag): """Get tasks logged recently with a specific tag.""" data = self.things3.get_seinfeld(tag) data = json.dumps(data) return Response(response=data, content_type="application/json") def tag(self, tag, area=None): """Get specific tag.""" self.mode_selector() if area is not None: data = self.things3.get_tag_today(tag) else: data = self.things3.get_tag(tag) self.things3.mode_task() data = json.dumps(data) return Response(response=data, content_type="application/json") def api(self, command): """Return database as JSON strings.""" if command in self.things3.functions: func = self.things3.functions[command] self.mode_selector() data = func(self.things3) self.things3.mode_task() data = json.dumps(data) return Response(response=data, content_type="application/json") data = json.dumps(self.things3.get_not_implemented()) return Response(response=data, content_type="application/json", status=404) def get_url(self): """Get the public url for the endpoint""" fqdn = f"{socket.gethostname()}.local" # pylint: disable=E1101 return f"http://{fqdn}:{self.port}" def api_filter(self, mode, uuid): """Filter view by specific modifiers""" if mode == "area" and uuid != "": self.things3.filter = f"TASK.area = '{uuid}' AND" self.things3.filter_area = uuid if mode == "project" and uuid != "": self.things3.filter = f""" (TASK.project = '{uuid}' OR HEADING.project = '{uuid}') AND """ self.things3.filter_project = uuid return Response(status=200) def api_filter_reset(self): """Reset filter modifiers""" self.things3.filter = "" self.things3.filter_project = None self.things3.filter_area = None return Response(status=200) def __init__(self, database=None, host=None, port=None, expose=None, debug_text=""): # pylint: disable-msg=too-many-arguments self.things3 = Things3(database=database, debug_text=debug_text) cfg = self.things3.get_from_config(host, "KANBANVIEW_HOST") self.host = cfg if cfg else self.host self.things3.set_config("KANBANVIEW_HOST", self.host) cfg = self.things3.get_from_config(port, "KANBANVIEW_PORT") self.port = cfg if cfg else self.port self.things3.set_config("KANBANVIEW_PORT", self.port) cfg = self.things3.get_from_config(expose, "API_EXPOSE") self.host = "0.0.0.0" if (str(cfg).lower() == "true") else "localhost" self.things3.set_config("KANBANVIEW_HOST", self.host) self.things3.set_config("API_EXPOSE", str(cfg).lower() == "true") self.flask = Flask(__name__) self.flask.add_url_rule("/config/<key>", view_func=self.config_get) self.flask.add_url_rule("/config/<key>", view_func=self.config_set, methods=["PUT"]) self.flask.add_url_rule("/api/<command>", view_func=self.api) self.flask.add_url_rule("/api/<command>", view_func=self.api, methods=["PUT"]) self.flask.add_url_rule("/api/url", view_func=self.get_url) self.flask.add_url_rule("/api/seinfeld/<tag>", view_func=self.seinfeld) self.flask.add_url_rule("/api/tag/<tag>", view_func=self.tag) self.flask.add_url_rule("/api/tag/<tag>/<area>", view_func=self.tag) self.flask.add_url_rule("/api/filter/<mode>/<uuid>", view_func=self.api_filter) self.flask.add_url_rule("/api/filter/reset", view_func=self.api_filter_reset) self.flask.add_url_rule("/<url>", view_func=self.on_get) self.flask.add_url_rule("/", view_func=self.on_get) self.flask.app_context().push() self.flask_context = None def main(self): """Main function.""" print(f"Serving at http://{self.host}:{self.port} ...") try: self.flask_context = make_server(self.host, self.port, self.flask, threaded=True) self.flask_context.serve_forever() except KeyboardInterrupt: print("Shutting down...") sys.exit(0)
def create_app(): flask_app = Flask(__name__) configure_app(flask_app) with flask_app.app_context(): db.init_app(flask_app) return flask_app
from flask import Flask, render_template, url_for, request, redirect, current_app, flash # get access to the form from pkmnForm import pokemonSubmit # this uses the flask constructor to connect flask to the main output app = Flask(__name__) #configure a secret key for csrf protection # config loads the current configuration change to an object that # affects all other extentions, files, etc app.config[ "SECRET KEY"] = "WGNy;2An6=}_&Fod1Tq~D!4_lu3/7[c?H!xcJG[Lr77wQX66]4XJigy_;n6K" app.app_context() # create a list that stores pokemon; includes sample pokemon already pokemonList = ["Pikachu", "Bulbasaur", "Squirtle", "Charmander"] # create a route for the site @app.route('/pokeList', methods=['POST', 'GET']) def pokeList(): # create a form variable that initializes the class form = pokemonSubmit() # this validate function returns True if form is submitted # using a POST request AND it is valid if form.validate_on_submit(): # from the form, the name variable inside the function, and data gets it pokemonName = form.name.data if pokemonName not in pokemonList: pokemonList.append(pokemonName)
import os from flask import Flask, render_template, request from models import * app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL") app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) def main(): db.create_all() if __name__ == "__main__": with app.app_context(): main()
class TestURLize(unittest.TestCase): def setUp(self): self.app = Flask('bogus') def test_dont_urlize_cats( self ): self.assertGreater(len(links.CATEGORIES_THAT_COULD_BE_HOSTNAMES), 0, 'The links.CATEGORIES_THAT_COULD_BE_HOSTNAMES must not be empty or it will match everything') @mock.patch(f'{links.__name__}.clickthrough') def test_doi(self, mock_clickthrough): with self.app.app_context(): mock_clickthrough.clickthrough_url = lambda url: f'http://arxiv.org/clickthrough?url={url}' self.maxDiff = 3000 self.assertEqual( links.urlize('here is a rando doi doi:10.1109/5.771073 that needs a link'), 'here is a rando doi doi:<a class="link-http link-external" data-doi="10.1109/5.771073" href="http://arxiv.org/clickthrough?url=https://dx.doi.org/10.1109/5.771073" rel="external noopener nofollow">10.1109/5.771073</a> that needs a link' ) def test_transform_token(self): # def doi_id_url_transform_token(tkn,fn): # return doi_id_url_transform_token(fn, tkn) with self.app.app_context(): self.assertEqual(links.urlize('', ['url']), '') self.assertEqual( links.urlize('it is fine, chapter 234 see<xxyx,234>'), escape('it is fine, chapter 234 see<xxyx,234>') ) self.assertEqual(links.urlize('http://arxiv.org', ['url']), '<a class="link-internal link-http" href="http://arxiv.org">http://arxiv.org</a>') self.assertEqual(links.urlize('https://arxiv.org', ['url']), '<a class="link-internal link-https" href="https://arxiv.org">https://arxiv.org</a>') self.assertEqual( links.urlize('in the front http://arxiv.org oth', ['url']), 'in the front <a class="link-internal link-http" href="http://arxiv.org">http://arxiv.org</a> oth' ) self.assertEqual( links.urlize('.http://arxiv.org.', ['url']), '.<a class="link-internal link-http" href="http://arxiv.org">http://arxiv.org</a>.' ) self.assertEqual( links.urlize('"http://arxiv.org"', ['url']), '"<a class="link-internal link-http" href="http://arxiv.org">http://arxiv.org</a>"' ) self.assertEqual( links.urlize('"https://arxiv.org/help"', ['url']), '"<a class="link-internal link-https" href="https://arxiv.org/help">https://arxiv.org/help</a>"' ) @mock.patch(f'{links.__name__}.clickthrough') @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_urlize(self, mock_clickthrough): with self.app.app_context(): mock_clickthrough.clickthrough_url.return_value = 'foo' self.assertEqual( links.urlize('http://example.com/'), '<a class="link-external link-http" href="http://example.com/" rel="external noopener nofollow">this http URL</a>', 'urlize (URL linking) 1/6' ) self.assertEqual( links.urlize('https://example.com/'), '<a class="link-external link-https" href="https://example.com/" rel="external noopener nofollow">this https URL</a>', 'urlize (URL linking) 2/6' ) self.assertEqual( links.urlize('ftp://example.com/'), '<a class="link-external link-ftp" href="ftp://example.com/" rel="external noopener nofollow">this ftp URL</a>', 'urlize (URL linking) 3/6' ) self.assertEqual( links.urlize('http://projecteuclid.org/euclid.bj/1151525136'), '<a class="link-external link-http" href="http://projecteuclid.org/euclid.bj/1151525136" rel="external noopener nofollow">this http URL</a>', 'urlize (URL linking) 6/6' ) self.assertEqual(links.urlize('2448446.4710(5)'), '2448446.4710(5)', 'urlize (should not match) 1/9') self.assertEqual(links.urlize('HJD=2450274.4156+/-0.0009'), 'HJD=2450274.4156+/-0.0009', 'urlize (should not match) 2/9') self.assertEqual( links.urlize('T_min[HJD]=49238.83662(14)+0.146352739(11)E.'), 'T_min[HJD]=49238.83662(14)+0.146352739(11)E.', 'urlize (should not match) 3/9' ) self.assertEqual(links.urlize('Pspin=1008.3408s'), 'Pspin=1008.3408s', 'urlize (should not match) 4/9') self.assertEqual( links.urlize('2453527.87455^{+0.00085}_{-0.00091}'), '2453527.87455^{+0.00085}_{-0.00091}', 'urlize (should not match) 5/9' ) self.assertEqual(links.urlize('2451435.4353'), '2451435.4353', 'urlize (should not match) 6/9') self.assertEqual( links.urlize('cond-mat/97063007'), '<a class="link-https" data-arxiv-id="cond-mat/9706300" href="https://arxiv.org/abs/cond-mat/9706300">cond-mat/9706300</a>7', 'urlize (should match) 7/9') self.assertEqual( links.urlize('[http://onion.com/something-funny-about-arxiv-1234]'), '[<a class="link-external link-http" href="http://onion.com/something-funny-about-arxiv-1234" rel="external noopener nofollow">this http URL</a>]') self.assertEqual( links.urlize( '[http://onion.com/?q=something-funny-about-arxiv.1234]' ), '[<a class="link-external link-http" href="http://onion.com/?q=something-funny-about-arxiv.1234" rel="external noopener nofollow">this http URL</a>]' ) self.assertEqual( links.urlize('http://onion.com/?q=something funny'), '<a class="link-external link-http" href="http://onion.com/?q=something" rel="external noopener nofollow">this http URL</a> funny', 'Spaces CANNOT be expected to be part of URLs' ) self.assertEqual( links.urlize( '"http://onion.com/something-funny-about-arxiv-1234"' ), '"<a class="link-external link-http" href="http://onion.com/something-funny-about-arxiv-1234" rel="external noopener nofollow">this http URL</a>"', 'Should handle URL surrounded by double quotes' ) self.assertEqual(links.urlize('< http://example.com/1<2 ><'), '< <a class="link-external link-http" href="http://example.com/1" rel="external noopener nofollow">this http URL</a><2 ><', 'urlize (URL linking) 5/6') self.assertEqual( links.urlize('Accepted for publication in A&A. The data will be available via CDS, and can be found "http://atlasgal.mpifr-bonn.mpg.de/cgi-bin/ATLASGAL_FILAMENTS.cgi"'), 'Accepted for publication in A&A. The data will be available via CDS, and can be found "<a class="link-external link-http" href="http://atlasgal.mpifr-bonn.mpg.de/cgi-bin/ATLASGAL_FILAMENTS.cgi" rel="external noopener nofollow">this http URL</a>"' ) self.assertEqual( links.urlize('see http://www.tandfonline.com/doi/abs/doi:10.1080/15980316.2013.860928?journalCode=tjid20'), 'see <a class="link-external link-http" href="http://www.tandfonline.com/doi/abs/doi:10.1080/15980316.2013.860928?journalCode=tjid20" rel="external noopener nofollow">this http URL</a>' ) self.assertEqual( links.urlize('http://authors.elsevier.com/a/1TcSd,Ig45ZtO'), '<a class="link-external link-http" href="http://authors.elsevier.com/a/1TcSd,Ig45ZtO" rel="external noopener nofollow">this http URL</a>' ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_category_id(self): self.assertEqual( links.urlize('version of arXiv.math.GR/0512484 (2011).', ['arxiv_id']), 'version of arXiv.<a class="link-https" data-arxiv-id="math.GR/0512484" href="https://arxiv.org/abs/math.GR/0512484">math.GR/0512484</a> (2011).' ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_parens(self): """ARXIVNG-250 Linkification should not choke on parentheses.""" with self.app.app_context(): self.assertEqual( links.urlize('http://www-nuclear.univer.kharkov.ua/lib/1017_3(55)_12_p28-59.pdf'), '<a class="link-external link-http" href="http://www-nuclear.univer.kharkov.ua/lib/1017_3(55)_12_p28-59.pdf" rel="external noopener nofollow">this http URL</a>' ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_hosts(self): with self.app.app_context(): self.assertEqual( links.urlize('can be downloaded from http://rwcc.bao.ac.cn:8001/swap/NLFFF_DBIE_code/HeHan_NLFFF_JGR.pdf'), 'can be downloaded from <a class="link-external link-http" href="http://rwcc.bao.ac.cn:8001/swap/NLFFF_DBIE_code/HeHan_NLFFF_JGR.pdf" rel="external noopener nofollow">this http URL</a>', "Should deal with ports correctly" ) self.assertEqual( links.urlize('images is at http://85.20.11.14/hosting/punsly/APJLetter4.2.07/'), 'images is at <a class="link-external link-http" href="http://85.20.11.14/hosting/punsly/APJLetter4.2.07/" rel="external noopener nofollow">this http URL</a>', "should deal with numeric IP correctly" ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_urls_with_plus(self): with self.app.app_context(): self.assertEqual( links.urlize('http://www.fkf.mpg.de/andersen/docs/pub/abstract2004+/pavarini_02.pdf'), '<a class="link-external link-http" href="http://www.fkf.mpg.de/andersen/docs/pub/abstract2004+/pavarini_02.pdf" rel="external noopener nofollow">this http URL</a>' ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_anchors_with_slash(self): with self.app.app_context(): self.assertIn( 'href="https://dms.sztaki.hu/ecml-pkkd-2016/#/app/privateleaderboard"', links.urlize('https://dms.sztaki.hu/ecml-pkkd-2016/#/app/privateleaderboard'), "Should deal with slash in URL anchor correctly" ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_ftp(self): with self.app.app_context(): self.assertEqual( links.urlize('7 Pages; ftp://ftp%40micrognu%2Ecom:anon%[email protected]/pnenp/conclusion.pdf'), '7 Pages; <a class="link-external link-ftp" href="ftp://ftp%40micrognu%2Ecom:anon%[email protected]/pnenp/conclusion.pdf" rel="external noopener nofollow">this ftp URL</a>' ) @mock.patch(f'{links.__name__}.url_for', mock_url_for) def test_arxiv_prefix(self): with self.app.app_context(): self.assertEqual( links.urlize("see arxiv:1201.12345"), 'see <a class="link-https" data-arxiv-id="1201.12345" href="https://arxiv.org/abs/1201.12345">arXiv:1201.12345</a>') @mock.patch(f'{links.__name__}.clickthrough') def test_doi_2(self, mock_clickthrough): with self.app.app_context(): mock_clickthrough.clickthrough_url = lambda x: x self.assertRegex(links.urlize('10.1088/1475-7516/2018/07/009'), r'<a.*href="https://.*10.1088/1475-7516/2018/07/009".*>10.1088/1475-7516/2018/07/009</a>') self.assertRegex(links.urlize('10.1088/1475-7516/2019/02/E02/meta'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/meta".*>10.1088/1475-7516/2019/02/E02/meta</a>') self.assertRegex(links.urlize('10.1088/1475-7516/2019/02/E02/META'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/META".*>10.1088/1475-7516/2019/02/E02/META</a>') self.assertRegex(links.urlize('doi:10.1088/1475-7516/2018/07/009'), r'<a.*href="https://.*10.1088/1475-7516/2018/07/009".*>10.1088/1475-7516/2018/07/009</a>') self.assertRegex(links.urlize('doi:10.1088/1475-7516/2019/02/E02/meta'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/meta".*>10.1088/1475-7516/2019/02/E02/meta</a>') self.assertRegex(links.urlize('doi:10.1088/1475-7516/2019/02/E02/META'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/META".*>10.1088/1475-7516/2019/02/E02/META</a>') @mock.patch(f'{links.__name__}.clickthrough') def test_double_doi(self, mock_clickthrough): with self.app.app_context(): mock_clickthrough.clickthrough_url = lambda x: x txt = links.urlize('10.1088/1475-7516/2018/07/009 10.1088/1475-7516/2019/02/E02/meta' ) self.assertNotRegex(txt, r'this.*URL', 'DOIs should not get the generic "this https URL" they should have the DOI text') self.assertRegex(txt, r'<a.*>10.1088/1475-7516/2018/07/009</a> <a.*>10.1088/1475-7516/2019/02/E02/meta</a>', 'Should handle two DOIs in a row correctly') @mock.patch(f'{links.__name__}.clickthrough') def test_broad_doi(self, mock_clickthrough): with self.app.app_context(): mock_clickthrough.clickthrough_url = lambda x: x broad_doi_fn = links.urlizer(['doi_field']) # ARXIVNG-3523 unusual DOI self.assertRegex(broad_doi_fn('21.11130/00-1735-0000-0005-146A-E'), r'<a.*href="https://.*21.11130.*>21.11130/00-1735-0000-0005-146A-E</a>') self.assertRegex(broad_doi_fn('10.1088/1475-7516/2018/07/009'), r'<a.*href="https://.*10.1088/1475-7516/2018/07/009".*>10.1088/1475-7516/2018/07/009</a>') self.assertRegex(broad_doi_fn('10.1088/1475-7516/2019/02/E02/meta'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/meta".*>10.1088/1475-7516/2019/02/E02/meta</a>') self.assertRegex(broad_doi_fn('10.1088/1475-7516/2019/02/E02/META'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/META".*>10.1088/1475-7516/2019/02/E02/META</a>') self.assertRegex(broad_doi_fn('doi:10.1088/1475-7516/2018/07/009'), r'<a.*href="https://.*10.1088/1475-7516/2018/07/009".*>10.1088/1475-7516/2018/07/009</a>') self.assertRegex(broad_doi_fn('doi:10.1088/1475-7516/2019/02/E02/meta'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/meta".*>10.1088/1475-7516/2019/02/E02/meta</a>') self.assertRegex(broad_doi_fn('doi:10.1088/1475-7516/2019/02/E02/META'), r'<a.*href="https://.*10.1088/1475-7516/2019/02/E02/META".*>10.1088/1475-7516/2019/02/E02/META</a>') txt = broad_doi_fn('10.1088/1475-7516/2018/07/009 10.1088/1475-7516/2019/02/E02/meta' ) self.assertNotRegex(txt, r'this.*URL', 'DOIs should not get the generic "this https URL" they should have the DOI text') self.assertRegex(txt, r'<a.*>10.1088/1475-7516/2018/07/009</a> <a.*>10.1088/1475-7516/2019/02/E02/meta</a>', 'Should handle two DOIs in a row correctly') urlized_doi = broad_doi_fn('10.1175/1520-0469(1996)053<0946:ASTFHH>2.0.CO;2') self.assertNotIn('href="http://2.0.CO"', urlized_doi, "Should not have odd second <A> tag for DOI urlize for ao-sci/9503001 see ARXIVNG-2049") leg_rx = r'<a .* href="https://dx.doi.org/10.1175/1520-0469%281996%29053%3C0946%3AASTFHH%3E2.0.CO%3B2".*' self.assertRegex(urlized_doi, leg_rx, "Should handle Complex DOI for ao-sci/9503001 see ARXIVNG-2049") # in legacy: # <a href="/ct?url=https%3A%2F%2Fdx.doi.org%2F10.1175%252F1520-0469%25281996%2529053%253C0946%253AASTFHH%253E2.0.CO%253B2&v=34a1af05">10.1175/1520-0469(1996)053<0946:ASTFHH>2.0.CO;2</a> # Post clickthrough on legacy goes to : # https://dx.doi.org/10.1175%2F1520-0469%281996%29053%3C0946%3AASTFHH%3E2.0.CO%3B2 def test_dont_urlize_category_name(self): with self.app.app_context(): urlize = links.urlizer() self.assertEqual(urlize('math.CO'), 'math.CO', 'category name math.CO should not get urlized') self.assertIn('href="http://supermath.co', urlize('supermath.co'), 'hostname close to category name should get urlized') def test_dont_urlize_arxiv_dot_org(self): with self.app.app_context(): urlize = links.urlizer() self.assertNotRegex(urlize('something https://arxiv.org bla'), r'this.*URL', 'arxiv.org should not get "this https URL" ARXIVNG-2130') self.assertNotRegex(urlize('something arxiv.org bla'), r'this.*URL', 'arxiv.org should not get "this https URL" ARXIVNG-2130') self.assertRegex(urlize('something arXiv.org'), r'arXiv\.org', 'arXiv.org should be preserved as text [ARXIVNG-2130]') self.assertRegex(urlize('something arxiv.org'), r'arxiv\.org', 'arXiv.org should be preserved as text [ARXIVNG-2130]')
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) CORS(app) bootstrap.init_app(app) app.config.from_object(configs) #restful显示中文 app.config.update(RESTFUL_JSON=dict(ensure_ascii=False)) app.config['JSON_AS_ASCII'] = False with app.app_context(): db.init_app(app) #初始化db # auth.init_app(app) #初始化httpauth # user1 = User(username='******', password='******') # user2 = User(username='******', password='******') # db.session.add_all([user1,user2]) # db.session.commit() # db.drop_all() # db.create_all() # app.app_context().push() # with app.app_context(): # db.init_app(app) # db.create_all() app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'Flask-QA.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # # a simple page that says hello @app.route('/') def index(): return render_template('dist/index.html') # app.register_blueprint(forms.wtf) app.register_blueprint(RestfulApi.RestfulApi) app.register_blueprint(User_permissions_api.user_permissions) app.register_blueprint(AuthorityApi.AuthorityApi) app.register_blueprint(AuxiliaryFunction.AuxiliaryFunction) app.register_blueprint(Restful.Tree_api.OperationTree) app.register_blueprint(Upload_file.RestfulFile) app.register_blueprint(Restful.TestCaseApi.TestCaseApi) app.register_blueprint(Restful.Timing_task.Unattended) app.register_blueprint(Restful.AnalysisLog.AnalysisLog) app.register_blueprint(Restful.GenerateScripts.GenerateScripts) app.register_blueprint(Restful.LogApi.LogApi) app.register_blueprint(Restful.MonitorResult.MonitorResult) app.register_blueprint(Pressure_test_monitoring.Pressure_monitor) app.app_context().push() # app.add_url_rule('/', endpoint='dist') return app
from flask import Flask from flask_cors import CORS from backend.__config__ import BaseConfig from backend.db import db from backend.service import auth_service, user_service, spbu_service from backend.service.util.json_encoder import ModelEncoder application = Flask(__name__) CORS( application, supports_credentials=True, ) application.config.from_object(BaseConfig) application.app_context().push() application.json_encoder = ModelEncoder db.init_app(application) # if not database_exists(BaseConfig.SQLALCHEMY_DATABASE_URI): # db.create_all() # initialize_database() application.register_blueprint(auth_service.auth, url_prefix='/auth') application.register_blueprint(user_service.user, url_prefix='/user') application.register_blueprint(spbu_service.spbu, url_prefix='/spbu') application.run(debug=True)
import os from flask import Flask from flask_restful import Api from app import db from app.api.item_api import ItemAPI from app.config import DB_CONN_STR, API_PORT # Quick and dirty main script to launch the API if __name__ == '__main__': flask_app = Flask('item_service') api = Api(flask_app) api.add_resource(ItemAPI, '/item', '/item/<string:item_id>') flask_app.config['SQLALCHEMY_DATABASE_URI'] = DB_CONN_STR db.init_app(flask_app) with flask_app.app_context(): db.create_all() db.session.commit() flask_app.run(debug=True, port=API_PORT)
# Add passenger. flight.add_passenger(name) return render_template("success.html") @app.route("/flights") def flights(): """ Lists all flights. """ flights = Flight_orig.query.all() return render_template("flights.html", flights=flights) @app.route("/flights/<int:flight_id>") def flight(flight_id): """ List a single flight """ # Make sure the flight exists. flight = Flight_orig.query.get(flight_id) if flight is None: return render_template("error.html", message="No such flight with that id.") # Get all passengers passengers = flight.passengers return render_template("flight.html", flight=flight, passengers=passengers) if __name__ == "__main__": with app.app_context( ): # One of the nuances of Flask, allows us to interact with the flask app without a webpage app.run()
to conncect to a spoecific server, change Config settings. provide better naming than original system. """ class Config(): SQLALCHEMY_DATABASE_URI = "mysql+pymysql://hui:[email protected]:3306/ngs_server?charset=utf8mb4" SQLALCHEMY_TRACK_MODIFICATIONS = False app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy() db.init_app(app) app.app_context().push() class BaseDataModel(): @property def id_display(self): return self.id class SeqRound(db.Model): __tablename__ = 'sequence_round' # __table_args__ = {'extend_existing': True} sequence_id = Column(mysql.INTEGER(unsigned=True), ForeignKey('sequence.id'), primary_key=True) rounds_id = Column(mysql.INTEGER(unsigned=True),
def create_app(configfile=None): app = Flask(__name__) app.secret_key = 's3cr3t' AppConfig(app) Bootstrap(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, 'user-login.sqlite') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False REDIS_URL = 'http://localhost:6379' urllib.parse.uses_netloc.append('redis') url = urllib.parse.urlparse(REDIS_URL) app.config['RQ_DEFAULT_HOST'] = url.hostname app.config['RQ_DEFAULT_PORT'] = url.port app.config['RQ_DEFAULT_PASSWORD'] = url.password app.config['RQ_DEFAULT_DB'] = 0 app.config['MAIL_SERVER'] = 'smtp.sendgrid.net' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True app.config['MAIL_DEBUG'] = True app.config['MAIL_USERNAME'] = '' app.config['MAIL_PASSWORD'] = '' # EAM : Set limit on the number of items in cache (RAM) cache.init_app(app, config={ 'CACHE_TYPE': 'simple', 'CACHE_THRESHOLD': 1000 }) # Set up asset pipeline assets_env = Environment(app) dirs = ['assets/styles', 'assets/scripts'] for path in dirs: assets_env.append_path(os.path.join(basedir, path)) assets_env.url_expire = True assets_env.register('app_css', app_css) assets_env.register('app_js', app_js) assets_env.register('vendor_css', vendor_css) assets_env.register('vendor_js', vendor_js) with app.app_context(): from .frontend import frontend app.register_blueprint(frontend) from .content import content app.register_blueprint(content) app.json_encoder = MiniJSONEncoder nav.init_app(app) mail.init_app(app) csrf.init_app(app) db.init_app(app) login_manager.init_app(app) compress.init_app(app) htmlmin.init_app(app) RQ(app) return app
from selenium import webdriver from flask import Flask from flask import g from urls import CF_MAIN_URL, CF_LOGIN_URL app = Flask(__name__) # initialize global variables ctx = app.app_context() ctx.push() g.browser = webdriver.Chrome() # g.browser = webdriver.PhantomJS() g.browser.set_window_size(1020, 2020) g.handle = '' g.password = '' g.default_url = CF_MAIN_URL g.login_url = CF_LOGIN_URL g.submit_url = '' g.browser.get(g.default_url)
def create_app(test_config=None): app = Flask(__name__) app.config.from_object('config.Config') data_path = path_join('CS235Flix', 'memory_repository') if test_config is not None: app.config.from_mapping(test_config) data_path = app.config['TEST_DATA_PATH'] if app.config['REPOSITORY'] == 'memory': repo.repository_instance = MemoryRepository() populate(data_path, repo.repository_instance) elif app.config['REPOSITORY'] == 'database': database_engine = create_engine( app.config['SQLALCHEMY_DATABASE_URI'], connect_args={"check_same_thread": False}, poolclass=NullPool, echo=app.config['SQLALCHEMY_ECHO']) if app.config['TESTING'] == 'True' or len( database_engine.table_names()) == 0: print("REPOPULATING DATABASE") clear_mappers() metadata.create_all(database_engine) for table in reversed(metadata.sorted_tables): database_engine.execute(table.delete()) map_model_to_tables() database_repository.populate(database_engine, data_path) else: map_model_to_tables() session_factory = sessionmaker(autocommit=False, autoflush=True, bind=database_engine) repo.repository_instance = database_repository.SqlAlchemyRepository( session_factory) with app.app_context(): from .home import home app.register_blueprint(home.home_blueprint) from .browsing import browse_by app.register_blueprint(browse_by.browse_blueprint) from .authentication import authentication app.register_blueprint(authentication.authentication_blueprint) from .reviews import reviews app.register_blueprint(reviews.reviews_blueprint) from .search import search app.register_blueprint(search.search_blueprint) from .user_profile import watchlist app.register_blueprint(watchlist.watchlist_blueprint) @app.before_request def before_flask_http_request_function(): if isinstance(repo.repository_instance, database_repository.SqlAlchemyRepository): repo.repository_instance.reset_session() @app.teardown_appcontext def shutdown_session(exception=None): if isinstance(repo.repository_instance, database_repository.SqlAlchemyRepository): repo.repository_instance.close_session() return app
def create_app(): """Construct the core application.""" print("*** create_app") #logging.basicConfig( # format='%(asctime)s %(process)d,%(threadName)s %(filename)s:%(lineno)d [%(levelname)s] %(message)s', # datefmt='%Y-%m-%d %H:%M:%S', # level=logging.INFO) #logger = logging.getLogger(__name__) #logger = logging.getLogger('myapp') logger.setLevel(logging.DEBUG) if Config.LOG_ENABLED.lower() == 'true': rabbit = RabbitMQHandler(host=Config.LOG_HOST, port=Config.LOG_PORT, username=Config.LOG_USERNAME, password=Config.LOG_PASSWORD, exchange=Config.LOG_EXCHANGE, routing_key_format=Config.LOG_KEY, fields=versionRequestValues) logger.addHandler(rabbit) logger.debug('test debug') app = Flask("fs", instance_relative_config=False) # RabbitMQ #app.config.setdefault('RABMQ_RABBITMQ_URL', 'amqp://*****:*****@localhost:5672/') #app.config.setdefault('RABMQ_SEND_EXCHANGE_NAME', 'flask_rabmq') #app.config.setdefault('RABMQ_SEND_EXCHANGE_TYPE', 'topic') #app.config.setdefault('RABMQ_SEND_POOL_SIZE', 2) #app.config.setdefault('RABMQ_SEND_POOL_ACQUIRE_TIMEOUT', 5) #ramq = RabbitMQ() #ramq.init_app(app=app) #ramq.send({'message_id': 222222, 'a': 7}, routing_key='flask_rabmq.test') #app.config.from_object('config.Config') # Remover #app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///site.db' #app.config["SQLALCHEMY_DATABASE_URI"] = 'mssql+pymssql://sist_rpsr:Ho1#h=j4@desesqlbdmg:2002/bdseg' app.config["SQLALCHEMY_DATABASE_URI"] = Config.SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.secret_key = Config.SECRET_KEY #db.app = app db.init_app(app) tl.start(block=False) with app.app_context(): # Imports from . import routes # Create tables for our models #db.create_all() #return app, ramq return app
def create_app(): app = Flask(__name__) with app.app_context(): from . import views # noqa: E402,F401 from . import apis # noqa: E402,F401 return app
from dash.dependencies import Input, Output from flask import Flask import plotly.express as px from db.database import ( get_cvss_v2_cols, get_cvss_v3_cols, get_cve_query_df_with_columns, init_db, ) temp_app = Flask(__name__) init_db(temp_app) with temp_app.app_context(): full_df = get_cve_query_df_with_columns() # This leaves some records not included because they have not been assigned versions or score information. cve_cvss_v3_df = full_df[get_cvss_v3_cols()].loc[ full_df["cvss_v3_version"].notna()] cve_cvss_v2_df = full_df[get_cvss_v2_cols()].loc[ full_df["cvss_v2_version"].notna()] # Add x col for display cve_cvss_v3_df["date_published"] = cve_cvss_v3_df.apply( lambda x: str(x["published_date"])[8:10], axis=1) px_box_cvss_v3_base_score = {} px_hist_cvss_v3_base_severity = {} px_hist_cvss_v3_attack_vector = {} px_hist_cvss_v3_attack_complexity = {} px_hist_cvss_v3_privileges_required = {}
def get_app(config, _app=None, with_external_mods=True, with_flask_admin=True): # Make sure app is a singleton if _app is not None: return _app app = Flask(__name__) app.config.update(config) # Bind app to DB DB.init_app(app) # For deleting files on "delete" media @before_models_committed.connect_via(app) def on_before_models_committed(sender, changes): for obj, change in changes: if change == "delete" and hasattr(obj, "__before_commit_delete__"): obj.__before_commit_delete__() # Bind app to MA MA.init_app(app) # Pass parameters to the usershub authenfication sub-module, DONT CHANGE THIS app.config["DB"] = DB # Pass parameters to the submodules app.config["MA"] = MA # Pass the ID_APP to the submodule to avoid token conflict between app on the same server app.config["ID_APP"] = app.config["ID_APPLICATION_GEONATURE"] with app.app_context(): if app.config["MAIL_ON_ERROR"] and app.config["MAIL_CONFIG"]: from geonature.utils.logs import mail_handler logging.getLogger().addHandler(mail_handler) # DB.create_all() if with_flask_admin: # from geonature.core.admin import flask_admin from geonature.core.admin.admin import flask_admin from pypnusershub.routes import routes app.register_blueprint(routes, url_prefix="/auth") from pypn_habref_api.routes import routes app.register_blueprint(routes, url_prefix="/habref") from pypnusershub import routes_register app.register_blueprint(routes_register.bp, url_prefix="/pypn/register") from pypnnomenclature.routes import routes app.register_blueprint(routes, url_prefix="/nomenclatures") from geonature.core.gn_permissions.routes import routes app.register_blueprint(routes, url_prefix="/permissions") from geonature.core.gn_permissions.backoffice.views import routes app.register_blueprint(routes, url_prefix="/permissions_backoffice") from geonature.core.routes import routes app.register_blueprint(routes, url_prefix="") from geonature.core.users.routes import routes app.register_blueprint(routes, url_prefix="/users") from geonature.core.gn_synthese.routes import routes app.register_blueprint(routes, url_prefix="/synthese") from geonature.core.gn_meta.routes import routes app.register_blueprint(routes, url_prefix="/meta") from geonature.core.ref_geo.routes import routes app.register_blueprint(routes, url_prefix="/geo") from geonature.core.gn_exports.routes import routes app.register_blueprint(routes, url_prefix="/exports") from geonature.core.auth.routes import routes app.register_blueprint(routes, url_prefix="/gn_auth") from geonature.core.gn_monitoring.routes import routes app.register_blueprint(routes, url_prefix="/gn_monitoring") from geonature.core.gn_commons.routes import routes app.register_blueprint(routes, url_prefix="/gn_commons") # Errors from geonature.core.errors import routes CORS(app, supports_credentials=True) # Emails configuration if app.config["MAIL_CONFIG"]: conf = app.config.copy() conf.update(app.config["MAIL_CONFIG"]) app.config = conf MAIL.init_app(app) app.config['TEMPLATES_AUTO_RELOAD'] = True # disable cache for downloaded files (PDF file stat for ex) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Loading third-party modules if with_external_mods: for conf, manifest, module in list_and_import_gn_modules(app): app.register_blueprint( module.backend.blueprint.blueprint, url_prefix=conf["MODULE_URL"] ) _app = app return app
web.config['BOOTSTRAP_SERVE_LOCAL'] = True # upload directory upload_directory = os.path.join( config.Config('upload', 'directory').value, 'uploads') if os.path.isdir(upload_directory) is not True: os.makedirs(upload_directory) web.config['UPLOAD_FOLDER'] = upload_directory web.config['MAX_CONTENT_LENGTH'] = int( config.Config('upload', 'max_size').value) * 1024 * 1024 db = SQLAlchemy(web) # just use the migration script's app context when you import the models # http://stackoverflow.com/questions/33905706/flask-migrate-seemed-to-delete-all-my-database-data with web.app_context(): from models import * description = "Cobra v{0} ( https://github.com/wufeifei/cobra ) is a static code analysis system that automates the detecting vulnerabilities and security issue.".format( VERSION) manager = Manager(web, description=description) host = config.Config('cobra', 'host').value port = config.Config('cobra', 'port').value port = int(port) class Statistic(Command): """ Statistics code-related information (lines of code / lines of comments / number of blank lines)
def create_app(config=None): """ Project app factory """ configs = { 'development': '.development', 'production': '.production', 'default': '.default' } if config not in configs: config = getenv("FLASK_CONFIGURATION", "default") config = 'app.config' + configs[config] app = Flask(__name__) app.config.from_object(config) Bootstrap(app) @app.errorhandler(400) def bad_request(error): return render_template('400.html'), 400 @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(error): return render_template('500.html'), 500 from app.models.models import db, Usuario from app.models.commands import populate app.app_context().push() db.init_app(app) migrate = Migrate(app, db) @app.cli.command() def create(): """ Creates database tables from sqlalchemy models """ db.create_all() populate() @app.cli.command() def drop(): """ Drops database tables """ prompt = input('Erase current database? [y/n]') if prompt == 'y': db.session.close_all() db.drop_all() from app.controllers.functions.email import mail mail.init_app(app) from app.controllers.routes import admin, management, users, views app.register_blueprint(management.management) app.register_blueprint(users.users) app.register_blueprint(views.views) upload_path = path.join(path.dirname(__file__), 'static') adm = admin.init_app(app, upload_path) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def user_loader(user_id): return db.session.query(Usuario).filter_by(id=user_id).first() @login_manager.unauthorized_handler def unauthorized_callback(): return redirect('/login') babel = Babel(app) @babel.localeselector def get_locale(): if request.args.get('lang'): session['lang'] = request.args.get('lang') return "pt" return app
def create_app(args=None): # create and configure the app app = Flask(__name__, static_url_path='', static_folder='static', instance_relative_config=True) # add user provided configurations for the if args: app.config.update( HOST=args["host"], PORT=args["port"], RETRIEVAL_HOST=args['retrieval_host'], RETRIEVAL_PORT=args['retrieval_port'], SIMILARITY_HOST=args['similarity_host'], SIMILARITY_PORT=args['similarity_port'], EMBEDDING_HOST=args['embedding_host'], EMBEDDING_PORT=args['embedding_port'], # TODO: add additional enviroments ) # set the service environment SERVICE_ENV = args["env"] if args else 'development' # setup the app configuration if SERVICE_ENV == 'production': app.config.from_object(config.ProductionConfig) elif SERVICE_ENV == 'development': app.config.from_object(config.DevelopmentConfig) elif SERVICE_ENV == 'testing': app.config.from_object(config.TestingConfig) # setup the cors configurations if app.config['CORS']['origins']: CORS(app, origins=app.config['CORS']['origins']) # add error handlers from .routes import error_handlers error_handlers.register(app) # create context: components are using app.config with app.app_context(): # add logger configuration config_logging.init_app(app) # add index routes from .routes import index app.register_blueprint(index.bp) # add embedding routes from .routes import service app.register_blueprint(service.bp) from .routes import database app.register_blueprint(database.bp) from .routes import document_retrieval app.register_blueprint(document_retrieval.bp) from .routes import document_similarity app.register_blueprint(document_similarity.bp) from .routes import text_embedding app.register_blueprint(text_embedding.bp) # TODO: log start of the service # return the app return app
api.add_resource(TableResource, '/api/tables/<id>') api.add_resource(NotificationResourceList, '/api/notifications') api.add_resource(NotificationResource, '/api/notifications/<id>') api.add_resource(ReservationResourceList, '/api/reservations') api.add_resource(ReservationResource, '/api/reservations/<id>') api.add_resource(FeedbackResourceList, '/api/feedback') api.add_resource(FeedbackResource, '/api/feedback/<id>') api.add_resource(MealResourceList, '/api/meals') api.add_resource(MealResource, '/api/meals/<id>') with application.app_context(): db.init() @application.route('/') def index(): return render_template('index.html') @application.route('/kidzone') def kidzone(): return render_template('kidzone.html') @application.route('/about') def about(): return render_template('about.html')
def build_distilr_api( # TODO: Pass application name in so it can be used in log prefix blueprints, # Collection of flask Blueprints build_distilr_application_context=None, # Built within the Flask app context. health_check_function=None, # Called with 1 arg: flask_app before_request_function=None): # Called with 1 arg: flask_app # logging.getLogger('flask_cors').level = logging.DEBUG LOG.info("Startup beggining...") app = Flask(__name__) CORS(app) _configure_logging() distilr_application_context = None if build_distilr_application_context: with app.app_context(): distilr_application_context = build_distilr_application_context() distilr_application_context = {} if distilr_application_context == None else distilr_application_context if before_request_function: @app.before_request def before_request_function_(): before_request_function(distilr_application_context) if health_check_function: @app.route(HEALTH_CHECK_URI, methods=('GET', )) def health_check_function_(): return health_check_function(g) else: @app.route(HEALTH_CHECK_URI, methods=('GET', )) def DEAFULT_HEALTH_CHECK_FUNCITON(): return '', 200 @app.errorhandler(DistilrBaseException) def handle_distilr_exceptions(e): response_body = {"description": e.description, 'details': e.details} LOG.error(e.description + ': ' + json.dumps(e.details)) return response_body, e.status_code, { 'Content-Type': 'application/json' } @app.errorhandler(Exception) def handle_exceptions(e): response_body = { "description": str(e), } LOG.error('---- {} (500) ----'.format(e.__class__.__name__)) LOG.exception(e) LOG.error('------------------') return response_body, 500, {'Content-Type': 'application/json'} for blueprint_ in blueprints: app.register_blueprint(blueprint_) return app
def setup(): # First, we instantiate a Flask object and configure it app = Flask(__name__) app.config.from_object(Config) # Then, we initialize our database, login manager and image upload system db_init_app(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'auth.login' configure_uploads(app, images_upload_set) @login_manager.user_loader def load_user(user_id): return db.session.query(User).get(int(user_id)) # Finally, we register needed blueprints app.register_blueprint(auth, url_prefix='/auth') app.register_blueprint(feed, url_prefix='') app.register_blueprint(profile, url_prefix='/profile') app.register_blueprint(post, url_prefix='/post') app.register_blueprint(follow, url_prefix='/follow') app.register_blueprint(create_post, url_prefix='/create_post') app.register_blueprint(create_comment, url_prefix='/create_comment') app.register_blueprint(search_post, url_prefix='/search_post') # Here we create some demo models with app.app_context(): test = User(email='*****@*****.**', username='******', password=generate_password_hash('eurycleemdp', method='sha256')) u1 = User(email='*****@*****.**', username='******', password=generate_password_hash('johnmdp', method='sha256')) u2 = User(email='*****@*****.**', username='******', password=generate_password_hash('estebanmdp', method='sha256')) u3 = User(email='*****@*****.**', username='******', password=generate_password_hash('samirmdp', method='sha256')) u4 = User(email='*****@*****.**', username='******', password=generate_password_hash('brittanymdp', method='sha256')) db.session.add_all([test, u1, u2, u3, u4]) u3.follow(u2) u1.follow(u2) u2.follow(u2) u3.follow(u3) u1.follow(u2) u1.follow(u4) db.session.commit() p1 = Post(user_id=u1.get_id(), username=u1.username, image_name='1.jpg', description='Une superbe vue de la plage !', tags="plage mer", hearts=12) p2 = Post(user_id=u2.get_id(), username=u2.username, image_name='2.jpg', description="Vive l'espace", tags="espace galaxie", hearts=23) p3 = Post(user_id=u3.get_id(), username=u3.username, image_name='3.jpg', description='Photo de nuit.', tags="nuit ciel", hearts=7) p4 = Post(user_id=u3.get_id(), username=u3.username, image_name='4.jpg', description='Souvenir de mon séjour à la montagne.', tags="montagnes vacances", hearts=9) p5 = Post(user_id=u4.get_id(), username=u4.username, image_name='5.gif', description='Chill bears.', tags="chill ours", hearts=141) p6 = Post(user_id=u1.get_id(), username=u1.username, image_name='6.jpg', description='Trop classe le Pape', tags="voiture pape", hearts=36) p7 = Post(user_id=u2.get_id(), username=u2.username, image_name='7.jpg', description="J'adore les glaces !", tags="glace glaces", hearts=25) p8 = Post(user_id=u3.get_id(), username=u3.username, image_name='8.jpg', description='Lever de soleil sur la mer', tags="soleil mer vacances", hearts=59) db.session.add_all([p1, p2, p3, p4, p5, p6, p7, p8]) db.session.commit() c1 = Comment(user_id=u3.get_id(), username=u3.username, body="trop b1 cette tof omg", post_id=p4.id) c2 = Comment(user_id=u3.get_id(), username=u3.username, body="les rageux diront photoshop", post_id=p4.id) c3 = Comment(user_id=u2.get_id(), username=u2.username, body="It do be like that sometime", post_id=p1.id) c4 = Comment(user_id=u1.get_id(), username=u1.username, body="Hmmmmm!", post_id=p7.id) c5 = Comment(user_id=u4.get_id(), username=u4.username, body="Yumyum", post_id=p7.id) c6 = Comment( user_id=u1.get_id(), username=u1.username, body= "je gagne 781€ par minute en restant chez moi grâce a gagnerunmaxdeblé.io", post_id=p1.id) c6 = Comment(user_id=u1.get_id(), username=u1.username, body="habemus papam", post_id=p6.id) db.session.add_all([c1, c2, c3, c4, c5, c6]) db.session.commit() return app
def create_app(config): app = Flask(__name__) CORS(app) app.config.from_object(config) app.register_blueprint(healthcheck_api, url_prefix="/api") app.register_blueprint(user_api, url_prefix="/api") app.register_blueprint(access_point_api, url_prefix="/api") app.register_blueprint(log_api, url_prefix="/api") # START GLOBAL HTTP CONFIGURATIONS @app.after_request def add_header(response): return response @app.errorhandler(400) def bad_request(e): logging.error(e) return response_with(resp.BAD_REQUEST_400) @app.errorhandler(500) def server_error(e): logging.error(e) return response_with(resp.SERVER_ERROR_500) @app.errorhandler(404) def not_found(e): logging.error(e) return response_with(resp.NOT_FOUND_HANDLER_404) # JWT Errors @app.errorhandler(AuthRequired) def auth_required(e): logging.error(e) return response_with(resp.UNAUTHORIZED_403, error=e.error) @app.errorhandler(DecodeError) def decode_error(e): logging.error(e) return response_with(resp.UNAUTHORIZED_403, error=e.error) @app.errorhandler(ExpiredSignatureError) def expired_error(e): logging.error(e) return response_with(resp.UNAUTHORIZED_403, error=e.error) @app.errorhandler(BaseJWTError) def base_jwt_error(e): logging.error(e) return response_with(resp.UNAUTHORIZED_403, error=e.error) # END GLOBAL HTTP CONFIGURATIONS db.init_app(app) with app.app_context(): db.create_all() logging.basicConfig( stream=sys.stdout, format="%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s|%(message)s", level=logging.DEBUG, ) return app
def app_factory(): monkey_patch_json_encoder() app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = config.get('SQLALCHEMY_DATABASE_URI') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.secret_key = config.get('FLASK_SESSION_SECRET_KEY') db.init_app(app) Marshmallow(app) app.wsgi_app = ProxyFix(app.wsgi_app) app.url_map.strict_slashes = False blueprint = Blueprint('v1', __name__, url_prefix='/api/v1') api.init_app(blueprint) api.add_namespace(auth_namespace, '/authentication') api.add_namespace(users_namespace, '/users') app.register_blueprint(blueprint) app.session_interface = AppSessionInterface() login_manager = LoginManager() login_manager.init_app(app) seed_data_enabled = config.get('SEED_DATA_ENABLED') if seed_data_enabled: with app.app_context(): seed_data = SeedDataService() seed_data.seed() @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) @login_manager.request_loader def load_user_from_request(request): header = request.headers.get('Authorization') if header is None: # review how to whitelist end points that we know won't ever require authn/authz # total hack, clean up with werkzeug or flask trimming, or our own method... this is super messy. whitelist = ['/api/v1', '/api/v1?', '/api/v1/?', '/api/v1/swagger.json'] if request.full_path in whitelist: return raise Unauthorized() header_value = header.split() auth_type = header_value[0].lower() if auth_type == 'bearer': authenticated_bearer_token(header_value[1]) elif auth_type == 'basic': creds = request.authorization if creds is not None: authenticate_basic(creds.username, creds.password) if current_user is None: raise Unauthorized() g.authenticated_from_header = True @app.after_request def after_request(response): if 'cache-control' not in response.headers: response.headers['cache-control'] = 'no-cache' return response @api.errorhandler def default_error_handler(e): """ Provide a default error handler for RestPlus to leverage. """ logger.exception(e) debug = config.get('FLASK_DEBUG') if not debug: message = 'An unhandled exception occurred.' return {'message': message}, 500 @app.errorhandler(400) def bad_request_error(e): return jsonify(error=400, text=str(e)), 400 @app.errorhandler(404) def page_not_found(e): return jsonify(error=404, text=str(e)), 404 @app.errorhandler(500) def server_error(e): logger.error(e) return jsonify(error=500, text=str(e)), 500 @app.errorhandler(RequestException) def request_exception(e): logger.error(e) return jsonify(error=500, text=str(e)), 500 return app
"timestamp": str(date.datetime.now()), "message": "Name {} is already exist".format(name) }) else: return json.dumps({ "status": False, "timestamp": str(date.datetime.now()), "message": "Invalid name {}".format(name) }) return json.dumps({ "status": False, "timestamp": str(date.datetime.now()), "message": "Unknown error" }) if os.path.isfile(fnames[2]): peer_nodes = np.load(fnames[2]).tolist() if os.path.isfile(fnames[1]): this_nodes_transactions = np.load(fnames[1]).tolist() if os.path.isfile(fnames[0]): blockchain = np.load(fnames[0]).tolist() else: blockchain.append(create_genesis_block()) with node.app_context(): init() node.run(host='0.0.0.0',port=5000)
import os from flask import Flask from user_db import * APP = Flask(__name__) APP.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL") APP.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(APP) def main(): db.create_all() if __name__ == '__main__': with APP.app_context(): main()