當前位置: 首頁>>代碼示例>>Python>>正文


Python app.Flask類代碼示例

本文整理匯總了Python中flask.app.Flask的典型用法代碼示例。如果您正苦於以下問題:Python Flask類的具體用法?Python Flask怎麽用?Python Flask使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Flask類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: parse_node

    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,代碼行數:26,代碼來源:cds_spider.py

示例2: __init__

 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)
開發者ID:fikani,項目名稱:pycomponents,代碼行數:7,代碼來源:core.py

示例3: BaseHTTPService

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")
開發者ID:CoreSecurity,項目名稱:HoneySAP,代碼行數:35,代碼來源:service.py

示例4: create_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
開發者ID:gitter-badger,項目名稱:hepdata-converter-ws,代碼行數:8,代碼來源:__init__.py

示例5: init_app

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
開發者ID:its-dirg,項目名稱:oidc-fed,代碼行數:10,代碼來源:rp.py

示例6: build_app

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
開發者ID:praetoria,項目名稱:mittn,代碼行數:10,代碼來源:server.py

示例7: init_app

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
開發者ID:its-dirg,項目名稱:oidc-fed,代碼行數:10,代碼來源:op.py

示例8: create_app

    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
開發者ID:pprolancer,項目名稱:orangeapp,代碼行數:11,代碼來源:__init__.py

示例9: _parsed_items_from_marcxml

    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,代碼行數:51,代碼來源:desy_spider.py

示例10: app_factory

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,代碼行數:46,代碼來源:__init__.py

示例11: setUp

 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'
開發者ID:tomasd,項目名稱:flask-emailactivation,代碼行數:9,代碼來源:test_activation.py

示例12: TestNegotiate

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()
開發者ID:jlebleu,項目名稱:xivo-confd,代碼行數:11,代碼來源:tests_flask_negotiate.py

示例13: EmailActivationTest

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 protected]'}
        email = {'subject':'subject', 
                 'sender':'[email protected]'}
        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,
                                          '[email protected]',
                                          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)
開發者ID:tomasd,項目名稱:flask-emailactivation,代碼行數:41,代碼來源:test_activation.py

示例14: create_app

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
開發者ID:its-dirg,項目名稱:ALservice,代碼行數:29,代碼來源:wsgi.py

示例15: make_app

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
開發者ID:rembish,項目名稱:homebank-wui,代碼行數:40,代碼來源:app.py


注:本文中的flask.app.Flask類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。