當前位置: 首頁>>代碼示例>>Python>>正文


Python decorators.method_decorator方法代碼示例

本文整理匯總了Python中django.utils.decorators.method_decorator方法的典型用法代碼示例。如果您正苦於以下問題:Python decorators.method_decorator方法的具體用法?Python decorators.method_decorator怎麽用?Python decorators.method_decorator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.decorators的用法示例。


在下文中一共展示了decorators.method_decorator方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check_ip

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def check_ip(func):
    # 實現禁止ip黑名單訪問發帖界麵。 解決: 可以通過在視圖函數中使用裝飾器實現
    def wrapper(request, *args, **kwargs):
        # 在視圖函數執行前做額外的操作:
        # 禁止ip黑名單訪問
        IP = request.META.get('REMOTE_ADDR')
        if IP not in ['192.168.210.160']:
            return HttpResponse('IP禁止訪問')

        # 一切正常,返回該返回的
        return func(request, *args, **kwargs)

    return wrapper


# 方式4, 直接把裝飾器定義成適合類視圖函數的裝飾器,添加一個self參數,這樣就能直接在類視圖函數中不需要method_decorator了 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:18,代碼來源:views.py

示例2: fix_initial_order

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def fix_initial_order(self, initial_order):
        """
        "initial_order" is a list of (position, direction) tuples; for example:
            [[1, 'asc'], [5, 'desc']]

        Here, we also accept positions expressed as column names,
        and convert the to the corresponding numeric position.
        """
        values = []
        keys = list(self.column_index.keys())
        for position, direction in initial_order:
            if type(position) == str:
                position = keys.index(position)
            values.append([position, direction])
        return values

    #@method_decorator(csrf_exempt) 
開發者ID:morlandi,項目名稱:django-datatables-view,代碼行數:19,代碼來源:views.py

示例3: __init__

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def __init__(self, *args, **kwargs):
        super(FailedLoginMiddleware, self).__init__(*args, **kwargs)
        # Watch the auth login.
        # Monkey-patch only once - otherwise we would be recording
        # failed attempts multiple times!
        if not FailedLoginMiddleware.patched:
            # Django 1.11 turned the `login` function view into the
            # `LoginView` class-based view
            try:
                from django.contrib.auth.views import LoginView

                our_decorator = watch_login()
                watch_login_method = method_decorator(our_decorator)
                LoginView.dispatch = watch_login_method(LoginView.dispatch)
            except ImportError:  # Django < 1.11
                auth_views.login = watch_login()(auth_views.login)

            FailedLoginMiddleware.patched = True 
開發者ID:jazzband,項目名稱:django-defender,代碼行數:20,代碼來源:middleware.py

示例4: test_require_safe_accepts_only_safe_methods

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def test_require_safe_accepts_only_safe_methods(self):
        """
        Test for the require_safe decorator.
        A view returns either a response or an exception.
        Refs #15637.
        """
        def my_view(request):
            return HttpResponse("OK")
        my_safe_view = require_safe(my_view)
        request = HttpRequest()
        request.method = 'GET'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'HEAD'
        self.assertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'POST'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'PUT'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'DELETE'
        self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)


# For testing method_decorator, a decorator that assumes a single argument.
# We will get type arguments if there is a mismatch in the number of arguments. 
開發者ID:nesdis,項目名稱:djongo,代碼行數:26,代碼來源:tests.py

示例5: test_invalid_non_callable_attribute_decoration

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def test_invalid_non_callable_attribute_decoration(self):
        """
        @method_decorator on a non-callable attribute raises an error.
        """
        msg = (
            "Cannot decorate 'prop' as it isn't a callable attribute of "
            "<class 'Test'> (1)"
        )
        with self.assertRaisesMessage(TypeError, msg):
            @method_decorator(lambda: None, name="prop")
            class Test:
                prop = 1

                @classmethod
                def __module__(cls):
                    return "tests" 
開發者ID:nesdis,項目名稱:djongo,代碼行數:18,代碼來源:tests.py

