本文整理汇总了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
示例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)
示例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")
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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'
示例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()
示例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)
示例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
示例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