Beispiel #1
0
class BaseHTTPService(BaseService):

    template_folder = None
    application_name = None

    def setup_server(self):
        super(BaseHTTPService, self).setup_server()

        # Create an Flask application for this service using the service name
        self.app = Flask(self.application_name or self.__class__.__name__, template_folder=self.template_folder or None)

        methods = dir(self)
        # Attach each route in the class
        for name in [x for x in methods if x.startswith("route_")]:
            method = getattr(self, name)
            self.app.add_url_rule(method.rule, name, method)
            self.logger.debug("Adding handler '%s' for '%s' rule", name, method.rule)

        # Attach error handlers in the class
        for name in [x for x in methods if x.startswith("error_")]:
            method = getattr(self, name)
            code = int(name.split("_", 2)[1])
            self.app.error_handler_spec[None][code] = method
            self.logger.debug("Adding handler '%s' for error code '%d'", name, code)

    def run(self):
        self.logger.debug("Waiting for clients")
        try:
            self.app.run(self.listener_address, self.listener_port)
        except KeyboardInterrupt:
            self.logger.warning("Canceled by the user")
            self.stop()

    def stop(self):
        self.logger.debug("Stopping server")
Beispiel #2
0
    def parse_node(self, response, node):
        node.remove_namespaces()
        cds_bibrec, ok, errs = create_bibrec(
            node.xpath('.//record').extract()[0]
        )
        if not ok:
            raise RuntimeError("Cannot parse record %s: %s", node, errs)
        self.logger.info("Here's the record: %s" % cds_bibrec)
        inspire_bibrec = CDS2Inspire(cds_bibrec).get_record()
        marcxml_record = record_xml_output(inspire_bibrec)
        record = create_record(marcxml_record)

        app = Flask('hepcrawl')
        app.config.update(
            self.settings.getdict('MARC_TO_HEP_SETTINGS', {})
        )
        with app.app_context():
            json_record = hep.do(record)
            base_uri = self.settings['SCHEMA_BASE_URI']
            json_record['$schema'] = base_uri + 'hep.json'

        parsed_item = ParsedItem(
                record=json_record,
                record_format='hep',
            )
        return parsed_item
Beispiel #3
0
def register_handlers(app: Flask) -> Flask:
    """A function to register global request handlers.
    To register a handler add them like the example
    Example usage:

        def fn(request: Request):
            pass

        app.before_request(fn)

    Args:
        app (Flask): Flask Application instance

    Returns:
        Flask: Flask Application instance
    """
    identity_loaded.connect_via(app)(on_identity_loaded)

    app.errorhandler(PermissionDenied)(permission_denied)
    app.errorhandler(CSRFError)(invalid_csrf)
    app.errorhandler(NoAuthorizationError)(invalid_csrf)
    app.errorhandler(InvalidUsage)(invalid_error_handler)
    app.errorhandler(Exception)(normalize_errors)

    return app
Beispiel #4
0
 def __init__(self, import_name, static_path=None, static_url_path=None,
              static_folder='static', template_folder='templates',
              instance_path=None, instance_relative_config=False, py_components_directories=[]):
     Flask.__init__(self, import_name, static_path, static_url_path,
                    static_folder, template_folder,
                    instance_path, instance_relative_config)
     self.__py_components_loader = BaseComponentLoader(self, py_components_directories)
Beispiel #5
0
def app_secured_from_configuration():
    app = Flask(__name__)
    app.config["OPA_SECURED"] = True
    app.config["OPA_URL"] = 'http://localhost:8181/v1/data/examples/allow'
    app.opa = OPA(app, input_function=parse_input)
    init_app(app)
    return app
def test_register_handlers_registers_connection_handler_with_bindings_validation(
    server_info: Info,
    faker: Faker,
):
    namespace = f"/{faker.pystr()}"
    spec = AsyncApiSpec(
        asyncapi=faker.pystr(),
        info=server_info,
        channels={
            namespace:
            Channel(bindings=ChannelBindings(
                ws=WebSocketsChannelBindings(method="GET", )), )
        },
    )
    server = new_mock_asynction_socket_io(spec)
    flask_app = Flask(__name__)

    server._register_handlers()
    _, registered_handler, _ = server.handlers[0]

    handler_with_validation = deep_unwrap(registered_handler, depth=1)
    actual_handler = deep_unwrap(registered_handler)

    with flask_app.test_client() as c:
        with patch.object(server, "start_background_task"):
            c.post()  # Inject invalid POST request
            actual_handler()  # actual handler does not raise validation errors
            with pytest.raises(BindingsValidationException):
                handler_with_validation()
Beispiel #7
0
def create_app(spark_context, app):
    global recommendationengine
    recommendationengine = RecommendationEngine(spark_context, app)

    app = Flask(__name__)
    app.register_blueprint(main)
    return app