示例6: notify_mobile_survey_end

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def notify_mobile_survey_end(self, request, mobile_survey):
        admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
        email_context = {
            "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
            "link": request.build_absolute_uri(reverse("home")),
            "greeting": _(
                "Hi!  The Mobile Survey you were part of has ended or is temporarily suspended. \
                Please permform a final sync of your local dataset as soon as possible."
            ),
            "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
        }

        html_content = render_to_string("email/general_notification.htm", email_context)
        text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

        # create the email, and attach the HTML version as well.
        for user in self.get_mobile_survey_users(mobile_survey):
            msg = EmailMultiAlternatives(
                _("There's been a change to an {app_name} Survey that you're part of!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send()


# @method_decorator(can_read_resource_instance(), name='dispatch') 
開發者ID:archesproject,項目名稱:arches,代碼行數:30,代碼來源:mobile_survey.py

示例7: get_queryset

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def get_queryset(self, **kwargs):
        name = self.request.GET.get('name', '')    
        return Disease.objects.filter(Q(name__icontains=name)|Q(gene_names__icontains=name))

    # @method_decorator(login_required)
    # def dispatch(self, *args, **kwargs):
    #     return super(DiseaseListView, self).dispatch(*args, **kwargs) 
開發者ID:raonyguimaraes,項目名稱:mendelmd,代碼行數:9,代碼來源:views.py

示例8: as_view

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        # 在這裏添加自己的裝飾器
        view = check_ip(view)
        return view


# 方式3, name=dispatch的話就是給所有的函數添加裝飾器
# @method_decorator(check_ip, name='get')
# @method_decorator(check_ip, name='dispatch') 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:12,代碼來源:views.py

示例9: class_view_decorator

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def class_view_decorator(function_decorator):
    """
    Convert a function based decorator into a class based decorator usable
    on class based Views.

    Can't subclass the `View` as it breaks inheritance (super in particular),
    so we monkey-patch instead.
    """
    def simple_decorator(View):
        View.dispatch = method_decorator(function_decorator)(View.dispatch)
        return View
    return simple_decorator 
開發者ID:KlubJagiellonski,項目名稱:Politikon,代碼行數:14,代碼來源:decorators.py

示例10: method_login_and_permission

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def method_login_and_permission(permission_name):
    return method_decorator(login_and_permission(permission_name), name='dispatch')

# photos 
開發者ID:compserv,項目名稱:hknweb,代碼行數:6,代碼來源:utils.py

示例11: get_mixin

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def get_mixin(decorator: Callable) -> Type[object]:
    """
    Helper function that allows dynamic application of decorators to a class-based views

    :param func decorator: the decorator to apply to the view
    """

    class Mixin(object):
        @method_decorator(decorator)
        def dispatch(self, request, *args, **kwargs):
            return super(Mixin, self).dispatch(request, *args, **kwargs)

    return Mixin 
開發者ID:chris104957,項目名稱:django-carrot,代碼行數:15,代碼來源:utilities.py

示例12: class_view_decorator

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def class_view_decorator(function_decorator):
    """Convert a function based decorator into a class based decorator usable
    on class based Views.

    Can't subclass the `View` as it breaks inheritance (super in particular),
    so we monkey-patch instead.
    """

    def simple_decorator(View):
        View.dispatch = method_decorator(function_decorator)(View.dispatch)
        return View

    return simple_decorator 
開發者ID:DMOJ,項目名稱:online-judge,代碼行數:15,代碼來源:views.py

示例13: class_login_required

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def class_login_required(cls):
    """Class decorator for View subclasses to restrict to logged in."""
    decorator = method_decorator(login_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
開發者ID:salopensource,項目名稱:sal,代碼行數:7,代碼來源:decorators.py

示例14: class_ga_required

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def class_ga_required(cls):
    """Class decorator for View subclasses to restrict to GA."""
    decorator = method_decorator(ga_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
開發者ID:salopensource,項目名稱:sal,代碼行數:7,代碼來源:decorators.py

示例15: class_staff_required

# 需要導入模塊: from django.utils import decorators [as 別名]
# 或者: from django.utils.decorators import method_decorator [as 別名]
def class_staff_required(cls):
    """Class decorator for View subclasses to restrict to staff."""
    decorator = method_decorator(staff_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
開發者ID:salopensource,項目名稱:sal,代碼行數:7,代碼來源:decorators.py


注:本文中的django.utils.decorators.method_decorator方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。