django.utils.functional.wraps

Here are the examples of the python api django.utils.functional.wraps taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: talk.org
Source File: cache.py
View license
def cache_control(**kwargs):

    def _cache_controller(viewfunc):

        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return _cache_controller

Example 2

Project: talk.org
Source File: cache.py
View license
def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return wraps(view_func)(_wrapped_view_func)

Example 3

Project: talk.org
Source File: http.py
View license
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):
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return wraps(func)(inner)
    return decorator

Example 4

Project: talk.org
Source File: vary.py
View license
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):
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return wraps(func)(inner_func)
    return decorator

Example 5

Project: talk.org
Source File: vary.py
View license
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):
            ...
    """
    def inner_func(*args, **kwargs):
        response = func(*args, **kwargs)
        patch_vary_headers(response, ('Cookie',))
        return response
    return wraps(func)(inner_func)

Example 6

Project: classic.rhizome.org
Source File: decorators.py
View license
def user_passes_membership_test(test_func, membershp_url="/membership_required/", 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):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)                
            path = urlquote(request.get_full_path())
            return HttpResponseRedirect('%s' % membershp_url)
        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
    return decorator

Example 7

Project: snowy
Source File: revisions.py
View license
    def create_on_success(self, func):
        """Creates a revision when the given function exist successfully."""
        def _create_on_success(*args, **kwargs):
            self.start()
            try:
                try:
                    result = func(*args, **kwargs)
                except:
                    self.invalidate()
                    raise
            finally:
                self.end()
            return result
        return wraps(func)(_create_on_success)

Example 8

Project: transifex
Source File: decorators.py
View license
def method_decorator(decorator):
    """
    Converts a function decorator into a method decorator
    """
    def _dec(func):
        def _wrapper(self, *args, **kwargs):
            def bound_func(*args2, **kwargs2):
                return func(self, *args2, **kwargs2)
            # bound_func has the signature that 'decorator' expects i.e.  no
            # 'self' argument, but it is a closure over self so it can call
            # 'func' correctly.
            return decorator(bound_func)(*args, **kwargs)
        return wraps(func)(_wrapper)
    update_wrapper(_dec, decorator)
    # Change the name to aid debugging.
    _dec.__name__ = 'method_decorator(%s)' % decorator.__name__
    return _dec

Example 9

Project: django-cachetree
Source File: invalidation.py
View license
def no_invalidation(function):
    """Function decorator that disables invalidation for the duration of the
    function.
    """
    def wrapper(*args, **kwargs):
        if cachetree_settings.INVALIDATE and not cachetree_settings.DISABLE:
            Invalidator.disconnect_signals()
        returned = function(*args, **kwargs)
        if cachetree_settings.INVALIDATE and not cachetree_settings.DISABLE:
            Invalidator.connect_signals()
        return returned
    return wraps(function)(wrapper)

Example 10

Project: django-failover
Source File: decorators.py
View license
def log_errors(function):
    """Decorator that catches and logs error in the wrapped
    function.
    """
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except Exception, e:
            logger.error(
                "Error in {0}.{1}: {2}".format(
                    function.__module__, function.__name__,e),
                exc_info=e,
            )
            
    return wraps(function)(wrapper)

Example 11

Project: django-failover
Source File: decorators.py
View license
def monitor(function):
    """Decorator that performs monitoring before calling the wrapped
    function.
    """
    from monitor import ServiceMonitor
    def wrapper(*args, **kwargs):
        ServiceMonitor.monitor()
        return function(*args, **kwargs)
    return wraps(function)(wrapper)

Example 12

Project: django-failover
Source File: decorators.py
View license
def recover_from_outages(function):
    """Decorator that attempts to recover from outages for services that are
    down, but does not perform monitoring of services that are not down.
    Intended for cases where discovery of outages is handled in some other
    way (for example, via exception logging).
    """
    from monitor import ServiceMonitor
    def wrapper(*args, **kwargs):
        ServiceMonitor.monitor(outages_only=True)
        return function(*args, **kwargs)
    return wraps(function)(wrapper)

########################################################################

Example 13

Project: django-nonrel
Source File: cache.py
View license
def cache_control(**kwargs):
    def _cache_controller(viewfunc):
        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response
        return wraps(viewfunc, assigned=available_attrs(viewfunc))(_cache_controlled)
    return _cache_controller

Example 14

Project: django-nonrel
Source File: cache.py
View license
def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view_func)

Example 15

Project: django-nonrel
Source File: csrf.py
View license
def csrf_response_exempt(view_func):
    """
    Modifies a view function so that its response is exempt
    from the post-processing of the CSRF middleware.
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.csrf_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)