Beispiel #8
0
    def __init__(self,
                 dbUri='sqlite:///:memory:',
                 port=5000,
                 verbose=False,
                 serializer=jsonSerializerWithUri):

        self.flaskApp = Flask(__name__,
                              static_url_path='',
                              static_folder=abspath('./static'))

        print 'Using following sqlite database URI:', dbUri
        self.flaskApp.config['SQLALCHEMY_DATABASE_URI'] = dbUri

        self.flaskApp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

        if verbose:
            self.flaskApp.config['SQLALCHEMY_ECHO'] = True

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

        self.port = port
        self.serializer = serializer
        self.namespaces = {}
Beispiel #9
0
    def setUp(self):
        modules.flags_manager.remove_all_flags()

        self.app = Flask(__name__)
        self.app.add_url_rule('/test', 'test', test_api, methods=['POST'])

        init_flask('test_app', self.app, setup_kuber_config_loader=False)

        flags.DEFINE_INTEGER_FLAG("test")
        self.loader = KuberConfigLoader("test_service")
        self.loader.load_config(
            config_pb2.GlobalConfig(
                flags=[{
                    "name": "test",
                    "type": "INTEGER",
                    "value": {
                        "base_value": {
                            "number_value": 1
                        }
                    }
                }],
                experiments={
                    2:
                    ExperimentDefinition(
                        id=2,
                        flag_values={
                            "test": FlagValue(base_value={"number_value": 2})
                        })
                }))

        self.server = Process(target=self.app.run, args=("127.0.0.1", 8008))
        self.server.start()
        sleep(1)
Beispiel #10
0
def app():
    """Import the test app"""
    app = Flask(__name__)
    app.config["OPA_SECURED"] = True
    app.config["OPA_URL"] = 'http://localhost:8181/v1/data/examples/allow'
    app.opa = OPA(app, input_function=parse_input).secured()
    init_app(app)
    return app
Beispiel #11
0
def init_app(app: Flask):
    from . import auth, user, order, shop, admin, merchant
    app.register_blueprint(auth.app)
    app.register_blueprint(user.app)
    app.register_blueprint(order.app)
    app.register_blueprint(shop.app)
    app.register_blueprint(admin.app)
    app.register_blueprint(merchant.app)
def create_app(config_filename=None):
    app = Flask(__name__)
    app.config.from_object(hepdata_converter_ws)

    from hepdata_converter_ws.api import api
    app.register_blueprint(api)

    return app
def create_app(config_filename=None):
    app = Flask(__name__)
    app.config.from_object(hepdata_converter_ws)

    from hepdata_converter_ws.api import api
    app.register_blueprint(api)

    return app
Beispiel #14
0
def init_app(app: Flask):
    from src.api import models
    db.init_app(app)
    print(emojize('Base de dados conectada :outbox_tray:'))

    with app.app_context():
        db.create_all()

    app.db = db
Beispiel #15
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    bootstrap.init_app(app)
    db.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    return app
Beispiel #16
0
        def _create_json_record(xml_record):
            object_record = create_record(etree.XML(xml_record))
            app = Flask('hepcrawl')
            app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS',
                                                    {}))
            with app.app_context():
                dojson_record = hep.do(object_record)

            return dojson_record
Beispiel #17
0
def build_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db = SQLAlchemy(app)
    app.secret_key = 'super secret key'
    admin = Admin(app, name='Fuzz', template_mode='bootstrap3')
    admin.add_view(ModelView(FuzzerIssue, db.session))
    logging.basicConfig(level=logging.DEBUG)
    return app
Beispiel #18
0
    def setUp(self):
        app = Flask(__name__)
        app.testing = True
        app.config["TESTING"] = True

        setup_rest_api(app)
        self.client = app.test_client

        # Init db
        DbSessionHolder(TestV1API.REST_TEST_DB).reset()
Beispiel #19
0
def setup(app: app.Flask):
    '''
    设置 中间件 蓝图 编码
    '''
    CorsMw.setupCors(app)
    ErrorHandle.errorHandle(app)
    GetRegionsBlue.registerBlueRegions(app)

    app.config['JSON_AS_ASCII'] = False
    app.config['UPLOAD_FOLDER'] = './tmp/'
Beispiel #20
0
def init_app():
    app = Flask(__name__)
    app.config.from_envvar("OIDCFED_RELYING_PARTY_CONFIG")

    template_loader = jinja2.FileSystemLoader(["templates", "../templates"])
    app.jinja_loader = template_loader

    app.rp = init_oidc_fed_rp(app.config)

    return app
Beispiel #21
0
    def create_app(self):
        from openbrokerapi.api import get_blueprint

        app = Flask(__name__)
        self.broker = Mock()

        app.register_blueprint(
            get_blueprint(self.broker, BrokerCredentials("", ""),
                          basic_config(level=logging.WARN)))
        return app
Beispiel #22
0
def create_app(config_name: str = "default") -> Flask:
    app = Flask(__name__)
    init_config(app, config_name)

    with app.app_context():
        init_extensions(app)
        init_blueprints(app)
        init_commands(app)

    return app
Beispiel #23
0
def main():
    '''
    This method registers all the end points of the application
    '''
    app = Flask(__name__)
    app.secret_key = 'some_secret_key'
    api = Api(app)
    jwt = JWT(app, validate_user, get_user_based_on_identity)
    api.add_resource(MyHanlder, '/api/hello')
    return app
