如何使用Python的Voluptuous验证URL和电子邮件?

2024-10-01 17:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python验证url和email输入数据,可能是这样的:

schema = Schema({
    Required('url'): All(str, Url()),
    Required('email'): All(str, Email())
})

看一下源代码,我发现volutous有一个内置的Url函数,在电子邮件的情况下它没有,所以我想建立自己的,问题是我不知道必须在模式内部调用这个函数。在


Tags: 数据函数url源代码电子邮件emailschemarequired
1条回答
网友
1楼 · 发布于 2024-10-01 17:31:54

更新:现在voluptuous已经有了电子邮件验证器。在

您可以这样编写自己的验证器

import re
from voluptuous import All, Invalid, Required, Schema

def Email(msg=None):
    def f(v):
        if re.match("[\w\.\-]*@[\w\.\-]*\.\w+", str(v)):
            return str(v)
        else:
            raise Invalid(msg or ("incorrect email address"))
    return f

schema = Schema({
        Required('email') : All(Email())
    })

schema({'email' : "invalid_email.com"}) # <  this will result in a MultipleInvalid Exception
schema({'email' : "valid@email.com"}) # <  this should validate the email address

相关问题 更多 >

    热门问题