Example 16

Project: django-nonrel
Source File: csrf.py
View license
def csrf_view_exempt(view_func):
    """
    Marks a view function as being exempt from 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)

Example 17

Project: django-nonrel
Source File: vary.py
View license
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):
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return wraps(func, assigned=available_attrs(func))(inner_func)
    return decorator

Example 18

Project: django-nonrel
Source File: vary.py
View license
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):
            ...
    """
    def inner_func(*args, **kwargs):
        response = func(*args, **kwargs)
        patch_vary_headers(response, ('Cookie',))
        return response
    return wraps(func, assigned=available_attrs(func))(inner_func)

Example 19

Project: hue
Source File: views.py
View license
def check_has_write_access_permission(view_func):
  """
  Decorator ensuring that the user is not a read only user.
  """
  def decorate(request, *args, **kwargs):
    if not has_write_access(request.user):
      raise PopupException(_('You are not allowed to modify the metastore.'), detail=_('You have must have metastore:write permissions'), error_code=301)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 20

Project: hue
Source File: decorators.py
View license
def check_editor_access_permission(view_func):

  def decorate(request, *args, **kwargs):
    if not request.user.is_superuser and request.user.has_hue_permission(action="disable_editor_access", app="oozie"):
      raise PopupException(_('Missing permission to access the Oozie Editor'), error_code=401)
    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 21

Project: hue
Source File: decorators.py
View license
def check_action_access_permission(view_func):
  """
  Decorator ensuring that the user has access to the workflow action.

  Arg: 'workflow action' id.
  Return: the workflow action or raise an exception

  Notice: its gets an id in input and returns the full object in output (not an id).
  """
  def decorate(request, *args, **kwargs):
    action_id = kwargs.get('action')
    action = Node.objects.get(id=action_id).get_full_node()
    Job.objects.can_read_or_exception(request, action.workflow.id)
    kwargs['action'] = action

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 22

Project: hue
Source File: decorators.py
View license
def check_action_edition_permission(view_func):
  """
  Decorator ensuring that the user has the permissions to modify a workflow action.

  Need to appear below @check_action_access_permission
  """
  def decorate(request, *args, **kwargs):
    action = kwargs.get('action')
    Job.objects.can_edit_or_exception(request, action.workflow)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 23

Project: hue
Source File: decorators.py
View license
def check_dataset_access_permission(view_func):
  """
  Decorator ensuring that the user has access to dataset.

  Arg: 'dataset'.
  Return: the dataset or raise an exception

  Notice: its gets an id in input and returns the full object in output (not an id).
  """
  def decorate(request, *args, **kwargs):
    dataset = kwargs.get('dataset')
    if dataset is not None:
      dataset = Dataset.objects.can_read_or_exception(request, dataset)
    kwargs['dataset'] = dataset

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 24

