当前位置: 首页>>代码示例>>Python>>正文


Python Flask.app_context方法代码示例

本文整理汇总了Python中flask.app.Flask.app_context方法的典型用法代码示例。如果您正苦于以下问题:Python Flask.app_context方法的具体用法?Python Flask.app_context怎么用?Python Flask.app_context使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask.app.Flask的用法示例。


在下文中一共展示了Flask.app_context方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: parse_node

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
    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
开发者ID:drjova,项目名称:hepcrawl,代码行数:28,代码来源:cds_spider.py

示例2: _parsed_items_from_marcxml

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
    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
开发者ID:drjova,项目名称:hepcrawl,代码行数:53,代码来源:desy_spider.py

示例3: app_factory

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
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
开发者ID:Calvin-CS,项目名称:csweb,代码行数:48,代码来源:__init__.py

示例4: __new__

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
    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
开发者ID:drimer,项目名称:example-codes,代码行数:23,代码来源:container.py

示例5: run

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
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
开发者ID:rubensgomes,项目名称:misc-python-projs,代码行数:80,代码来源:sensorapp.py

示例6: BaseTestCase

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
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()
开发者ID:StanislavKraev,项目名称:jb_code,代码行数:67,代码来源:base_test_case.py

示例7: SimpleFlaskAppTest

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
class SimpleFlaskAppTest(unittest.TestCase):

    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

    def _parse(self, resp):
        resp = resp.decode("utf-8")
        return json.loads(resp)

    def test_validation_mongoengine_will_work_with_model_serializer(self):

        class Doc(db.Document):
            value = db.StringField(validation=RegexpValidator(r"\d+", message="Bad value").for_mongoengine())

        Doc.drop_collection()

        class Serializer(ModelSerializer):
            class Meta:
                model = Doc

        Doc.objects.create(value="123")

        s = Serializer(data={"value": "asd"})
        self.assertEqual(s.validate(), False)
        self.assertEqual(s.errors, {"value": ["Bad value"]})

    def test_resource_decorator(self):

        class S(BaseSerializer):

            field = fields.StringField(required=True)

        @self.app.route("/test", methods=["POST"])
        @validate(S)
        def resource(cleaned_data):
            return "OK"

        resp = self.client.post("/test", data=json.dumps({}), headers={"Content-Type": "application/json"})
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(
            json.loads(resp.data.decode("utf-8")), {'field': ['Field is required']}
        )

    def testSimpleResourceAndRouter(self):

        router = DefaultRouter(self.app)

        class Resource(BaseResource):

            def get(self, request):
                return "GET"

            def post(self, request):
                return "POST"

            def put(self, request):
                return "PUT"

            def patch(self, request):
                return "PATCH"

            def delete(self, request):
                return "DELETE"

            @list_route(methods=["GET", "POST"])
            def listroute(self, request):
                return "LIST"

            @detail_route(methods=["GET", "POST"])
            def detailroute(self, request, pk):
                return "detail"

        self.assertSetEqual(
            set(Resource.get_allowed_methods()), {"get", "post", "put", "patch", "delete"}
        )

        router.register("/test", Resource, "test")

        for method in ["get", "post", "put", "patch", "delete"]:
#.........这里部分代码省略.........
开发者ID:wnorales,项目名称:Python,代码行数:103,代码来源:test_flask_app.py

示例8: str

# 需要导入模块: from flask.app import Flask [as 别名]
# 或者: from flask.app.Flask import app_context [as 别名]
        if os.environ['SERVER_SOFTWARE'].startswith('Dev'):
            return constants.ENV_LOCAL
        elif os.environ['SERVER_SOFTWARE'].startswith('Google App Engine/'):
            #For considering an environment staging we assume the version id
            # contains -staging and the URL
            current_version_id = str(os.environ['CURRENT_VERSION_ID']) if (
                'CURRENT_VERSION_ID') in os.environ else ''
            if '-staging' in current_version_id:
                return constants.ENV_STAGING
            #If not local or staging then is production TODO: really?
            return constants.ENV_PRODUCTION
    return constants.ENV_LOCAL

flask_app = Flask(__name__)
flask_app.json_encoder = CustomJSONEncoder
with flask_app.app_context():
    environment = get_environment()
    #Load settings from the corresponding class
    if environment == constants.ENV_PRODUCTION:
        flask_app.config.from_object(ProductionConfig)
    else:
        flask_app.config.from_object(TestingConfig)
    #If debug then enable
    if flask_app.config['DEBUG']:
        flask_app.debug = True
        app = DebuggedApplication(flask_app, evalex=True)
    app = flask_app
    from google.appengine.ext.deferred import application as deferred_app
    import admin_views
    import views
开发者ID:dcifuen,项目名称:gentlemeet,代码行数:32,代码来源:__init__.py


注:本文中的flask.app.Flask.app_context方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。