python/django 中的电子邮件白名单/黑名单

发布于 2024-07-17 04:28:07 字数 914 浏览 14 评论 0 原文

我正在编写一个 django 应用程序,用于跟踪允许哪些电子邮件地址将内容发布到用户帐户。 用户可以根据需要将地址列入白名单和黑名单。

任何未指定的地址都可以按消息处理,也可以默认为白名单或黑名单(再次由用户指定)。

这是我写的 django 模型......你认为这是一个好方法吗? 或者我应该向每个用户的配置文件模型添加白名单和黑名单字段?

class knownEmail(models.Model):
    # The user who set this address' permission, NOT
    # the user who the address belongs to...
    relatedUser = models.ManyToManyField(User)
    email = models.EmailField()

class whiteList(knownEmail):
    pass

class blackList(knownEmail):
    pass

然后我可以做这样的事情:

def checkPermission(user, emailAddress):
    "Check if 'emailAddress' is allowed to post content to 'user's profile"
    if whiteList.objects.filter(relatedUser=user, email=emailAddress):
        return True
    elif blackList.objects.filter(relatedUser=user, email=emailAddress):
        return False
    else:
        return None

有更好的方法吗?

I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.

Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specified).

Here are the django models I wrote... do you think is a good way to do it? or should I add a whitelist and blacklist field to each user's profile model?

class knownEmail(models.Model):
    # The user who set this address' permission, NOT
    # the user who the address belongs to...
    relatedUser = models.ManyToManyField(User)
    email = models.EmailField()

class whiteList(knownEmail):
    pass

class blackList(knownEmail):
    pass

Then I could do something like:

def checkPermission(user, emailAddress):
    "Check if 'emailAddress' is allowed to post content to 'user's profile"
    if whiteList.objects.filter(relatedUser=user, email=emailAddress):
        return True
    elif blackList.objects.filter(relatedUser=user, email=emailAddress):
        return False
    else:
        return None

Is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆悲凉 2024-07-24 04:28:07

我会对其进行重组,以便两个列表都包含在一个模型中。

class PermissionList(models.Model):
    setter = models.ManyToManyField(User)
    email = models.EmailField(unique=True) #don't want conflicting results
    permission = models.BooleanField()

然后,您的列表将是:

# whitelist
PermissionList.objects.filter(permission=True)
# blacklist
PermissionList.objects.filter(permission=False)

要检查特定用户,您只需向模型添加几个函数:

class PermissionList(...):
    ...
    @classmethod
    def is_on_whitelist(email):
        return PermissionList.objects.filter(email=email, permission=True).count() > 0

    @classmethod
    def is_on_blacklist(email):
        return PermissionList.objects.filter(email=email, permission=False).count() > 0

    @classmethod
    def has_permission(email):
        if PermissionList.is_on_whitelist(email):
            return True
        if PermissionList.is_on_blacklist(email):
            return False
        return None

将所有内容放在一个位置会简单得多,并且您可以用更少的工作进行更有趣的查询。

I would restructure it so both lists were contained in one model.

class PermissionList(models.Model):
    setter = models.ManyToManyField(User)
    email = models.EmailField(unique=True) #don't want conflicting results
    permission = models.BooleanField()

Then, your lists would just be:

# whitelist
PermissionList.objects.filter(permission=True)
# blacklist
PermissionList.objects.filter(permission=False)

To check a particular user, you just add a couple functions to the model:

class PermissionList(...):
    ...
    @classmethod
    def is_on_whitelist(email):
        return PermissionList.objects.filter(email=email, permission=True).count() > 0

    @classmethod
    def is_on_blacklist(email):
        return PermissionList.objects.filter(email=email, permission=False).count() > 0

    @classmethod
    def has_permission(email):
        if PermissionList.is_on_whitelist(email):
            return True
        if PermissionList.is_on_blacklist(email):
            return False
        return None

Having everything in one place is a lot simpler, and you can make more interesting queries with less work.

﹉夏雨初晴づ 2024-07-24 04:28:07

[请以大写字母开头所有类名。]

您的代码没有很好地利用您的类区别。

具体来说,您的课程没有任何不同的行为。 由于这两个类都具有相同的方法,因此不清楚为什么它们首先是两个不同的类。 如果他们有不同的方法,那么你的解决方案就是好的。

但是,如果他们没有不同的方法,您可能需要考虑提供自定义的 KnownEmail 两个子集的 ="nofollow noreferrer">manager

class WhiteList( models.Manager ):
    def get_query_set( self ):
        return super( WhiteList, self ).get_query_set().filter( status='W' )

class BlackList( models.Manager )
    def get_query_set( self ):
        return super( BlackList, self ).get_query_set().filter( status='B' )

class KnownEmail( models.Model ):
    relatedUser = models.ForeignKey(User)
    email = models.EmailField()
    status = models.CharField( max_length=1, choices=LIST_CHOICES )
    objects = models.Manager() # default manager shows all lists
    whiteList= WhiteList() # KnownEmail.whiteList.all() is whitelist subset
    blackList= BlackList() # KnownEmail.blackList.all() is blackList subset

[Please start All Class Names With Upper Case Letters.]

Your code doesn't make use of your class distinction very well.

Specifically, your classes don't have any different behavior. Since both classes have all the same methods, it isn't clear why these are two different classes in the first place. If they have different methods, then your solution is good.

If, however, they don't have different methods, you might want to look at providing a customized manager for each of the two subsets of KnownEmail

class WhiteList( models.Manager ):
    def get_query_set( self ):
        return super( WhiteList, self ).get_query_set().filter( status='W' )

class BlackList( models.Manager )
    def get_query_set( self ):
        return super( BlackList, self ).get_query_set().filter( status='B' )

class KnownEmail( models.Model ):
    relatedUser = models.ForeignKey(User)
    email = models.EmailField()
    status = models.CharField( max_length=1, choices=LIST_CHOICES )
    objects = models.Manager() # default manager shows all lists
    whiteList= WhiteList() # KnownEmail.whiteList.all() is whitelist subset
    blackList= BlackList() # KnownEmail.blackList.all() is blackList subset
悟红尘 2024-07-24 04:28:07

此类将电子邮件地址与电子邮件域黑名单进行比较。 如果您愿意,可以使用 pip 安装 django-email-blacklist

from django.conf import settings
import re

class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""

    def __init__(self):
        self.emails = [line.strip() for line in   open(settings.DISPOSABLE_EMAIL_DOMAINS)]

    def chunk(self, l, n):
        return (l[i:i + n] for i in range(0, len(l), n))

    def is_disposable(self, email):
        for email_group in self.chunk(self.emails, 20):
            regex = "(.*" + ")|(.*".join(email_group) + ")"
                if re.match(regex, email):
                    return True
                return False

This class compares an email address with a blacklist of email domains. If you preffer you can download this module using pip install django-email-blacklist.

from django.conf import settings
import re

class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""

    def __init__(self):
        self.emails = [line.strip() for line in   open(settings.DISPOSABLE_EMAIL_DOMAINS)]

    def chunk(self, l, n):
        return (l[i:i + n] for i in range(0, len(l), n))

    def is_disposable(self, email):
        for email_group in self.chunk(self.emails, 20):
            regex = "(.*" + ")|(.*".join(email_group) + ")"
                if re.match(regex, email):
                    return True
                return False
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文