Project: hue
Source File: decorators.py
View license
def check_dataset_edition_permission(authorize_get=False):
  """
  Decorator ensuring that the user has the permissions to modify a dataset.
  A dataset can be edited if the coordinator that owns the dataset can be edited.

  Need to appear below @check_dataset_access_permission
  """
  def inner(view_func):
    def decorate(request, *args, **kwargs):
      dataset = kwargs.get('dataset')
      if dataset is not None and not (authorize_get and request.method == 'GET'):
        Job.objects.can_edit_or_exception(request, dataset.coordinator)

      return view_func(request, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

Example 25

Project: hue
Source File: dashboard.py
View license
def show_oozie_error(view_func):
  def decorate(request, *args, **kwargs):
    try:
      return view_func(request, *args, **kwargs)
    except RestException, ex:
      LOG.exception("Error communicating with Oozie in %s", view_func.__name__)

      detail = ex._headers.get('oozie-error-message', ex)
      if 'Max retries exceeded with url' in str(detail) or 'Connection refused' in str(detail):
        detail = _('The Oozie server is not running')
      raise PopupException(_('An error occurred with Oozie.'), detail=detail)
  return wraps(view_func)(decorate)

Example 26

Project: hue
Source File: decorators.py
View license
def allow_viewer_only(view_func):
  def decorate(request, *args, **kwargs):

    collection_json = json.loads(request.POST.get('collection', '{}'))

    if collection_json['id']:
      try:
        doc2 = Document2.objects.get(id=collection_json['id'])
        if USE_NEW_EDITOR.get():
          doc2.can_read_or_exception(request.user)
        else:
          doc2.doc.get().can_read_or_exception(request.user)
      except Document2.DoesNotExist:
        message = _("Dashboard does not exist or you don't have the permission to access it.")
        raise PopupException(message)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 27

Project: hue
Source File: decorators.py
View license
def allow_owner_only(view_func):
  def decorate(request, *args, **kwargs):

    collection_json = json.loads(request.POST.get('collection', '{}'))

    if collection_json['id']:
      try:
        doc2 = Document2.objects.get(id=collection_json['id'])
        if USE_NEW_EDITOR.get():
          doc2.can_write_or_exception(request.user)
        else:
          doc2.doc.get().can_write_or_exception(request.user)
      except Document2.DoesNotExist:
        message = _("Dashboard does not exist or you don't have the permission to access it.")
        raise PopupException(message)

    return view_func(request, *args, **kwargs)
  return wraps(view_func)(decorate)

Example 28

Project: hue
Source File: decorators.py
View license
def get_connector_or_exception(exception_class=PopupException):
  def inner(view_func):
    def decorate(request, connector_id, *args, **kwargs):
      try:
        c = client.SqoopClient(conf.SERVER_URL.get(), request.user.username, request.LANGUAGE_CODE)
        connector = c.get_connector(int(connector_id))
      except RestException, e:
        handle_rest_exception(e, _('Could not get connector.'))
      return view_func(request, connector=connector, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

Example 29

Project: hue
Source File: decorators.py
View license
def get_link_or_exception(exception_class=PopupException):
  def inner(view_func):
    def decorate(request, link_id, *args, **kwargs):
      try:
        c = client.SqoopClient(conf.SERVER_URL.get(), request.user.username, request.LANGUAGE_CODE)
        link = c.get_link(int(link_id))
      except RestException, e:
        handle_rest_exception(e, _('Could not get link.'))
      return view_func(request, link=link, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

Example 30

Project: hue
Source File: decorators.py
View license
def get_job_or_exception(exception_class=PopupException):
  def inner(view_func):
    def decorate(request, job_id, *args, **kwargs):
      try:
        c = client.SqoopClient(conf.SERVER_URL.get(), request.user.username, request.LANGUAGE_CODE)
        job = c.get_job(int(job_id))
      except RestException, e:
        handle_rest_exception(e, _('Could not get job.'))
      return view_func(request, job=job, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

Example 31

Project: hue
Source File: decorators.py
View license
def get_submission_or_exception(exception_class=PopupException):
  def inner(view_func):
    def decorate(request, submission_id, *args, **kwargs):
      try:
        c = client.SqoopClient(conf.SERVER_URL.get(), request.user.username, request.LANGUAGE_CODE)
        submission = c.get_submission(int(submission_id))
      except RestException, e:
        handle_rest_exception(e, _('Could not get submission.'))
      return view_func(request, submission=submission, *args, **kwargs)
    return wraps(view_func)(decorate)
  return inner

Example 32

View license
def positive_filter_decorator(func):
    def inner(qs, user):
        if isinstance(qs, basestring):
            model = get_model(*qs.split('.'))
            if not model:
                return []
            qs = model._default_manager.all()
        if user.is_anonymous():
            return qs.none()
        return func(qs, user)
    inner._decorated_function = getattr(func, '_decorated_function', func)
    return wraps(func)(inner)

Example 33

View license
def negative_filter_decorator(func):
    def inner(qs, user):
        if isinstance(qs, basestring):
            model = get_model(*qs.split('.'))
            if not model:
                return []
            qs = model._default_manager.all()
        if user.is_anonymous():
            return qs
        return func(qs, user)
    inner._decorated_function = getattr(func, '_decorated_function', func)
    return wraps(func)(inner)

Example 34

Project: django-compositepks
Source File: transaction.py
View license
def autocommit(func):
    """
    Decorator that activates commit on save. This is Django's default behavior;
    this decorator is useful if you globally activated transaction management in
    your settings file and want the default behavior in some view functions.
    """
    def _autocommit(*args, **kw):
        try:
            enter_transaction_management()
            managed(False)
            return func(*args, **kw)
        finally:
            leave_transaction_management()
    return wraps(func)(_autocommit)

Example 35

Project: django-compositepks
Source File: transaction.py
View license
def commit_manually(func):
    """
    Decorator that activates manual transaction control. It just disables
    automatic transaction control and doesn't do any commit/rollback of its
    own -- it's up to the user to call the commit and rollback functions
    themselves.
    """
    def _commit_manually(*args, **kw):
        try:
            enter_transaction_management()
            managed(True)
            return func(*args, **kw)
        finally:
            leave_transaction_management()

    return wraps(func)(_commit_manually)

Example 36

Project: django-compositepks
Source File: cache.py
View license
def cache_control(**kwargs):

    def _cache_controller(viewfunc):

        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return _cache_controller

Example 37

Project: django-compositepks
Source File: cache.py
View license
def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return wraps(view_func)(_wrapped_view_func)

Example 38

Project: django-compositepks
Source File: http.py
View license
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):
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return wraps(func)(inner)
    return decorator

Example 39

Project: django-compositepks
Source File: vary.py
View license
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):
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return wraps(func)(inner_func)
    return decorator

Example 40

Project: django-compositepks
Source File: vary.py
View license
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):
            ...
    """
    def inner_func(*args, **kwargs):
        response = func(*args, **kwargs)
        patch_vary_headers(response, ('Cookie',))
        return response
    return wraps(func)(inner_func)

Example 41

Project: aemanager
Source File: decorators.py
View license
def subscription_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    decorator which redirects to subscribe page if needed
    use login_required.
    """
    def decorator(request, *args, **kwargs):
        if request.user.get_profile().is_allowed():
            return view_func(request, *args, **kwargs)
        messages.warning(request, _('Your subscription has expired. You need to subscribe again to keep using %(site_name)s') % {'site_name': Site.objects.get_current().name})
        return HttpResponseRedirect(reverse('subscribe'))
    return login_required(wraps(view_func, assigned=available_attrs(view_func))(decorator), redirect_field_name=redirect_field_name)

Example 42

Project: aemanager
Source File: decorators.py
View license
def settings_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    decorator which redirects to settings page if mandatory
    values are not set, use login_required.
    """
    def decorator(request, *args, **kwargs):
        if request.user.get_profile().settings_defined():
            return view_func(request, *args, **kwargs)
        messages.info(request, _('You need to fill these informations to continue'))
        return HttpResponseRedirect(reverse('settings_edit'))
    return login_required(wraps(view_func, assigned=available_attrs(view_func))(decorator), redirect_field_name=redirect_field_name)

Example 43

Project: aemanager
Source File: decorators.py
View license
def disabled_for_demo(view_func):
    """
    decorator which redirects to settings page if mandatory
    values are not set, use login_required.
    """
    def decorator(request, *args, **kwargs):
        if not settings.DEMO:
            return view_func(request, *args, **kwargs)
        return HttpResponseForbidden(ugettext("You can't use this feature in demo"))

    return wraps(view_func, assigned=available_attrs(view_func))(decorator)

Example 44

Project: lettuce
Source File: decorators.py
View license
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.
    """
    if not login_url:
        from django.conf import settings
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = urlquote(request.get_full_path())
            tup = login_url, redirect_field_name, path
            return HttpResponseRedirect('%s?%s=%s' % tup)
        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
    return decorator

Example 45

Project: lettuce
Source File: decorators.py
View license
def method_decorator(decorator):
    """
    Converts a function decorator into a method decorator
    """
    def _dec(func):
        def _wrapper(self, *args, **kwargs):
            def bound_func(*args2, **kwargs2):
                return func(self, *args2, **kwargs2)
            # bound_func has the signature that 'decorator' expects i.e.  no
            # 'self' argument, but it is a closure over self so it can call
            # 'func' correctly.
            return decorator(bound_func)(*args, **kwargs)
        return wraps(func)(_wrapper)
    update_wrapper(_dec, decorator)
    # Change the name to aid debugging.
    _dec.__name__ = 'method_decorator(%s)' % decorator.__name__
    return _dec

Example 46

Project: lettuce
Source File: cache.py
View license
def cache_control(**kwargs):
    def _cache_controller(viewfunc):
        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response
        return wraps(viewfunc, assigned=available_attrs(viewfunc))(_cache_controlled)
    return _cache_controller

Example 47

Project: lettuce
Source File: cache.py
View license
def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view_func)

Example 48

Project: lettuce
Source File: csrf.py
View license
def csrf_response_exempt(view_func):
    """
    Modifies a view function so that its response is exempt
    from the post-processing of the CSRF middleware.
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.csrf_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)

Example 49

Project: lettuce
Source File: csrf.py
View license
def csrf_view_exempt(view_func):
    """
    Marks a view function as being exempt from 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)

Example 50

Project: lettuce
Source File: http.py
View license
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):
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return wraps(func, assigned=available_attrs(func))(inner)
    return decorator