我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.decorators.available_attrs()。
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 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): """ 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): """ 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)
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 api_require_http_methods(request_method_list): """ This is copied verbatim from django.views.decorators.require_http_methods *except* it changes which HTTP response class to return. All of this just to make it possible to always return a JSON response when the request method is not allowed. Also, it's changed to use the f'' string format. """ def decorator(func): @wraps(func, assigned=available_attrs(func)) def inner(request, *args, **kwargs): if request.method not in request_method_list: message = ( f'Method Not Allowed ({request.method}): {request.path}' ) logger.warning( message, extra={'status_code': 405, 'request': request} ) return JsonHttpResponseNotAllowed(request_method_list, { 'error': message, }) return func(request, *args, **kwargs) return inner return decorator
def login_required(func=None, redirect_field_name="next", login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log in page if necessary. """ def decorator(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) return handle_redirect_to_login( request, redirect_field_name=redirect_field_name, login_url=login_url ) return _wrapped_view if func: return decorator(func) return decorator
def profile(simple=None, **params): """ ????????? ??? ?????????????? ???????. ??????: @profile(sql=True) def test(*args, **kwargs): ... """ def decorator(func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): func_fullname = '%s.%s' % (func.__module__, func.__qualname__) with Profile(func_fullname, **params): result = func(*args, **kwargs) return result return inner return decorator(simple) if simple else decorator
def cache_qr_code(): """ Decorator that caches the requested page if a settings named 'QR_CODE_CACHE_ALIAS' exists and is not empty or None. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *view_args, **view_kwargs): cache_enabled = request.GET.get('cache_enabled', True) if cache_enabled and hasattr(settings, 'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS: # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the # page. timeout = settings.CACHES[settings.QR_CODE_CACHE_ALIAS]['TIMEOUT'] response = cache_page(timeout, cache=settings.QR_CODE_CACHE_ALIAS)(view_func)(request, *view_args, **view_kwargs) else: # No cache alias for storing the generated qr code, call the view as is. response = (view_func)(request, *view_args, **view_kwargs) return response return _wrapped_view return decorator
def is_owner(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # assume username is first arg if request.user.is_authenticated(): if request.user.username == kwargs['username']: return view_func(request, *args, **kwargs) protocol = "https" if request.is_secure() else "http" return HttpResponseRedirect("%s://%s" % (protocol, request.get_host())) path = request.build_absolute_uri() login_url = request.build_absolute_uri(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.urlparse(login_url)[:2] current_scheme, current_netloc = urlparse.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, None, REDIRECT_FIELD_NAME) return _wrapped_view
def catch_exception(fun): """ Used as decorator to catch all exceptions and log them without breaking the inner function. Can be disabled by using the fail_silently keyword argument, which won't be passed to inner function. """ @wraps(fun, assigned=available_attrs(fun)) def wrap(*args, **kwargs): if kwargs.pop('fail_silently', True): try: return fun(*args, **kwargs) except Exception as e: logger.exception(e) logger.error('Got exception when running %s(%s, %s): %s.', fun.__name__, args, kwargs, e) else: return fun(*args, **kwargs) return wrap
def catch_api_exception(fun): """ Like catch_exception above, but it logs the exception caught. """ from api.task.utils import task_log_exception # circular imports @wraps(fun, assigned=available_attrs(fun)) def wrap(*args, **kwargs): try: return fun(*args, **kwargs) except Exception as e: logger.exception(e) logger.error('Got exception when running %s(%s, %s): %s.', fun.__name__, args, kwargs, e) for arg in args: if is_request(arg): try: task_log_exception(arg, e, task_id=getattr(e, 'task_id', None)) except Exception as exc: logger.exception(exc) break else: logger.warning('API exception could not be logged into task log') return wrap
def user_allowed_for_project(view_func): """ Check that the user is allowed for the project. If the user is not allowed, the view will be redirected to the standard login page. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): try: slug = kwargs['slug'] except IndexError: raise ImproperlyConfigured project = get_object_or_404(Project, slug=slug) if project.is_allowed(request.user): return view_func(request, *args, **kwargs) if request.user.is_authenticated(): raise PermissionDenied path = request.build_absolute_uri() return redirect_to_login(path) return _wrapped_view
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
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
def digest_hash(): def decorators(func): @wraps(func, assigned=available_attrs(func)) def inner(*args, **kwargs): for arg in args: if isinstance(arg, (Request, HttpRequest)): check = DigestCheck(arg) check.verify() response = func(*args, **kwargs) if response.status_code == 200: builder = sha256() builder.update(response.content) digest = "sha256:%s" % builder.hexdigest().lower() response['Etag'] = digest response['Docker-Content-Digest '] = digest return response return inner return decorators
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 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 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