Beispiel #24
0
def init_app():
    app = Flask(__name__)

    template_loader = jinja2.FileSystemLoader(["templates", "../templates"])
    app.jinja_loader = template_loader
    app.config.from_envvar("OIDCFED_PROVIDER_CONFIG")

    app.op = init_fed_op(app.config)

    return app
Beispiel #25
0
def init_app():
    app = Flask(__name__)
    app.config.from_object(config)
    app.template_folder = config.template_folder
    handler = RotatingFileHandler(config.log_path,
                                  maxBytes=10000,
                                  backupCount=1)
    handler.setLevel(logging.INFO)
    app.logger.addHandler(handler)
    register_blueprints(app)
    return app
Beispiel #26
0
    def create_app(self):
        app = Flask(self.__class__.__name__)

        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'VERYSECRET'
        app.url_map.strict_slashes = False

        self.register_blueprint(app)

        self.app = app
        return app
Beispiel #27
0
def test_opa_create_with_staticmethod_deny_access():
    app = Flask(__name__)
    opa_url = 'http://localhost:8181/v1/data/dm/allow'
    app.opa = OPA.secure(app, input_function=parse_input, url=opa_url)
    init_app(app)

    responses.add(responses.POST, opa_url, json={'result': False}, status=200)

    response = app.test_client().get('/')

    assert 403 == response.status_code
def init_app(app: Flask):
    # Register database functions with the Flask app
    if not os.path.isdir(app.instance_path):
        # Create the instance directory if it doesn't exist already
        os.mkdir(app.instance_path)
    db_path = os.path.dirname(app.config["DATABASE"])
    if not os.path.isdir(db_path):
        # Create the db directory if it doesn't exist already
        os.mkdir(db_path)
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)
Beispiel #29
0
        def _create_json_record(xml_record):
            object_record = create_record(etree.XML(xml_record))
            app = Flask('hepcrawl')
            app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS',
                                                    {}))
            with app.app_context():
                dojson_record = hep.do(object_record)
                base_uri = self.settings['SCHEMA_BASE_URI']
                dojson_record['$schema'] = base_uri + 'hep.json'

            return dojson_record
Beispiel #30
0
def create_app():
    app = Flask(__name__)
    bootstrap = Bootstrap(app)

    app.config.from_object(Config)

    # login manager inicializando la app
    login_manager.init_app(app)

    # Se registra el nuevo blueprint auth
    app.register_blueprint(auth)

    return app
Beispiel #31
0
    def _parsed_items_from_marcxml(
            self,
            marcxml_records,
            base_url="",
            hostname="",
            url_schema=None,
            ftp_params=None,
            url=""
    ):
        app = Flask('hepcrawl')
        app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS', {}))
        file_name = url.split('/')[-1]

        with app.app_context():
            parsed_items = []
            for xml_record in marcxml_records:
                try:
                    record = marcxml2record(xml_record)
                    parsed_item = ParsedItem(record=record, record_format='hep')
                    parsed_item.ftp_params = ftp_params
                    parsed_item.file_name = file_name

                    files_to_download = [
                        self._get_full_uri(
                            current_url=document['url'],
                            base_url=base_url,
                            schema=url_schema,
                            hostname=hostname,
                        )
                        for document in parsed_item.record.get('documents', [])
                        if self._has_to_be_downloaded(document['url'])
                    ]
                    parsed_item.file_urls = files_to_download

                    self.logger.info('Got the following attached documents to download: %s'% files_to_download)
                    self.logger.info('Got item: %s' % parsed_item)

                    parsed_items.append(parsed_item)

                except Exception as e:
                    tb = ''.join(traceback.format_tb(sys.exc_info()[2]))
                    error_parsed_item = ParsedItem.from_exception(
                        record_format='hep',
                        exception=repr(e),
                        traceback=tb,
                        source_data=xml_record,
                        file_name=file_name
                    )
                    parsed_items.append(error_parsed_item)

            return parsed_items
Beispiel #32
0
    def _parsed_items_from_marcxml(
            self,
            marcxml_records,
            base_url="",
            hostname="",
            url_schema=None,
            ftp_params=None,
            url=""
    ):
        app = Flask('hepcrawl')
        app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS', {}))
        file_name = url.split('/')[-1]

        with app.app_context():
            parsed_items = []
            for xml_record in marcxml_records:
                try:
                    record = marcxml2record(xml_record)
                    parsed_item = ParsedItem(record=record, record_format='hep')
                    parsed_item.ftp_params = ftp_params
                    parsed_item.file_name = file_name

                    files_to_download = [
                        self._get_full_uri(
                            current_url=document['url'],
                            base_url=base_url,
                            schema=url_schema,
                            hostname=hostname,
                        )
                        for document in parsed_item.record.get('documents', [])
                        if self._has_to_be_downloaded(document['url'])
                    ]
                    parsed_item.file_urls = files_to_download

                    self.logger.info('Got the following attached documents to download: %s'% files_to_download)
                    self.logger.info('Got item: %s' % parsed_item)

                    parsed_items.append(parsed_item)

                except Exception as e:
                    tb = ''.join(traceback.format_tb(sys.exc_info()[2]))
                    error_parsed_item = ParsedItem.from_exception(
                        record_format='hep',
                        exception=repr(e),
                        traceback=tb,
                        source_data=xml_record,
                        file_name=file_name
                    )
                    parsed_items.append(error_parsed_item)

            return parsed_items
