本文整理匯總了Python中flask.Flask方法的典型用法代碼示例。如果您正苦於以下問題:Python flask.Flask方法的具體用法?Python flask.Flask怎麽用?Python flask.Flask使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask
的用法示例。
在下文中一共展示了flask.Flask方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create_app
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def create_app(config_name):
app = Flask(__name__)
#app.config['JSON_AS_ASCII'] = False
# 進行app配置 把自己的config設定導入到app中
app.config.from_object(config[config_name])
# 初始化app配置
config[config_name].init_app(app)
db.init_app(app)
db.app = app
# 初始化apscheduler
scheduler.init_app(app)
scheduler.start()
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .job import main as job_blueprint
app.register_blueprint(job_blueprint,url_prefix='/v1/cron/job')
return app
示例2: create_app
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def create_app():
"""Construct the core flask_session_tutorial."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
# Initialize Plugins
db.init_app(app)
login_manager.init_app(app)
sess.init_app(app)
with app.app_context():
from . import routes
from . import auth
from .assets import compile_static_assets, compile_auth_assets
app.register_blueprint(routes.main_bp)
app.register_blueprint(auth.auth_bp)
# Create static asset bundles
compile_static_assets(app)
compile_auth_assets(app)
# Create Database Models
db.create_all()
return app
示例3: make_web
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def make_web(queue):
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen():
while True:
frame = queue.get()
_, frame = cv2.imencode('.JPEG', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
try:
app.run(host='0.0.0.0', port=8889)
except:
print('unable to open port')
示例4: create_app
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def create_app(config_object=ProdConfig):
"""An application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/
:param config_object: The configuration object to use.
"""
app = Flask(__name__)
sslify = SSLify(app)
# set config from the passed object
app.config.from_object(config_object)
# set additional config values from environ
app.config['SLACK_WEBHOOK_URL'] = os.environ.get('SLACK_WEBHOOK_URL')
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
register_template_globals(app)
@app.before_first_request
def before_first_request():
register_logging(app)
return app
示例5: create_user
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def create_user(**data):
"""Creates user with encrypted password"""
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkdf2:sha256'
)
# Here you insert the `data` in your users database
# for this simple example we are recording in a json file
db_users = json.load(open('users.json'))
# add the new created user to json
db_users[data['username']] = data
# commit changes to database
json.dump(db_users, open('users.json', 'w'))
return data
# [--- Flask Factories ---]
示例6: _users_for_repo
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def _users_for_repo(user, repo_name, oldest_age=55):
""" Returns users that have commited in a repo in the last N weeks """
since = (datetime.now() - timedelta(weeks=oldest_age)).isoformat()
r = await github.commits_for_repo(user, repo_name, since=since)
r_json = await r.json()
users = set()
for commit in r_json:
if "author" in commit and commit["author"] is not None:
user = (
commit["author"]["login"],
commit["commit"]["author"]["email"],
commit["commit"]["author"]["name"],
)
users.add(user)
return list(users)
# Flask routes
示例7: __init__
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def __init__(self):
self.app = Flask(__name__)
custom_errors = {
'JsonInvalidError': {
'status': 500,
'message': 'JSON format not valid'
},
'JsonRequiredError': {
'status': 400,
'message': 'JSON input required'
}
}
self.api = swagger.docs(Api(self.app, errors=custom_errors), apiVersion=API_VERSION_NUMBER)
self.api.add_resource(DummyEndpoint, '/dummy', endpoint='dummy')
self.api.add_resource(HelloEndpoint, '/hello', endpoint='hello')
示例8: create_app
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def create_app():
app = Flask(__name__)
@app.route('/foo')
@api.validate()
def foo():
pass
@app.route('/bar')
@api_strict.validate()
def bar():
pass
@app.route('/lone', methods=['GET'])
def lone_get():
pass
@app.route('/lone', methods=['POST'])
def lone_post():
pass
return app
示例9: __init__
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def __init__(self, gateway, config, connector_type):
super().__init__()
self.__log = log
self._default_converters = {
"uplink": "JsonRESTUplinkConverter",
"downlink": "JsonRESTDownlinkConverter"
}
self.__config = config
self._connector_type = connector_type
self.statistics = {'MessagesReceived': 0,
'MessagesSent': 0}
self.__gateway = gateway
self.__USER_DATA = {}
self.setName(config.get("name", 'REST Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
self._connected = False
self.__stopped = False
self.daemon = True
self._app = Flask(self.get_name())
self._api = Api(self._app)
self.__rpc_requests = []
self.__attribute_updates = []
self.__fill_requests_from_TB()
self.endpoints = self.load_endpoints()
self.load_handlers()
示例10: make_config
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def make_config(self, instance_relative=False):
"""Used to create the config attribute by the Flask constructor.
The `instance_relative` parameter is passed in from the constructor
of Flask (there named `instance_relative_config`) and indicates if
the config should be relative to the instance path or the root path
of the application.
.. versionadded:: 0.8
"""
root_path = self.root_path
if instance_relative:
root_path = self.instance_path
defaults = dict(self.default_config)
defaults['ENV'] = get_env()
defaults['DEBUG'] = get_debug_flag()
return self.config_class(root_path, defaults)
示例11: update_template_context
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def update_template_context(self, context):
"""Update the template context with some commonly used variables.
This injects request, session, config and g into the template
context as well as everything template context processors want
to inject. Note that the as of Flask 0.6, the original values
in the context will not be overridden if a context processor
decides to return a value with the same key.
:param context: the context as a dictionary that is updated in place
to add extra variables.
"""
funcs = self.template_context_processors[None]
reqctx = _request_ctx_stack.top
if reqctx is not None:
bp = reqctx.request.blueprint
if bp is not None and bp in self.template_context_processors:
funcs = chain(funcs, self.template_context_processors[bp])
orig_ctx = context.copy()
for func in funcs:
context.update(func())
# make sure the original values win. This makes it possible to
# easier add new variables in context processors without breaking
# existing views.
context.update(orig_ctx)
示例12: make_shell_context
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def make_shell_context(self):
"""Returns the shell context for an interactive shell for this
application. This runs all the registered shell context
processors.
.. versionadded:: 0.11
"""
rv = {'app': self, 'g': g}
for processor in self.shell_context_processors:
rv.update(processor())
return rv
#: What environment the app is running in. Flask and extensions may
#: enable behaviors based on the environment, such as enabling debug
#: mode. This maps to the :data:`ENV` config key. This is set by the
#: :envvar:`FLASK_ENV` environment variable and may not behave as
#: expected if set in code.
#:
#: **Do not enable development when deploying in production.**
#:
#: Default: ``'production'``
示例13: test_cli_runner
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def test_cli_runner(self, **kwargs):
"""Create a CLI runner for testing CLI commands.
See :ref:`testing-cli`.
Returns an instance of :attr:`test_cli_runner_class`, by default
:class:`~flask.testing.FlaskCliRunner`. The Flask app object is
passed as the first argument.
.. versionadded:: 1.0
"""
cls = self.test_cli_runner_class
if cls is None:
from flask.testing import FlaskCliRunner as cls
return cls(self, **kwargs)
示例14: process_response
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def process_response(self, response):
"""Can be overridden in order to modify the response object
before it's sent to the WSGI server. By default this will
call all the :meth:`after_request` decorated functions.
.. versionchanged:: 0.5
As of Flask 0.5 the functions registered for after request
execution are called in reverse order of registration.
:param response: a :attr:`response_class` object.
:return: a new response object or the same, has to be an
instance of :attr:`response_class`.
"""
ctx = _request_ctx_stack.top
bp = ctx.request.blueprint
funcs = ctx._after_request_functions
if bp is not None and bp in self.after_request_funcs:
funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
if None in self.after_request_funcs:
funcs = chain(funcs, reversed(self.after_request_funcs[None]))
for handler in funcs:
response = handler(response)
if not self.session_interface.is_null_session(ctx.session):
self.session_interface.save_session(self, ctx.session, response)
return response
示例15: assert_request
# 需要導入模塊: import flask [as 別名]
# 或者: from flask import Flask [as 別名]
def assert_request(
app: web.Application, idx: int, method: str, path: str, headers: Optional[Dict[str, str]] = None
) -> None:
request = get_incoming_requests(app)[idx]
assert request.method == method
if request.method == "GET":
# Ref: #200
# GET requests should not contain bodies
if not isinstance(app, Flask):
if not isinstance(request.content, EmptyStreamReader):
assert request.content._read_nowait(-1) != b"{}"
else:
assert request.data == b""
assert request.path == path
if headers:
for key, value in headers.items():
assert request.headers.get(key) == value