本文整理匯總了Python中flask.current_app.testing方法的典型用法代碼示例。如果您正苦於以下問題:Python current_app.testing方法的具體用法?Python current_app.testing怎麽用?Python current_app.testing使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask.current_app
的用法示例。
在下文中一共展示了current_app.testing方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __call__
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def __call__(self, form, field):
if current_app.testing:
return True
if request.json:
response = request.json.get('g-recaptcha-response', '')
else:
response = request.form.get('g-recaptcha-response', '')
remote_ip = request.remote_addr
if not response:
raise ValidationError(field.gettext(self.message))
if not self._validate_recaptcha(response, remote_ip):
field.recaptcha_error = 'incorrect-captcha-sol'
raise ValidationError(field.gettext(self.message))
示例2: password_recovery
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def password_recovery():
''' creates a password_recovery_hash and sends email to user (assumes login=email)'''
post_data = request.get_json()
if not post_data:
raise InvalidPayload()
email = post_data.get('email')
if not email:
raise InvalidPayload()
# fetch the user data
user = User.first_by(email=email)
if user:
token = user.encode_password_token()
with session_scope(db.session):
user.token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
if not current_app.testing:
from project.api.common.utils.mails import send_password_recovery_email
send_password_recovery_email(user, token.decode()) # send recovery email
return {
'status': 'success',
'message': 'Successfully sent email with password recovery.',
}
else:
raise NotFoundException(message='Login/email does not exist, please write a valid login/email')
示例3: email_verification
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def email_verification(user_id):
''' creates a email_token_hash and sends email with token to user (assumes login=email), idempotent (could be use for resend)'''
post_data = request.get_json()
if not post_data:
raise InvalidPayload()
email = post_data.get('email')
if not email:
raise InvalidPayload()
# fetch the user data
user = User.first_by(email=email)
if user:
token = user.encode_email_token()
with session_scope(db.session):
user.email_token_hash = bcrypt.generate_password_hash(token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()
if not current_app.testing:
from project.api.common.utils.mails import send_email_verification_email
send_email_verification_email(user, token.decode()) # send recovery email
return {
'status': 'success',
'message': 'Successfully sent email with email verification.',
}
else:
raise NotFoundException(message='Login/email does not exist, please write a valid login/email')
示例4: redirect_to_ssl
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def redirect_to_ssl(self):
"""
Redirect incoming requests to HTTPS.
"""
criteria = [
request.is_secure,
current_app.debug,
current_app.testing,
request.headers.get("X-Forwarded-Proto", "http") == "https",
]
if (
request.headers.get("User-Agent", "")
.lower()
.startswith(self.exclude_user_agents)
):
return
if not any(criteria):
if request.url.startswith("http://"):
url = request.url.replace("http://", "https://", 1)
r = redirect(url, code=301)
return r
示例5: insecure_transport
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def insecure_transport(self):
"""Creates a context to enable the oauthlib environment variable in
order to debug with insecure transport.
"""
origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT')
if current_app.debug or current_app.testing:
try:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
yield
finally:
if origin:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin
else:
os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None)
else:
if origin:
warnings.warn(
'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ '
'but the app is not running in debug mode or testing mode.'
' It may put you in danger of the Man-in-the-middle attack'
' while using OAuth 2.', RuntimeWarning)
yield
示例6: save
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def save(self, check_status=True, **kwargs):
# While used in async method, app context is not available by default
# and needs to be imported
from flask import current_app as app
from kqueen.server import create_app
try:
if not app.testing:
app = create_app()
except RuntimeError:
app = create_app()
with app.app_context():
if check_status:
self.state = self.engine_status(save=False)
self.verbose_name = getattr(self.get_engine_cls(), 'verbose_name', self.engine)
return super().save(**kwargs)
#
# AUTHENTICATION
#
示例7: fetch_data
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def fetch_data(gs, url):
"""Fetches a URL from Kubernetes (production) or reads it from a file (test).
The file name is derived from the URL in the following way:
The file name is 'testdata/' + last element of the URL + '.input.json'.
For example, if the URL is 'https://host:port/api/v1beta3/path/to/resource',
then the file name is 'testdata/resource.input.json'.
The input is always JSON. It is converted to an internal representation
by this routine.
Args:
gs: global state.
url: the URL to fetch from Kubernetes in production.
Returns:
The contents of the URL (in production) or the contents of the file
(in a test).
Raises:
IOError: if cannot open the test file.
ValueError: if cannot convert the contents of the file to JSON.
Other exceptions may be raised as the result of attempting to
fetch the URL.
"""
start_time = time.time()
if app.testing:
# Read the data from a file.
url_elements = url.split('/')
fname = 'testdata/' + url_elements[-1] + '.input.json'
v = json.loads(open(fname, 'r').read())
gs.add_elapsed(start_time, fname, time.time() - start_time)
return v
else:
# Send the request to Kubernetes
headers = get_kubernetes_headers()
v = requests.get(url, headers=headers, verify=False).json()
gs.add_elapsed(start_time, url, time.time() - start_time)
return v
示例8: create_users
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def create_users():
if current_app.testing:
return
db.create_all()
user_datastore.create_role(
name="admin",
permissions={"admin-read", "admin-write", "user-read", "user-write"},
)
user_datastore.create_role(name="monitor", permissions={"admin-read", "user-read"})
user_datastore.create_role(name="user", permissions={"user-read", "user-write"})
user_datastore.create_role(name="reader", permissions={"user-read"})
user_datastore.create_user(
email="admin@me.com", password=hash_password("password"), roles=["admin"]
)
user_datastore.create_user(
email="ops@me.com", password=hash_password("password"), roles=["monitor"]
)
real_user = user_datastore.create_user(
email="user@me.com", password=hash_password("password"), roles=["user"]
)
user_datastore.create_user(
email="reader@me.com", password=hash_password("password"), roles=["reader"]
)
# create initial blog
blog = app.blog_cls(text="my first blog", user=real_user)
db.session.add(blog)
db.session.commit()
print(f"First blog id {blog.id}")
# Views
# Note that we always add @auth_required so that if a client isn't logged in
# we will get a proper '401' and redirected to login page.
示例9: __init__
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def __init__(self, *args, **kwargs):
if current_app.testing:
self.TIME_LIMIT = None
super().__init__(*args, **kwargs)
示例10: __init__
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def __init__(self, data_name):
if ChatAPI.bot_name != data_name:
ChatAPI.bot_name = data_name
ChatAPI.bot = web_bot.FrozenBot(frozen_model_dir=data_name,
is_testing=current_app.testing)
config = ChatAPI.bot.config
_ = get_database_model('Chatbot',
filter=ChatAPI.bot_name,
dataset=config['dataset'],
**config['model_params'])
db.session.commit()
# TODO: delete this after refactor rest of file.
session['data_name'] = data_name
示例11: register_user_cellphone
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def register_user_cellphone(user_id: int):
''' generates cellphone_validation_code, idempotent (could be used for resend cellphone_validation_code)
allows just 1 user per cellphone validation!
'''
post_data = request.get_json()
if not post_data:
raise InvalidPayload()
cellphone_number = post_data.get('cellphone_number')
cellphone_cc = post_data.get('cellphone_cc')
if not cellphone_number or not cellphone_cc:
raise InvalidPayload()
user = User.get(user_id)
if user.cellphone_validation_date and user.cellphone_number == cellphone_number and user.cellphone_cc == cellphone_cc:
raise BusinessException(message='Registered. You have already registered this cellphone number.')
cellphone_validation_code, cellphone_validation_code_expiration = User.generate_cellphone_validation_code()
with session_scope(db.session) as session:
user.cellphone_number = cellphone_number
user.cellphone_cc = cellphone_cc
user.cellphone_validation_code = cellphone_validation_code
user.cellphone_validation_code_expiration = cellphone_validation_code_expiration
user.cellphone_validation_date = None
if not current_app.testing:
from project.api.common.utils.twilio import send_cellphone_verification_code
send_cellphone_verification_code(user, cellphone_validation_code)
return {
'status': 'success',
'message': 'Successfully sent validation code.'
}
示例12: verify_cms_signers
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def verify_cms_signers(f):
"""Verify the signers of a request containing a CMS/PKCS#7, DER encoded body.
The certificate of each signer is placed on the global **g** variable as **g.signers** and the signed data is
set as **g.signed_data**.
In unit tests, this decorator is completely disabled by the presence of testing = True
Raises:
- TypeError if *Content-Type* header is not "application/pkcs7-signature"
- SigningError if any signer on the CMS content is not valid.
"""
@wraps(f)
def decorator(*args, **kwargs):
if current_app.testing:
return f(*args, **kwargs)
current_app.logger.debug('Verifying CMS Request Data for request to %s', request.url)
if request.headers['Content-Type'] != "application/pkcs7-signature":
raise TypeError("verify_cms_signers expects application/pkcs7-signature, got: {}".format(
request.headers['Content-Type']))
g.signers, g.signed_data = _verify_cms_signers(request.data)
return f(*args, **kwargs)
return decorator
示例13: verify_mdm_signature
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def verify_mdm_signature(f):
"""Verify the signature supplied by the client in the request using the ``Mdm-Signature`` header.
If the authenticity of the message has been verified,
then the signer is attached to the **g** object as **g.signer**.
In unit tests, this decorator is completely disabled by the presence of app.testing = True.
You can also disable enforcement in dev by setting the flask setting DEBUG to true.
:reqheader Mdm-Signature: BASE64-encoded CMS Detached Signature of the message. (if `SignMessage` was true)
"""
@wraps(f)
def decorator(*args, **kwargs):
if current_app.testing:
return f(*args, **kwargs)
if 'Mdm-Signature' not in request.headers:
raise TypeError('Client did not supply an Mdm-Signature header but signature is required.')
detached_signature = b64decode(request.headers['Mdm-Signature'])
try:
signers, signed_data = _verify_cms_signers(detached_signature, detached=True)
g.signers = signers
g.signed_data = signed_data
except InvalidSignature as e:
current_app.logger.warn("Invalid Signature in Mdm-Signature header")
if not current_app.config.get('DEBUG', False):
return abort(403)
return f(*args, **kwargs)
return decorator
示例14: _send_mail_async
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def _send_mail_async(subject_or_message=None, to=None, template=None, **kwargs):
subject_or_message = subject_or_message or kwargs.pop('subject')
if current_app and current_app.testing:
return async_mail_task.apply([subject_or_message, to, template], kwargs)
return async_mail_task.delay(subject_or_message, to, template, **kwargs)
示例15: __init__
# 需要導入模塊: from flask import current_app [as 別名]
# 或者: from flask.current_app import testing [as 別名]
def __init__(self, *args, **kwargs):
if app.testing:
self.TIME_LIMIT = None
super().__init__(*args, **kwargs)