Beispiel #33
0
def create_app():
    application = Flask(__name__)
    application.secret_key = gen_random_password()
    Bootstrap(application)

    application.register_blueprint(base_bp)
    application.register_blueprint(files_bp)
    application.register_blueprint(helpers_bp)

    return application
Beispiel #34
0
        def _get_crawl_result(xml_record):
            app = Flask('hepcrawl')
            app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS',
                                                    {}))
            with app.app_context():
                item = ParsedItem(record={}, record_format='hep')
                try:
                    item.record = marcxml2record(xml_record)
                except Exception as e:
                    item.exception = repr(e)
                    item.traceback = traceback.format_tb(sys.exc_info()[2])
                    item.source_data = xml_record

            return item
Beispiel #35
0
    def setUp(self):
        app = Flask(__name__)
        app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
        app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
        db = SQLAlchemy()
        db.init_app(app)
        app.app_context().push()
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False

        if not os.getenv("DATABASE_URL"):
            raise RuntimeError("DATABASE_URL is not set")
        self.app = app.test_client()
Beispiel #36
0
def _parsed_item_from_marcxml(marcxml_record, settings):
    app = Flask('hepcrawl')
    app.config.update(settings.getdict('MARC_TO_HEP_SETTINGS', {}))

    with app.app_context():
        try:
            record = cds_marcxml2record(marcxml_record)
            return ParsedItem(record=record, record_format='hep')
        except Exception as e:
            tb = ''.join(traceback.format_tb(sys.exc_info()[2]))
            return ParsedItem.from_exception(record_format='hep',
                                             exception=repr(e),
                                             traceback=tb,
                                             source_data=marcxml_record)
Beispiel #37
0
    def _parsed_items_from_marcxml(self, marcxml_records, base_url="", url=""):
        self.logger.info('parsing record')
        app = Flask('hepcrawl')
        app.config.update(self.settings.getdict('MARC_TO_HEP_SETTINGS', {}))
        file_name = url.split('/')[-1].split("?")[0]

        with app.app_context():
            parsed_items = []
            for xml_record in marcxml_records:
                try:
                    record = marcxml2record(xml_record)
                    parsed_item = ParsedItem(record=record,
                                             record_format='hep')
                    parsed_item.file_name = file_name
                    new_documents = []
                    files_to_download = []
                    self.logger.info("Parsed document: %s", parsed_item.record)
                    self.logger.info("Record have documents: %s", "documents"
                                     in parsed_item.record)
                    for document in parsed_item.record.get('documents', []):
                        if self._is_local_path(document['url']):
                            document['url'] = self._get_full_uri(
                                document['url'])
                            self.logger.info("Updating document %s", document)
                        else:
                            files_to_download.append(document['url'])
                        new_documents.append(document)

                    if new_documents:
                        parsed_item.record['documents'] = new_documents

                    parsed_item.file_urls = files_to_download
                    self.logger.info(
                        'Got the following attached documents to download: %s',
                        files_to_download)
                    self.logger.info('Got item: %s', parsed_item)

                    parsed_items.append(parsed_item)

                except Exception as e:
                    tb = ''.join(traceback.format_tb(sys.exc_info()[2]))
                    error_parsed_item = ParsedItem.from_exception(
                        record_format='hep',
                        exception=repr(e),
                        traceback=tb,
                        source_data=xml_record,
                        file_name=file_name)
                    parsed_items.append(error_parsed_item)

            return parsed_items
Beispiel #38
0
def create_app(config_name):
    app = Flask(__name__)
    print(__name__)
    app.config.from_object(config[config_name])
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    # 初始化db
    db.init_app(app)

    login_manager.init_app(app)
    # 初始化日志配置
    common = LogCommon()
    app = common.init_log(app, 'log')

    # 附加路由和自定义的错误页面
    from app.pyweb.main import main
    app.register_blueprint(main)
    # 定义认证路由
    from app.pyweb.auth import auth
    app.register_blueprint(auth, url_prefix='/auth')
    # 定义Captcha路由
    from app.pyweb.captcha_chinese import captcha
    app.register_blueprint(captcha, url_prefix='/captcha')

    return app
Beispiel #39
0
def stuff_client(app: Flask):
    client = app.test_client()
    user = User("stuff", "*****@*****.**", stuff=True)
    user.set_password("stuffpsw")
    with app.app_context():
        db.session.add(user)
        db.session.commit()
    res = client.post("/auth/token/login",
                      json={
                          "username": "******",
                          "password": "******",
                      })
    assert res.is_json
    token = res.get_json().get("token")
    client.environ_base["HTTP_AUTHORIZATION"] = "Bearer {}".format(token)
    return client
