本文整理汇总了Python中flask.current_app.test_request_context方法的典型用法代码示例。如果您正苦于以下问题:Python current_app.test_request_context方法的具体用法?Python current_app.test_request_context怎么用?Python current_app.test_request_context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.current_app
的用法示例。
在下文中一共展示了current_app.test_request_context方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def create():
'''Create a new user'''
data = {
'first_name': click.prompt('First name'),
'last_name': click.prompt('Last name'),
'email': click.prompt('Email'),
'password': click.prompt('Password', hide_input=True),
'password_confirm': click.prompt('Confirm Password', hide_input=True),
}
# Until https://github.com/mattupstate/flask-security/issues/672 is fixed
with current_app.test_request_context():
form = RegisterForm(MultiDict(data), meta={'csrf': False})
if form.validate():
data['password'] = encrypt_password(data['password'])
del data['password_confirm']
data['confirmed_at'] = datetime.utcnow()
user = datastore.create_user(**data)
success('User(id={u.id} email={u.email}) created'.format(u=user))
return user
errors = '\n'.join('\n'.join(e) for e in form.errors.values())
exit_with_error('Error creating user', errors)
示例2: get_auth_cookies
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def get_auth_cookies(user: "User") -> List[Dict[Any, Any]]:
# Login with the user specified to get the reports
with current_app.test_request_context("/login"):
login_user(user)
# A mock response object to get the cookie information from
response = Response()
current_app.session_interface.save_session(current_app, session, response)
cookies = []
# Set the cookies in the driver
for name, value in response.headers:
if name.lower() == "set-cookie":
cookie = parse_cookie(value)
cookies.append(cookie["session"])
return cookies
示例3: get_emails
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def get_emails(self, user):
"""
Gets the verified email addresses of the authenticated GitHub user.
"""
with current_app.test_request_context("/"):
login_user(user)
return self.session.get("user/emails", all_pages=True)
示例4: validate
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def validate():
'''Validate the Swagger/OpenAPI specification with your config'''
with current_app.test_request_context():
schema = json.loads(json.dumps(api.__schema__))
try:
schemas.validate(schema)
success('API specifications are valid')
except schemas.SchemaValidationError as e:
exit_with_error('API specifications are not valid', e)
示例5: bulk_invite_user_to_service
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def bulk_invite_user_to_service(file_name, service_id, user_id, auth_type, permissions):
# permissions
# manage_users | manage_templates | manage_settings
# send messages ==> send_texts | send_emails | send_letters
# Access API keys manage_api_keys
# platform_admin
# view_activity
# "send_texts,send_emails,send_letters,view_activity"
from app.invite.rest import create_invited_user
file = open(file_name)
for email_address in file:
data = {
'service': service_id,
'email_address': email_address.strip(),
'from_user': user_id,
'permissions': permissions,
'auth_type': auth_type,
'invite_link_host': current_app.config['ADMIN_BASE_URL']
}
with current_app.test_request_context(
path='/service/{}/invite/'.format(service_id),
method='POST',
data=json.dumps(data),
headers={"Content-Type": "application/json"}
):
try:
response = create_invited_user(service_id)
if response[1] != 201:
print("*** ERROR occurred for email address: {}".format(email_address.strip()))
print(response[0].get_data(as_text=True))
except Exception as e:
print("*** ERROR occurred for email address: {}. \n{}".format(email_address.strip(), e))
file.close()
示例6: get_url_path
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def get_url_path(view: str, **kwargs: Any) -> str:
with current_app.test_request_context():
return headless_url(url_for(view, **kwargs))
示例7: url_for
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def url_for(*args, **kwargs):
"""url_for replacement that works even when there is no request context.
"""
if '_external' not in kwargs:
kwargs['_external'] = False
reqctx = _request_ctx_stack.top
if reqctx is None:
if kwargs['_external']:
raise RuntimeError('Cannot generate external URLs without a '
'request context.')
with current_app.test_request_context():
return _url_for(*args, **kwargs)
return _url_for(*args, **kwargs)
示例8: get
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def get(self):
"""
An OEmbed compliant API endpoint
See: http://oembed.com/
Support datasets and reuses URLs
"""
args = oembed_parser.parse_args()
if args['format'] != 'json':
return {'message': 'Only JSON format is supported'}, 501
url = args['url']
# Fix flask not detecting URL with https://domain:443/
if 'https:' in url and ':443/' in url:
url = url.replace(':443/', '/')
with current_app.test_request_context(url) as ctx:
if not ctx.request.endpoint:
return {'message': 'Unknown URL "{0}"'.format(url)}, 404
endpoint = ctx.request.endpoint.replace('_redirect', '')
view_args = ctx.request.view_args
if endpoint not in self.ROUTES:
return {'message': 'The URL "{0}" does not support oembed'.format(url)}, 404
param, prefix = self.ROUTES[endpoint]
item = view_args[param]
if isinstance(item, Exception):
if isinstance(item, HTTPException):
return {
'message': 'An error occured on URL "{0}": {1}'.format(url, str(item))
}, item.code
raise item
width = maxwidth = 1000
height = maxheight = 200
params = {
'width': width,
'height': height,
'item': item,
'type': prefix
}
params[param] = item
html = theme.render('oembed.html', **params)
return {
'type': 'rich',
'version': '1.0',
'html': html,
'width': width,
'height': height,
'maxwidth': maxwidth,
'maxheight': maxheight,
}
示例9: run_email_result_task
# 需要导入模块: from flask import current_app [as 别名]
# 或者: from flask.current_app import test_request_context [as 别名]
def run_email_result_task(index_name, sketch_id=None):
"""Create email Celery task.
This task is run after all sketch analyzers are done and emails
the result of all analyzers to the user who imported the data.
Args:
index_name: An index name.
sketch_id: A sketch ID (optional).
Returns:
Email sent status.
"""
# We need to get a fake request context so that url_for() will work.
with current_app.test_request_context():
searchindex = SearchIndex.query.filter_by(index_name=index_name).first()
sketch = None
try:
to_username = searchindex.user.username
except AttributeError:
logging.warning('No user to send email to.')
return ''
if sketch_id:
sketch = Sketch.query.get(sketch_id)
subject = 'Timesketch: [{0:s}] is ready'.format(searchindex.name)
# TODO: Use jinja templates.
body = 'Your timeline [{0:s}] has been imported and is ready.'.format(
searchindex.name)
if sketch:
view_urls = sketch.get_view_urls()
view_links = []
for view_url, view_name in iter(view_urls.items()):
view_links.append('<a href="{0:s}">{1:s}</a>'.format(
view_url,
view_name))
body = body + '<br><br><b>Sketch</b><br>{0:s}'.format(
sketch.external_url)
analysis_results = searchindex.description.replace('\n', '<br>')
body = body + '<br><br><b>Analysis</b>{0:s}'.format(
analysis_results)
if view_links:
body = body + '<br><br><b>Views</b><br>' + '<br>'.join(
view_links)
try:
send_email(subject, body, to_username, use_html=True)
except RuntimeError as e:
return repr(e)
return 'Sent email to {0:s}'.format(to_username)