本文整理汇总了Python中flask.render_template_string方法的典型用法代码示例。如果您正苦于以下问题:Python flask.render_template_string方法的具体用法?Python flask.render_template_string怎么用?Python flask.render_template_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.render_template_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def __call__(self, obj):
"""
Extract a value from `obj` and return the formatted value.
"""
# Extract value from the object.
value = self.expr(**{x: getattr(obj, x)
for x in dir(obj)
if not x.startswith('_')})
if value is None:
if self.raise_on_err:
raise AttributeError(self.path)
# Get a template, maybe
template = (self.template if self.template
else implicit_templates.get(type(value)))
if template:
return render_template_string(template, value=value)
else:
return value
示例2: render_graphiql
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def render_graphiql(
params,
result,
graphiql_version=None,
graphiql_template=None,
graphiql_html_title=None,
):
graphiql_version = graphiql_version or GRAPHIQL_VERSION
template = graphiql_template or TEMPLATE
return render_template_string(
template,
graphiql_version=graphiql_version,
graphiql_html_title=graphiql_html_title,
result=result,
params=params,
)
示例3: test_template_filters
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_template_filters():
template = """
Dollar: {{ 0.1 | dollar }}<br>
Sum Key: {{ data | sum_key('col') }}<br>
Max Key: {{ data | max_key('col') }}<br>
Average Key: {{ data | average_key('col') }}<br>
"""
data = [
dict(col=0),
dict(col=0.5),
dict(col=0.5),
dict(col=1),
]
with current_app.app_context():
html = render_template_string(template, data=data)
assert 'Dollar: $0.10<br>' in html
assert 'Sum Key: 2.0<br>' in html
assert 'Max Key: 1<br>' in html
assert 'Average Key: 0.5<br>' in html
示例4: test_method_view
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_method_view(app, client):
# auth_required with flask method view
from flask.views import MethodView
from flask import render_template_string
class MyView(MethodView):
decorators = [auth_required("token", "session")]
def get(self):
return render_template_string("Hi view")
myview = MyView.as_view("myview")
app.add_url_rule("/myview", view_func=myview, methods=["GET"])
response = client.get("/myview", follow_redirects=False)
# should require login
assert response.status_code == 302
assert "/login" in response.location
authenticate(client)
response = client.get("/myview")
assert response.status_code == 200
assert b"Hi view" in response.data
示例5: login
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def login():
template = """
{{ get_flashed_messages() }}
{{ form.errors }}
<form method="POST">
<label>Username{{ form.username() }}</label>
<label>Password{{ form.password() }}</label>
{{ form.submit() }}
{{ form.hidden_tag() }}
</form>
"""
# Instantiate a LDAPLoginForm which has a validator to check if the user
# exists in LDAP.
form = LDAPLoginForm()
if form.validate_on_submit():
# Successfully logged in, We can now access the saved user object
# via form.user.
login_user(form.user) # Tell flask-login to log them in.
return redirect("/") # Send them home
return render_template_string(template, form=form)
示例6: send_test_template
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def send_test_template():
'''
Sends a test template to the provided address
'''
form = SendTestTemplateForm(request.form)
if form.validate_on_submit():
report = EmailReport.make_sample()
try:
subject = render_template_string(form.subject.data, report=report)
text = render_template_string(form.text.data, report=report)
email_provider.send(
to=form.recipient.data,
sender=g.user.email(),
subject=subject,
body=text)
return jsonify({'success': True, 'message': 'Sent test email.'})
except Exception as e:
return json_error(400, str(e), {})
return json_error(400, list_errors(form), {})
示例7: test_as_filter
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_as_filter(self):
'''URL helpers should exists as filter'''
url = url_for('site.home', one='value')
assert_urls_equal(
render_template_string(
"{{ url|url_rewrite(one='other-value') }}", url=url),
url_for('site.home', one='other-value')
)
assert_urls_equal(
render_template_string(
"{{ url|url_add(two='other-value') }}", url=url),
url_for('site.home', one='value', two='other-value')
)
assert_urls_equal(
render_template_string("{{ url|url_del('one') }}", url=url),
url_for('site.home')
)
示例8: test_as_global
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_as_global(self):
'''URL helpers should exists as global function'''
url = url_for('site.home', one='value')
assert_urls_equal(
render_template_string(
"{{ url_rewrite(url, one='other-value') }}", url=url),
url_for('site.home', one='other-value')
)
assert_urls_equal(
render_template_string(
"{{ url_add(url, two='other-value') }}", url=url),
url_for('site.home', one='value', two='other-value')
)
assert_urls_equal(
render_template_string("{{ url_del(url, 'one') }}", url=url),
url_for('site.home')
)
示例9: test_as_global_default
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_as_global_default(self, app):
'''URL helpers should exists as global function without url param'''
url = url_for('site.home', one='value')
with app.test_request_context(url):
assert_urls_equal(
render_template_string("{{ url_rewrite(one='other-value') }}"),
full_url('site.home', one='other-value')
)
assert_urls_equal(
render_template_string("{{ url_add(two='other-value') }}"),
full_url('site.home', one='value', two='other-value')
)
assert_urls_equal(
render_template_string("{{ url_del(None, 'one') }}"),
full_url('site.home')
)
assert render_template_string("{{ in_url('one') }}") == 'True'
assert render_template_string("{{ in_url('one') }}") == 'True'
assert render_template_string("{{ in_url('two') }}") == 'False'
示例10: test_i18n_alternate_links
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_i18n_alternate_links(self, app, client):
test = I18nBlueprint('test', __name__)
@test.route('/i18n/<key>/')
def i18n(key):
return render_template_string('{{ i18n_alternate_links() }}')
app.register_blueprint(test)
app.config['DEFAULT_LANGUAGE'] = 'en'
app.config['LANGUAGES'] = {
'en': 'English',
'fr': 'Français',
'de': 'German',
}
response = client.get(url_for('test.i18n', key='value', param='other'))
link = ('<link rel="alternate" '
'href="/{lang}/i18n/value/?param=other" '
'hreflang="{lang}" />')
assert response.data.decode('utf8') == ''.join([link.format(lang='fr'),
link.format(lang='de')])
示例11: test_i18n_alternate_links_outside_i18n_blueprint
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def test_i18n_alternate_links_outside_i18n_blueprint(self, app, client):
test = Blueprint('test', __name__)
@test.route('/not-i18n/<key>/')
def i18n(key):
return render_template_string('{{ i18n_alternate_links() }}')
app.register_blueprint(test)
app.config['DEFAULT_LANGUAGE'] = 'en'
app.config['LANGUAGES'] = {
'en': 'English',
'fr': 'Français',
'de': 'German',
}
response = client.get(url_for('test.i18n', key='value', param='other'))
assert response.data == b''
示例12: action_succeeded
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def action_succeeded(message=None, status_code=200):
"""Generate html (for GET request) or json (for POST requests) response with a custom success message.
Args:
message (str): custom success message
status_code (int): the http status code to return
Returns:
Tuple[Union[str,flask.Response],int]: rendered html code or json Response object and http code
with a success message
"""
if request.method == "POST":
response = {"status": "ok"}
if message:
response["msg"] = message
return jsonify(response), status_code
template = (
"<h2>{{ message }}</h2> "
"<p>Note: This feature is still early in development, "
"please reach out to Security if you have any feedback.</p>"
)
return render_template_string(template, message=message), status_code
示例13: action_failed
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def action_failed(message=None, status_code=500):
"""Generate html (for GET request) or json (for POST requests) response with a custom failure message.
Args:
message (str): custom failure message
status_code (int): the http status code to return
Returns:
Tuple[Union[str,flask.Response],int]: rendered html code or json Response object and http code
with an error message
"""
if request.method == "POST":
response = {"status": "error"}
if message:
response["message"] = message
return jsonify(response), status_code
template = (
"<h2>Something went wrong: {{ message }}</h2> "
"<p>Please complete the action by emailing to Security.</p>"
"<p>Note: This feature is still early in development, "
"please reach out to Security if you have any feedback.</p>"
)
return render_template_string(template, message=message), status_code
示例14: deploy_query
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def deploy_query(redis_key = None):
try:
Key_incr = '%s_incr' % redis_key
Redis.expire(redis_key,30)
if Redis.lrange(redis_key,0,-1):
data = Redis.rpop(redis_key)
if '_End_' in data:
Redis.expire(redis_key,3)
return render_template_string(data)
else:
Redis.incr(Key_incr, 1)
if int(Redis.get(Key_incr)) >10000:
Redis.delete(Key_incr)
return render_template_string("_End_")
return render_template_string("")
except Exception as e:
logging.error(e)
return redirect(url_for('error'))
示例15: publish_query
# 需要导入模块: import flask [as 别名]
# 或者: from flask import render_template_string [as 别名]
def publish_query(secret_key=None):
try:
Msg_Key = 'op_publish_msg_%s' %secret_key
Key_incr = '%s_incr' % Msg_Key
Redis.expire(Msg_Key,30)
if Redis.lrange(Msg_Key,0,-1):
data = Redis.rpop(Msg_Key)
if '_End_' in str(data):
Redis.expire(Msg_Key,3)
return render_template_string(data)
else:
Redis.incr(Key_incr, 1)
if int(Redis.get(Key_incr)) >10000:
Redis.delete(Key_incr)
return render_template_string("_End_")
return render_template_string("")
except Exception as e:
logging.error(e)
return render_template_string(e)