Source code for flask.ext.admin.helpers
from re import sub
from jinja2 import contextfunction
from flask import g, request, url_for
from wtforms.validators import DataRequired, InputRequired
from flask.ext.admin._compat import urljoin, urlparse
from ._compat import string_types
def set_current_view(view):
g._admin_view = view
[docs]def get_current_view():
"""
Get current administrative view.
"""
return getattr(g, '_admin_view', None)
def get_url(endpoint, **kwargs):
"""
Alternative to Flask `url_for`.
If there's current administrative view, will call its `get_url`. If there's none - will
use generic `url_for`.
:param endpoint:
Endpoint name
:param kwargs:
View arguments
"""
view = get_current_view()
if not view:
return url_for(endpoint, **kwargs)
return view.get_url(endpoint, **kwargs)
[docs]def is_field_error(errors):
"""
Check if wtforms field has error without checking its children.
:param errors:
Errors list.
"""
for e in errors:
if isinstance(e, string_types):
return True
return False
@contextfunction
[docs]def resolve_ctx(context):
"""
Resolve current Jinja2 context and store it for general consumption.
"""
g._admin_render_ctx = context
[docs]def get_render_ctx():
"""
Get view template context.
"""
return getattr(g, '_admin_render_ctx', None)
def prettify_class_name(name):
"""
Split words in PascalCase string into separate words.
:param name:
String to split
"""
return sub(r'(?<=.)([A-Z])', r' \1', name)
def is_safe_url(target):
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
return (test_url.scheme in ('http', 'https') and
ref_url.netloc == test_url.netloc)
def get_redirect_target(param_name='url'):
target = request.values.get(param_name)
if target and is_safe_url(target):
return target