Beispiel #40
0
def app_factory(config):
    '''This factory creates a Flask application instance based on the settings
    in the provided configuration object.'''

    # Create the Flask app, register the blueprint and initialize the
    #     flask-mail service.
    # Blueprints must be used to implement factories (I believe) because
    #     they allow the factory to register the application's routes
    #     before they must be implemented.
    app = Flask(__name__)
    app.config.from_object(config)

    from app.views import web
    app.register_blueprint(web)

    mail.init_app(app)

    # Create the (only) mongodb instance for use by all running applications.
    # Different apps may use different Mongo databases.
    # The production server already has its data, so don't always
    #     call db_reset().
    mongo = PyMongo(app)
    if config.DATA:
        with app.app_context():
            db_reset(mongo, config.DATA)

    # Store the Mongo database object in the Flask globals so that it can
    # be accessed when needed.
    @app.before_request
    def before_request():
        g.mongo = mongo

    # This Jinja2 template must be defined here, on the app, rather than
    # in views.py on the blueprint.
    @app.template_filter('start_token')
    def start_token(name):
        '''This routine returns the substring of the given name up to but not
        including the first slash. If there is no slash, it returns the
        full name. It is used in the templates to find either the page
        name or category.'''
        if (name.find('/') == -1):
            return name
        else:
            return name[:name.find('/')]

    return app
 def setUp(self):
     self.app = Flask(__name__)
     self.app.register_blueprint(emailactivation.views.app)
     self.app.config['SECRET_KEY'] = 'SECRET'
     self.mail = Mail(self.app)
     
     @self.app.route('/index')
     def index():
         return 'index'
