Here are the examples of the python api django.utils.decorators.available_attrs taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
53 Examples
3
Source : decorators.py
with GNU General Public License v3.0
from canway
with GNU General Public License v3.0
from canway
def escape_exempt(view_func):
"""
转义豁免,被此装饰器修饰的action可以不进行中间件escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_script(view_func):
3
Source : decorators.py
with GNU General Public License v3.0
from canway
with GNU General Public License v3.0
from canway
def escape_script(view_func):
"""
被此装饰器修饰的action会对GET与POST参数进行javascript escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_script = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_url(view_func):
3
Source : decorators.py
with GNU General Public License v3.0
from canway
with GNU General Public License v3.0
from canway
def escape_url(view_func):
"""
被此装饰器修饰的action会对GET与POST参数进行url escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_url = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_exempt_param(*param_list, **param_list_dict):
3
Source : decorators.py
with GNU General Public License v3.0
from canway
with GNU General Public License v3.0
from canway
def escape_exempt_param(*param_list, **param_list_dict):
"""
此装饰器用来豁免某个view函数的某个参数
@param param_list: 参数列表
@return:
"""
def _escape_exempt_param(view_func):
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
if param_list_dict.get("param_list"):
wrapped_view.escape_exempt_param = param_list_dict["param_list"]
else:
wrapped_view.escape_exempt_param = list(param_list)
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
return _escape_exempt_param
3
Source : utils.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def decorate_callable(self, func):
@wraps(func, assigned=available_attrs(func))
def inner(*args, **kwargs):
with self as context:
if self.kwarg_name:
kwargs[self.kwarg_name] = context
return func(*args, **kwargs)
return inner
def __call__(self, decorated):
3
Source : cache.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def cache_control(**kwargs):
def _cache_controller(viewfunc):
@wraps(viewfunc, assigned=available_attrs(viewfunc))
def _cache_controlled(request, *args, **kw):
response = viewfunc(request, *args, **kw)
patch_cache_control(response, **kwargs)
return response
return _cache_controlled
return _cache_controller
def never_cache(view_func):
3
Source : cache.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def never_cache(view_func):
"""
Decorator that adds headers to a response so that it will
never be cached.
"""
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view_func(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
add_never_cache_headers(response)
return response
return _wrapped_view_func
3
Source : clickjacking.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def xframe_options_exempt(view_func):
"""
Modifies a view function by setting a response variable that instructs
XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.
e.g.
@xframe_options_exempt
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
resp.xframe_options_exempt = True
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
3
Source : csrf.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def csrf_exempt(view_func):
"""
Marks a view function as being exempt from the CSRF view protection.
"""
# We could just do view_func.csrf_exempt = True, but decorators
# are nicer if they don't have side-effects, so we return a new
# function.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.csrf_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
3
Source : vary.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def vary_on_cookie(func):
"""
A view decorator that adds "Cookie" to the Vary header of a response. This
indicates that a page's contents depends on cookies. Usage:
@vary_on_cookie
def index(request):
...
"""
@wraps(func, assigned=available_attrs(func))
def inner_func(*args, **kwargs):
response = func(*args, **kwargs)
patch_vary_headers(response, ('Cookie',))
return response
return inner_func
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def user_passes_test(test_func):
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseForbidden()
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def login_required_403(function=None):
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def ratelimit(limit=10,length=86400):
""" The length is in seconds and defaults to a day"""
def decorator(func):
def inner(request, *args, **kwargs):
ip_hash = str(hash(request.META['REMOTE_ADDR']))
result = cache.get(ip_hash)
if result:
result = int(result)
if result == limit:
return HttpResponseForbidden("Ooops too many requests today!")
else:
result +=1
cache.set(ip_hash,result,length)
return func(request,*args,**kwargs)
cache.add(ip_hash,1,length)
return func(request, *args, **kwargs)
return wraps(func, assigned=available_attrs(func))(inner)
return decorator
3
Source : decorators.py
with GNU General Public License v3.0
from guomaoqiu
with GNU General Public License v3.0
from guomaoqiu
def login_exempt(view_func):
"""登录豁免,被此装饰器修饰的action可以不校验登录."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.login_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
3
Source : decorators.py
with GNU General Public License v3.0
from guomaoqiu
with GNU General Public License v3.0
from guomaoqiu
def function_check(func_code):
"""
功能开关装饰器
@param func_code: 功能ID
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
_result, _message = func_check(func_code)
if _result == 1:
return view_func(request, *args, **kwargs)
else:
return _redirect_func_check_failed(request)
return _wrapped_view
return decorator
def _redirect_func_check_failed(request):
3
Source : decorators.py
with GNU General Public License v3.0
from guomaoqiu
with GNU General Public License v3.0
from guomaoqiu
def escape_exempt(view_func):
"""
转义豁免,被此装饰器修饰的action可以不进行中间件escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_texteditor(view_func):
3
Source : decorators.py
with GNU General Public License v3.0
from guomaoqiu
with GNU General Public License v3.0
from guomaoqiu
def escape_texteditor(view_func):
"""
被此装饰器修饰的action会对GET与POST参数作为富文本编辑内容处理
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_script = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_url(view_func):
3
Source : decorators.py
with GNU General Public License v3.0
from guomaoqiu
with GNU General Public License v3.0
from guomaoqiu
def escape_url(view_func):
"""
被此装饰器修饰的action会对GET与POST参数进行url escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_url = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
3
Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def passes_test_decorator(test_func, message):
"""Decorator creator that creates a decorator for checking that
user passes the test, redirecting to login or returning a 403
error. The test function should be on the form fn(user) ->
true/false."""
def decorate(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def inner(request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseRedirect('%s?%s=%s' % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path())))
elif test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
else:
raise PermissionDenied(message)
return inner
return decorate
def role_required(*role_names):
3
Source : transaction.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def __call__(self, func):
@wraps(func, assigned=available_attrs(func))
def inner(*args, **kwargs):
with self:
return func(*args, **kwargs)
return inner
def atomic(using=None, savepoint=True):
3
Source : clickjacking.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def xframe_options_exempt(view_func):
"""
Modifies a view function by setting a response variable that instructs
XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.
e.g.
@xframe_options_exempt
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
resp.xframe_options_exempt = True
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
3
Source : decorators.py
with MIT License
from morphosis-nitmz
with MIT License
from morphosis-nitmz
def user_passes_test(test_func, message=default_message):
"""
Decorator for views that checks that the user passes the given test,
setting a message in case of no success. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if not test_func(request.user):
messages.success(request, message)
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
def login_required_message(function=None, message=default_message):
3
Source : decorators.py
with Apache License 2.0
from unixhot
with Apache License 2.0
from unixhot
def escape_exempt(view_func):
"""
转义豁免,被此装饰器修饰的action可以不进行中间件escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_script(view_func):
3
Source : decorators.py
with Apache License 2.0
from unixhot
with Apache License 2.0
from unixhot
def escape_script(view_func):
"""
被此装饰器修饰的action会对GET与POST参数进行javascript escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_script = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_url(view_func):
3
Source : decorators.py
with Apache License 2.0
from unixhot
with Apache License 2.0
from unixhot
def escape_url(view_func):
"""
被此装饰器修饰的action会对GET与POST参数进行url escape
"""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.escape_url = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def escape_exempt_param(*param_list, **param_list_dict):
3
Source : decorators.py
with Apache License 2.0
from unixhot
with Apache License 2.0
from unixhot
def escape_exempt_param(*param_list, **param_list_dict):
"""
此装饰器用来豁免某个view函数的某个参数
@param param_list: 参数列表
@return:
"""
def _escape_exempt_param(view_func):
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
if param_list_dict.get('param_list'):
wrapped_view.escape_exempt_param = param_list_dict['param_list']
else:
wrapped_view.escape_exempt_param = list(param_list)
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
return _escape_exempt_param
3
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_logged_in():
"""A method decorator that checks that the requesting user is logged in
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self)
return function(self, request, *args, **kwargs)
return wrapper
return decorator
def require_verified_user_access():
3
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_verified_user_access():
"""A method decorator that checks that the requesting user has a verified email address """
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self)
if not check_user_verified(user):
return redirect_to_not_verified(request, view=self)
return function(self, request, *args, **kwargs)
return wrapper
return decorator
def require_superuser():
0
Source : decorators.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
return _wrapped_view
return decorator
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
0
Source : exception.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 500 responses.
This decorator is automatically applied to all middleware to ensure that
no middleware leaks an exception and that the next middleware in the stack
can rely on getting a response instead of an exception.
"""
@wraps(get_response, assigned=available_attrs(get_response))
def inner(request):
try:
response = get_response(request)
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
def response_for_exception(request, exc):
0
Source : clickjacking.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def xframe_options_deny(view_func):
"""
Modifies a view function so its response has the X-Frame-Options HTTP
header set to 'DENY' as long as the response doesn't already have that
header set.
e.g.
@xframe_options_deny
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
if resp.get('X-Frame-Options') is None:
resp['X-Frame-Options'] = 'DENY'
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def xframe_options_sameorigin(view_func):
0
Source : clickjacking.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def xframe_options_sameorigin(view_func):
"""
Modifies a view function so its response has the X-Frame-Options HTTP
header set to 'SAMEORIGIN' as long as the response doesn't already have
that header set.
e.g.
@xframe_options_sameorigin
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
if resp.get('X-Frame-Options') is None:
resp['X-Frame-Options'] = 'SAMEORIGIN'
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def xframe_options_exempt(view_func):
0
Source : http.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def require_http_methods(request_method_list):
"""
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note that request methods should be in uppercase.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
if request.method not in request_method_list:
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return HttpResponseNotAllowed(request_method_list)
return func(request, *args, **kwargs)
return inner
return decorator
require_GET = require_http_methods(["GET"])
0
Source : http.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The ETag function should return a string (or
None if the resource doesn't exist), while the last_modified function
should return a datetime object (or None if the resource doesn't exist).
The ETag function should return a complete ETag, including quotes (e.g.
'"etag"'), since that's the only way to distinguish between weak and strong
ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
to a strong ETag by adding quotes.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (precondition
failed), depending upon the request method. In either case, it will add the
generated ETag and Last-Modified headers to the response if it doesn't
already have them.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
# Compute values (if any) for the requested resource.
def get_last_modified():
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
return timegm(dt.utctimetuple())
# The value from etag_func() could be quoted or unquoted.
res_etag = etag_func(request, *args, **kwargs) if etag_func else None
res_etag = quote_etag(res_etag) if res_etag is not None else None
res_last_modified = get_last_modified()
response = get_conditional_response(
request,
etag=res_etag,
last_modified=res_last_modified,
)
if response is None:
response = func(request, *args, **kwargs)
# Set relevant headers on the response if they don't already exist.
if res_last_modified and not response.has_header('Last-Modified'):
response['Last-Modified'] = http_date(res_last_modified)
if res_etag and not response.has_header('ETag'):
response['ETag'] = res_etag
return response
return inner
return decorator
# Shortcut decorators for common cases based on ETag or Last-Modified only
def etag(etag_func):
0
Source : vary.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def vary_on_headers(*headers):
"""
A view decorator that adds the specified headers to the Vary header of the
response. Usage:
@vary_on_headers('Cookie', 'Accept-language')
def index(request):
...
Note that the header names are not case-sensitive.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner_func(*args, **kwargs):
response = func(*args, **kwargs)
patch_vary_headers(response, headers)
return response
return inner_func
return decorator
def vary_on_cookie(func):
0
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def permission_required(perm, login_url=None, redirect=REDIRECT_FIELD_NAME):
"""A replacement for django.contrib.auth.decorators.permission_required
that doesn't ask authenticated users to log in."""
if not login_url:
login_url = settings.LOGIN_URL
def decorator(view_fn):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
if request.user.has_perm(perm):
return view_fn(request, *args, **kwargs)
t = loader.get_template('403.html')
c = RequestContext(request, {'request_path': request.path})
return HttpResponseForbidden(t.render(c))
path = urlquote(request.get_full_path)
tup = login_url, redirect, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_fn, assigned=available_attrs(view_fn))(_wrapped_view)
return decorator
0
Source : decorators.py
with BSD 3-Clause "New" or "Revised" License
from druids
with BSD 3-Clause "New" or "Revised" License
from druids
def auth_token_renewal_exempt(view_func):
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.auth_token_renewal_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
0
Source : decorators.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
# urlparse chokes on lazy objects in Python 3, force to str
resolved_login_url = force_str(
resolve_url(login_url or settings.LOGIN_URL))
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
return _wrapped_view
return decorator
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
0
Source : clickjacking.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def xframe_options_deny(view_func):
"""
Modifies a view function so its response has the X-Frame-Options HTTP
header set to 'DENY' as long as the response doesn't already have that
header set.
e.g.
@xframe_options_deny
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
if resp.get('X-Frame-Options', None) is None:
resp['X-Frame-Options'] = 'DENY'
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def xframe_options_sameorigin(view_func):
0
Source : clickjacking.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def xframe_options_sameorigin(view_func):
"""
Modifies a view function so its response has the X-Frame-Options HTTP
header set to 'SAMEORIGIN' as long as the response doesn't already have
that header set.
e.g.
@xframe_options_sameorigin
def some_view(request):
...
"""
def wrapped_view(*args, **kwargs):
resp = view_func(*args, **kwargs)
if resp.get('X-Frame-Options', None) is None:
resp['X-Frame-Options'] = 'SAMEORIGIN'
return resp
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
def xframe_options_exempt(view_func):
0
Source : http.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def require_http_methods(request_method_list):
"""
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note that request methods should be in uppercase.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
if request.method not in request_method_list:
logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
extra={
'status_code': 405,
'request': request
}
)
return HttpResponseNotAllowed(request_method_list)
return func(request, *args, **kwargs)
return inner
return decorator
require_GET = require_http_methods(["GET"])
0
Source : http.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The Etag function should return a string (or
None if the resource doesn't exist), whilst the last_modified function
should return a datetime object (or None if the resource doesn't exist).
If both parameters are provided, all the preconditions must be met before
the view is processed.
This decorator will either pass control to the wrapped view function or
return an HTTP 304 response (unmodified) or 412 response (preconditions
failed), depending upon the request method.
Any behavior marked as "undefined" in the HTTP spec (e.g. If-none-match
plus If-modified-since headers) will result in the view function being
called.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
# Get HTTP request headers
if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE")
if if_modified_since:
if_modified_since = parse_http_date_safe(if_modified_since)
if_none_match = request.META.get("HTTP_IF_NONE_MATCH")
if_match = request.META.get("HTTP_IF_MATCH")
if if_none_match or if_match:
# There can be more than one ETag in the request, so we
# consider the list of values.
try:
etags = parse_etags(if_none_match or if_match)
except ValueError:
# In case of invalid etag ignore all ETag headers.
# Apparently Opera sends invalidly quoted headers at times
# (we should be returning a 400 response, but that's a
# little extreme) -- this is Django bug #10681.
if_none_match = None
if_match = None
# Compute values (if any) for the requested resource.
if etag_func:
res_etag = etag_func(request, *args, **kwargs)
else:
res_etag = None
if last_modified_func:
dt = last_modified_func(request, *args, **kwargs)
if dt:
res_last_modified = timegm(dt.utctimetuple())
else:
res_last_modified = None
else:
res_last_modified = None
response = None
if not ((if_match and (if_modified_since or if_none_match)) or
(if_match and if_none_match)):
# We only get here if no undefined combinations of headers are
# specified.
if ((if_none_match and (res_etag in etags or
"*" in etags and res_etag)) and
(not if_modified_since or
(res_last_modified and if_modified_since and
res_last_modified < = if_modified_since))):
if request.method in ("GET", "HEAD"):
response = HttpResponseNotModified()
else:
logger.warning('Precondition Failed: %s', request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif if_match and ((not res_etag and "*" in etags) or
(res_etag and res_etag not in etags)):
logger.warning('Precondition Failed: %s', request.path,
extra={
'status_code': 412,
'request': request
}
)
response = HttpResponse(status=412)
elif (not if_none_match and request.method == "GET" and
res_last_modified and if_modified_since and
res_last_modified < = if_modified_since):
response = HttpResponseNotModified()
if response is None:
response = func(request, *args, **kwargs)
# Set relevant headers on the response if they don't already exist.
if res_last_modified and not response.has_header('Last-Modified'):
response['Last-Modified'] = http_date(res_last_modified)
if res_etag and not response.has_header('ETag'):
response['ETag'] = quote_etag(res_etag)
return response
return inner
return decorator
# Shortcut decorators for common cases based on ETag or Last-Modified only
def etag(etag_func):
0
Source : vary.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def vary_on_headers(*headers):
"""
A view decorator that adds the specified headers to the Vary header of the
response. Usage:
@vary_on_headers('Cookie', 'Accept-language')
def index(request):
...
Note that the header names are not case-sensitive.
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner_func(*args, **kwargs):
response = func(*args, **kwargs)
patch_vary_headers(response, headers)
return response
return inner_func
return decorator
def vary_on_cookie(func):
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_admin_access_decorator(group_url_arg='group'):
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(request, *args, **kwargs):
group_name = kwargs.get(group_url_arg, None)
if not group_name:
return HttpResponseNotFound(_("No team provided"))
group = get_group_for_request(group_name, request)
user = request.user
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self, group=group)
if check_object_write_access(group, user):
kwargs['group'] = group
return function(request, *args, **kwargs)
# Access denied, redirect to 403 page and and display an error message
return redirect_to_403(request, self, group=group)
return wrapper
return decorator
def require_logged_in():
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_superuser():
"""A method decorator that checks that the requesting user is a superuser (admin or portal admin)
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self)
if not check_user_superuser(user):
raise PermissionDenied('You do not have permission to access this page.')
return function(self, request, *args, **kwargs)
return wrapper
return decorator
def require_portal_manager():
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_portal_manager():
"""A method decorator that checks that the requesting user is a portal manager or superuser (admin or portal admin)
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self)
if not check_user_portal_manager(user) and not check_user_superuser(user):
raise PermissionDenied('You do not have permission to access this page.')
return function(self, request, *args, **kwargs)
return wrapper
return decorator
def dispatch_group_access(group_url_kwarg='group', group_attr='group'):
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def dispatch_group_access(group_url_kwarg='group', group_attr='group'):
"""A method decorator that takes the group name from the kwargs of a
dispatch function in CBVs and performs no priviledge checks
Additionally this function populates the group instance to the view
instance as attribute `group_attr`
:param str group_url_kwarg: The name of the key containing the group name.
Defaults to `'group'`.
:param str group_attr: The attribute name which can later be used to access
the group from within an view instance (e.g. `self.group`). Defaults to
`'group'`.
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
group_name = kwargs.get(group_url_kwarg, None)
if not group_name:
return HttpResponseNotFound(_("No team provided"))
group = get_group_for_request(group_name, request)
deactivated_app_error = _check_deactivated_app_access(self, group, request)
if deactivated_app_error:
return deactivated_app_error
setattr(self, group_attr, group)
return function(self, request, *args, **kwargs)
return wrapper
return decorator
def require_admin_access(group_url_kwarg=None, group_attr=None):
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_admin_access(group_url_kwarg=None, group_attr=None):
"""A method decorator that takes the group name from the kwargs of a
dispatch function in CBVs and checks that the requesting user is allowed to
perform administrative operations.
Additionally this function populates the group instance to the view
instance as attribute `group_attr`
:param str group_url_kwarg: The name of the key containing the group name.
Defaults to `'group'`.
:param str group_attr: The attribute name which can later be used to access
the group from within an view instance (e.g. `self.group`). Defaults to
`'group'`.
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
url_kwarg = group_url_kwarg or getattr(self, 'group_url_kwarg', 'group')
attr = group_attr or getattr(self, 'group_attr', 'group')
group_name = kwargs.get(url_kwarg, None)
if not group_name:
return HttpResponseNotFound(_("No team provided"))
group = get_group_for_request(group_name, request)
user = request.user
deactivated_app_error = _check_deactivated_app_access(self, group, request)
if deactivated_app_error:
return deactivated_app_error
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self, group=group)
if check_object_write_access(group, user):
setattr(self, attr, group)
return function(self, request, *args, **kwargs)
# Access denied, redirect to 403 page and and display an error message
return redirect_to_403(request, self, group=group)
return wrapper
return decorator
def require_read_access(group_url_kwarg=None, group_attr=None):
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_read_access(group_url_kwarg=None, group_attr=None):
"""A method decorator that takes the group name from the kwargs of a
dispatch function in CBVs and checks that the requesting user is allowed to
perform read operations.
Additionally this function populates the group instance to the view
instance as attribute `group_attr`
:param str group_url_kwarg: The name of the key containing the group name.
Defaults to `'group'`.
:param str group_attr: The attribute name which can later be used to access
the group from within an view instance (e.g. `self.group`). Defaults to
`'group'`.
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
url_kwarg = group_url_kwarg or getattr(self, 'group_url_kwarg', 'group')
attr = group_attr or getattr(self, 'group_attr', 'group')
group_name = kwargs.get(url_kwarg, None)
if not group_name:
return HttpResponseNotFound(_("No team provided"))
group = get_group_for_request(group_name, request)
user = request.user
# this is why almost every BaseTaggableObject's View has a .group attribute:
setattr(self, attr, group)
# record visit to group for this user
if user.is_authenticated and hasattr(group, 'mark_visited'):
group.mark_visited(user)
requested_object = None
try:
requested_object = self.get_object()
except (AttributeError, TypeError):
pass
except CosinnusPermissionDeniedException:
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self, group=group)
else:
return redirect_to_403(request, self, group=group)
obj_public = requested_object and getattr(requested_object, 'media_tag', None) \
and requested_object.media_tag.visibility == BaseTagObject.VISIBILITY_ALL
# catch anyonymous users trying to navigate to private groups (else self.get_object() throws a Http404!)
if not (obj_public or group.public or user.is_authenticated):
return redirect_to_not_logged_in(request, view=self, group=group)
deactivated_app_error = _check_deactivated_app_access(self, group, request)
if deactivated_app_error:
return deactivated_app_error
if requested_object:
if check_object_read_access(requested_object, user):
return function(self, request, *args, **kwargs)
else:
if check_object_read_access(group, user):
return function(self, request, *args, **kwargs)
# Access denied, redirect to 403 page and and display an error message
return redirect_to_403(request, self, group=group)
return wrapper
return decorator
def require_write_access(group_url_kwarg=None, group_attr=None):
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_write_access(group_url_kwarg=None, group_attr=None):
"""A method decorator that takes the group name from the kwargs of a
dispatch function in CBVs and checks that the requesting user is allowed to
perform write operations.
Additionally this function populates the group instance to the view
instance as attribute `group_attr`
:param str group_url_kwarg: The name of the key containing the group name.
Defaults to `'group'`.
:param str group_attr: The attribute name which can later be used to access
the group from within an view instance (e.g. `self.group`). Defaults to
`'group'`.
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
url_kwarg = group_url_kwarg or getattr(self, 'group_url_kwarg', 'group')
attr = group_attr or getattr(self, 'group_attr', 'group')
group_name = kwargs.get(url_kwarg, None)
if not group_name:
return HttpResponseNotFound(_("No team provided"))
group = get_group_for_request(group_name, request)
user = request.user
# set the group attr
setattr(self, attr, group)
# catch anyonymous users trying to naviagte to private groups (else self.get_object() throws a Http404!)
if not group.public and not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self, group=group)
deactivated_app_error = _check_deactivated_app_access(self, group, request)
if deactivated_app_error:
return deactivated_app_error
requested_object = None
try:
requested_object = self.get_object()
except (AttributeError, TypeError):
pass
# objects can never be written by non-logged in members
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self, group=group)
if requested_object:
# editing/deleting an object, check if we are owner or staff member or group admin or site admin
if check_object_write_access(requested_object, user):
return function(self, request, *args, **kwargs)
else:
# creating a new object, check if we can create objects in the group
if check_group_create_objects_access(group, user):
return function(self, request, *args, **kwargs)
# Access denied, redirect to 403 page and and display an error message
return redirect_to_403(request, self, group=group)
return wrapper
return decorator
def require_write_access_groupless():
0
Source : views.py
with GNU Affero General Public License v3.0
from wechange-eg
with GNU Affero General Public License v3.0
from wechange-eg
def require_write_access_groupless():
"""A method decorator that takes the requested object of i.e. an edit or delete view in the
dispatch function and checks that the requesting user is allowed to
perform write operations.
"""
def decorator(function):
@functools.wraps(function, assigned=available_attrs(function))
def wrapper(self, request, *args, **kwargs):
user = request.user
# catch anyonymous users trying to naviagte here
if not user.is_authenticated:
return redirect_to_not_logged_in(request, view=self)
requested_object = None
try:
requested_object = self.get_object()
except (AttributeError, TypeError):
pass
if requested_object:
# editing/deleting an object, check if we are owner or staff member or group admin or site admin
if check_object_write_access(requested_object, user):
return function(self, request, *args, **kwargs)
# Access denied, redirect to 403 page and and display an error message
return redirect_to_403(request, self)
return wrapper
return decorator
def require_user_token_access(token_name, group_url_kwarg='group', group_attr='group', id_url_kwarg=None):
See More Examples