class TestNegotiate(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.secret_key = 'test'

    def _mock_headers(self, headers=None, **kwargs):
        if headers is None:
            headers = {}
        ctx = self.app.test_request_context('', headers=headers, **kwargs)
        ctx.push()
class EmailActivationTest(TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.register_blueprint(emailactivation.views.app)
        self.app.config['SECRET_KEY'] = 'SECRET'
        self.mail = Mail(self.app)
        
        @self.app.route('/index')
        def index():
            return 'index'
        
    def testSendEmail(self):
        callback = my_callback
        
        data = {'mail':'*****@*****.**'}
        email = {'subject':'subject', 
                 'sender':'*****@*****.**'}
        with patch('test_activation.my_callback') as c:
            with self.app.test_request_context():
                c.return_value = url_for('index') 
                signature = signature_serialize(callback, data)
                with self.mail.record_messages() as outbox:
                    send_activation_email(self.mail,
                                          '*****@*****.**',
                                          callback=callback,
                                          data=data,
                                          email_context=email,
                                          template_context={},
                                          body_template='test.html')
                                      
                self.assertEquals(1, len(outbox), 'Email was sent')
                self.assertIn(url_for('emailactivation.activation', 
                                      signature=signature, _external=True),
                              outbox[0].body)
                
                with self.app.test_client() as client:
                    response = client.get(url_for('emailactivation.activation', 
                                                   signature=signature,))
                    self.assertEquals(302, response.status_code)
                    self.assertEquals(url_for('index', _external=True), 
                                      response.location)
Beispiel #44
0
def create_app(config: dict = {}, mail_client=None):
    app = Flask(__name__, static_folder='static')

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('ALSERVICE_CONFIG')

    MakoTemplates(app)
    app._mako_lookup = TemplateLookup(directories=[pkg_resources.resource_filename('alservice.service', 'templates')],
                                      input_encoding='utf-8', output_encoding='utf-8',
                                      imports=['from flask_babel import gettext as _'])

    app.al = init_account_linking(app, mail_client)

    babel = Babel(app)
    babel.localeselector(get_locale)
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = pkg_resources.resource_filename('alservice.service',
                                                                                  'data/i18n/locales')

    from .views import account_linking_views
    app.register_blueprint(account_linking_views)

    setup_logging(app.config.get('LOGGING_LEVEL', 'INFO'))

    logger = logging.getLogger(__name__)
    logger.info('Running ALservice version %s', pkg_resources.get_distribution('ALservice').version)

    return app
Beispiel #45
0
def make_app(import_name=__name__, config="homebank.settings.Configuration", debug=False):

    app = Flask(import_name)
    app.config.from_object(config)
    app.config.from_envvar("FLASK_SETTINGS", silent=True)
    app.debug = debug
    app.jinja_env.filters["currency"] = lambda x: "{:,.2f} %s".format(x).replace(",", " ").replace(".", ",") % (
        app.config.get("CURRENCY", "")
    )

    if app.debug:
        import_string("flask.ext.debugtoolbar:DebugToolbarExtension")(app)

    @app.errorhandler(404)
    def not_found(ex):
        return render_template("404.html"), 404

    for blueprint in ["__init__", "accounts", "transactions"]:
        app.register_blueprint(import_string("homebank.blueprints.%s:root" % blueprint))

    login_manager = LoginManager(app=app)
    login_manager.login_view = "index.login"
    login_manager.session_protection = "strong"

    @login_manager.user_loader
    def load_user(uid):
        if uid != app.config["PINCODE"]:
            return None
        return User()

    if not app.debug:
        handler = StreamHandler()
        if "ERROR_LOG" in app.config:
            handler = WatchedFileHandler(app.config["ERROR_LOG"])

        handler.setLevel(WARNING)
        handler.setFormatter(Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
        app.logger.addHandler(handler)

    return app
Beispiel #46
0
    def setup_server(self):
        super(BaseHTTPService, self).setup_server()

        # Create an Flask application for this service using the service name
        self.app = Flask(self.application_name or self.__class__.__name__, template_folder=self.template_folder or None)

        methods = dir(self)
        # Attach each route in the class
        for name in [x for x in methods if x.startswith("route_")]:
            method = getattr(self, name)
            self.app.add_url_rule(method.rule, name, method)
            self.logger.debug("Adding handler '%s' for '%s' rule", name, method.rule)

        # Attach error handlers in the class
        for name in [x for x in methods if x.startswith("error_")]:
            method = getattr(self, name)
            code = int(name.split("_", 2)[1])
            self.app.error_handler_spec[None][code] = method
            self.logger.debug("Adding handler '%s' for error code '%d'", name, code)
    def setUp(self):
        self.app = Flask(__name__)

        self.test_client = self.app.test_client()
        self.init_logging()
        self.init_validator_context()
        self.config = TEST_CONFIG

        self.auth_cookie = None
        load_filters(self.app.jinja_env, self.config)
        self.app_context = self.app.app_context()
        self.app_context.__enter__()
        set_template_loader(self.app.jinja_env)
        init_configuration(self.app, self.config)
        init_blueprints(self.app)
        init_services(self.app)
        init_login_system(self.app)
        init_db(self.app)
        init_plugins()
        self.mailer = celery.conf['MAILER']
        self.mailer.mails = []
        self.sms_sender = celery.conf['SMS_SENDER']
        self.sms_sender.sms = []
        self.user = None
        self.user_profile = None
        UserManager.init(self.config, self.app.logger)
        sql_db.init_app(self.app)
        sql_db.create_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        @self.app.errorhandler(413)
        def catcher(error):
            data_json = json.dumps({"error": {"code": errors.FileToLarge.ERROR_CODE, "message": errors.FileToLarge.ERROR_MESSAGE}})
            result = Response(data_json, mimetype='application/json', status=400)
            result.headers.add('Access-Control-Allow-Credentials', "true")
            result.headers.add('Access-Control-Allow-Origin', "http://%s" % self.config['site_domain'])
            return result
Beispiel #48
0
    def setUp(self):
        self.app = Flask(__name__)

        self.client = self.app.test_client()

        self.db = MongoEngine(self.app)

        with self.app.app_context():
            self.db.connection.drop_database("test")
        # self.db.connection

        class TestCol(db.Document):
            value = db.StringField()

            def __unicode__(self):
                return "TestCol(value={})".format(self.value)

        TestCol.objects.delete()

        TestCol.objects.create(value="1")
        TestCol.objects.create(value="2")

        self.TestCol = TestCol
Beispiel #49
0
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            app = Flask(__name__)

            app.register_blueprint(PeopleBluePrintFactory.create())

            flask_injector = FlaskInjector(
                app=app,
                modules=[DatabaseModule(), ],
            )

            app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
            app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/production.db'

            db.init_app(app)
            with app.app_context():
                db.create_all()

            cls._instance = flask_injector

        return cls._instance
Beispiel #50
0
from flask.app import Flask
from flask.templating import render_template
import urllib2
from flask.globals import request
from bs4 import BeautifulSoup
import sqlite3 as lite
import HTMLParser

DATABASE = 'nc4h.db'
nc4hers = ["Sarah Kotzian","Amy Chilcote","David Herpy Larry Hancock","Michael Yoder","Salim Oden","Shannon McCollum","Mitzi Downing"]

nc4h = Flask(__name__)
nc4h.secret_key = 'nc4h'

@nc4h.route('/')
def home():
    return render_template('home.html')

@nc4h.route('/add')
def add_submission():
    return render_template('index.html')

@nc4h.route('/getname/',methods=["GET"])
def getname():
    url = request.args.get('transferurl')
    usock = urllib2.urlopen(url)
    filer = usock.read();
    parsed_html = BeautifulSoup(filer,  "html5lib")
    my_out = str(parsed_html.find('title')).replace('<title>','').replace('</title>','').replace('|','').replace('NC 4-H Youth Development','')
    h = HTMLParser.HTMLParser()
    s = h.unescape(my_out)
Beispiel #51
0
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from werkzeug.exceptions import BadRequest
 
from gevent import monkey
monkey.patch_all()
 
from socketio.namespace import BaseNamespace
from socketio.server import SocketIOServer
from werkzeug.wsgi import SharedDataMiddleware
from werkzeug.serving import run_with_reloader
 
from flask.app import Flask
from TwitterAPI import TwitterAPI
 
app = Flask(__name__)
app.config['DEBUG'] = True
 
TwitterApi = TwitterAPI(
    'RfJOrhv4ElNAGb4dQnJZ3A',
    'dwEu677epT6xzwWrVu2UwVwNH9FPr6LwDUOippVb4',
    '39249210-Fl4xReKp6Uh0cIUV4rHS3FCh9J8uj9y9DVHwRQSHP',
    'v0XwZ2ma1xdpA35as6a02YR9ihONT55BtjWMLc0Npsr6o'
)
 
def send_tweets(socket, hashtag_value):
    tweets = TwitterApi.request('statuses/filter', {'track': hashtag_value})
 
    for tweet in tweets.get_iterator():
        socket.emit('tweet', tweet)
        gevent.sleep()
Beispiel #52
0
# -*- coding: utf-8 -*-
'''
    MiniTwit
    ~~~~~~~~

    A microblogging applicatoin written with Flask and sqlite3.
'''

# configuration
DATABASE = '../../minitwit.db'
PER_PAGE = 30
DEBUG = True
SECRET_KEY = 'development key'

# create our little applicatoin 
app = Flask(__name__)
app.config.from_object(__name__)    # read configuration from this file
app.config.from_envvar('MINITWIT_SETTING', silent=True)

def connect_db():
    """
    :return: a new connection to the database
    """
    return sqlite3.connect(app.config['DATABASE'])

def init_db():
    """
    Creates the database tables.
    """
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
def run():
    """ daemon run function.

    This function should be called to start the system.
    """

    instance_path = ini_config.get("Flask", "INSTANCE_PATH")

    # app: Flask application object
    logging.debug("initializing the Flask app")
    global globalFlaskApp
    globalFlaskApp = Flask(__name__,
                            instance_path=instance_path,
                            instance_relative_config=True)

    is_debug = ini_config.getboolean("Flask", "DEBUG")
    is_testing = ini_config.getboolean("Flask", "TESTING")
    is_json_sort_keys = ini_config.getboolean("Flask", "JSON_SORT_KEYS")
    max_content_length = ini_config.getint("Flask", "MAX_CONTENT_LENGTH")

    globalFlaskApp.config.update(DEBUG=is_debug,
                                  TESTING=is_testing,
                                  JSON_SORT_KEYS=is_json_sort_keys,
                                  MAX_CONTENT_LENGTH=max_content_length)


    with globalFlaskApp.app_context():

        logging.info("Starting application ...")

        from rgapps.utils.utility import get_log_file_handles
        logger_fds = get_log_file_handles(logging.getLogger())
        logging.debug("Logger file handles fileno [{0}]"
                       .format(logger_fds))

        system = platform.system()

        if system == "Linux":
            logging.info("Server running on Linux.")

            pid_file = ini_config.get("Sensor", "SENSOR_PID_FILE")
            working_dir = ini_config.get("Logging", "WORKING_DIR")

            logging.debug("Instantiating daemon with pid_file [{0}] "
                           "and working_dir [{1}]"
                           .format(pid_file, working_dir))

            import daemon.pidfile

            daemon_context = daemon.DaemonContext(
                working_directory=working_dir,
                umask=0o002,
                pidfile=daemon.pidfile.PIDLockFile(pid_file))

            logging.debug("Setting up daemon signal map")
            daemon_context.signal_map = { signal.SIGTERM: program_cleanup }
            logging.debug("daemon signal map has been setup")

            if (logger_fds):
                logging.debug("setting files_preserve for the log file "
                               "descriptor [{0}]"
                               .format(logger_fds))
                daemon_context.files_preserve = logger_fds

            logging.debug("Starting daemon by opening its context.")
            daemon_context.open()

            logging.info("Calling read_store_readings....")
            read_store_readings()

            logging.debug("Closing the daemon context.")
            daemon_context.close()

        else:
            logging.info("Server running on Windows system ...")
            read_store_readings()

    return
Beispiel #54
0
from flask.app import Flask
from flask.globals import request
from flask.json import jsonify
from flask.templating import render_template
import json
from app_controller import get_app_controller


"""
The REST APIs are defined in this file.
"""

app = Flask(__name__)
app_controller = get_app_controller()

"""
 Called to display movie details on webpage. It returns a random movie from list of movies.
"""
@app.route('/getNextMovie', methods=['GET'])
def get_next_movie():
    session_id = request.args.get('sessionId').encode('utf-8')
    return jsonify(app_controller.get_next_movie(session_id))


"""
 Called to save a rating submitted by user in the db.
"""
@app.route('/saveMovieRating', methods=['POST'])
def save_movie_rating():
    movie_id = request.form['movieId'].encode('utf-8')
    rating = request.form['rating'].encode('utf-8')
class BaseTestCase(TestCase):
    def setUp(self):
        self.app = Flask(__name__)

        self.test_client = self.app.test_client()
        self.init_logging()
        self.init_validator_context()
        self.config = TEST_CONFIG

        self.auth_cookie = None
        load_filters(self.app.jinja_env, self.config)
        self.app_context = self.app.app_context()
        self.app_context.__enter__()
        set_template_loader(self.app.jinja_env)
        init_configuration(self.app, self.config)
        init_blueprints(self.app)
        init_services(self.app)
        init_login_system(self.app)
        init_db(self.app)
        init_plugins()
        self.mailer = celery.conf['MAILER']
        self.mailer.mails = []
        self.sms_sender = celery.conf['SMS_SENDER']
        self.sms_sender.sms = []
        self.user = None
        self.user_profile = None
        UserManager.init(self.config, self.app.logger)
        sql_db.init_app(self.app)
        sql_db.create_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        @self.app.errorhandler(413)
        def catcher(error):
            data_json = json.dumps({"error": {"code": errors.FileToLarge.ERROR_CODE, "message": errors.FileToLarge.ERROR_MESSAGE}})
            result = Response(data_json, mimetype='application/json', status=400)
            result.headers.add('Access-Control-Allow-Credentials', "true")
            result.headers.add('Access-Control-Allow-Origin', "http://%s" % self.config['site_domain'])
            return result

    def tearDown(self):
        sql_db.session.close()
        #sql_db.drop_all()
        for table in reversed(sql_db.metadata.sorted_tables):
            sql_db.engine.execute(table.delete())

        # noinspection PyUnresolvedReferences
        self.app.model_cache_context.clear()
        self.app_context.__exit__(None, None, None)

    def get_test_resource_name(self, name):
        return os.path.join(CURRENT_DIR, 'test_data', name)

    def init_logging(self):
        consoleHandler = logging.StreamHandler()
        consoleHandler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        consoleHandler.setLevel(logging.DEBUG)
        self.app.logger.addHandler(consoleHandler)
        self.app.logger.setLevel(logging.DEBUG)

    def init_validator_context(self):
        self.app.validator_context = ValidatorContext()
        self.app.rendering_context = RenderingContext()
        self.app.model_cache_context = ModelCacheContext()
 def setUp(self):
     self.app = Flask(__name__)
     self.app.secret_key = 'test'
import logging
from flask.app import Flask
from apps.config.apps_config import db_session, log_file


app = Flask(__name__)


from apps.billing.views import mod as billingModule
from apps.login.views import mod as loginModule

app.register_blueprint(billingModule)
app.register_blueprint(loginModule)


@app.teardown_appcontext
def shutdown_session(exception=None):
    log.info("----------------- IN Shutdown session --------------")
    db_session.remove()
    log.info("----------------- AFter RemoveShutdown session --------------")


logging.basicConfig(filename=log_file, level=logging.DEBUG)
log = logging.getLogger()
Beispiel #58
0
import argparse
import urllib
import urllib2
import re

from flask.app import Flask
from flask import request, make_response

app = Flask(__name__)

close_head_regexp = re.compile("</head>", re.IGNORECASE)
href_regexp = re.compile("href\s?=\s?[\"']http://([\w\.]+)(/?.*?)[\"']", re.IGNORECASE | re.MULTILINE)
src_regexp = re.compile("src\s?=\s?[\"'][htps:]*//([\w\.]+)(/?.*?)[\"']", re.IGNORECASE | re.MULTILINE)


PROXY_REQUEST_HEADER_PREFIXES = [
    "x-",
    "cookie",
    "user-agent",
    "cache-control",
]

PROXY_RESPONSE_HEADER_PREFIXES = [
    "x-",
    "content-type",
    "content-disposition",
    "date",
    "expires",
    "pragma",
    "p3p",
    "set-cookie",
Beispiel #59
0
from flask.app import Flask
from flask.ext.admin.base import MenuLink
import settings
from todo_app.admin_views import AdminIndex
from werkzeug.debug import DebuggedApplication
from flask_admin import Admin
from google.appengine.api import users


flask_app = Flask(__name__)
flask_app.config.from_object(settings)

admin = Admin(flask_app, name='TODO', index_view=AdminIndex(url='/admin', name='Home'), )
admin.add_link(MenuLink(name='Logout',url = users.create_logout_url('/')))

if flask_app.config['DEBUG']:
    flask_app.debug = True
    app = DebuggedApplication(flask_app, evalex=True)

app = flask_app

from todo_app import admin_views
from todo_app import views
Beispiel #60
0
from chisubmit.common import ChisubmitException
from chisubmit.common.utils import gen_api_key
from chisubmit.backend.webapp.api.json_encoder import CustomJSONEncoder
from chisubmit.backend.webapp.api.blueprints import api_endpoint

from flask.app import Flask
from flask.ext.sqlalchemy import SQLAlchemy

import wtforms_json
from chisubmit.backend.webapp.auth.testing import TestingAuth
from chisubmit.backend.webapp.auth import set_auth
from chisubmit.backend.webapp.auth.ldap import LDAPAuth

wtforms_json.init()

app = Flask(__name__)
app.json_encoder = CustomJSONEncoder

db = SQLAlchemy(app)

import chisubmit.backend.webapp.api.views
app.register_blueprint(api_endpoint, url_prefix='/api/v0')


class ChisubmitAPIServer(object):

    def __init__(self, debug):
        self.app = app        
        self.db = db
        self.debug = debug