Django项目常用验证及写法

友情提醒:本文最后更新于 2677 天前,文中所描述的信息可能已发生改变,请谨慎使用。

Django项目中常用的验证写法

命名python文件,如:validate.py,加入类似如下内容(具体自己用到的验证自己写):

# coding:utf-8

import re
import json
from urlparse import urlparse
 
class IpValidate(object):
    def ip_validate(self, ip):
        parts = ip.split(".")
        if len(parts) < 4:
            return False, "IP is invalidate"
        if len(parts) == 4:
            for part in parts:
                if str(part).isdigit():
                    if int(part) < 0 or int(part) > 255:
                        return False, "IP is invalidate"
                else:
                    return False, "IP is invalidate1"
            return True, ""
 
class EmailValidate(object):
    def __init__(self, email):
        self.email = email
 
    def email_validate(self):
        email = self.email
        reg = re.compile("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$")
        success = reg.match(email)
        if not success:
            return False, 'Email不合法'
        return True, ''
 
class ChannelUpdateValidate(IpValidate, EmailValidate):
    VALIDATORS = [
        "validate_ip",
        "validate_port",
        "validate_origin_url",
    ]
 
    def run_validators(self, validators):
        for validator in validators:
            if hasattr(self, validator):
                func = getattr(self, validator)
                if not func():
                    return False
        return True
 
    def validate_params(self):
        return self.run_validators(self.VALIDATORS)
 
    def __init__(self, ip, port, origin_url):
        self.ip = ip
        self.port = port
        self.origin_url = origin_url
        self.message = ""
 
    def validate_ip(self):
        ips = self.ip.split(",")
        for ip in ips:
            ip_success, message = self.ip_validate(ip)
            domain_success, message = self.domain_validate(ip)
            if not ip_success and not domain_success:
                self.message = "源站不合法"
                return False
            return True, ""
 
    def validate_port(self):
        if str(self.port).isdigit():
            return True, ""
        self.message = "端口号不合法"
        return False
 
    def validate_origin_url(self):
        reg = re.compile("^(?:http|ftp)?://")
        success = reg.match(self.origin_url)
        if not success:
            self.message = 'URL格式错误'
            return False
        return True, ''
 
class ChannelValidate(ChannelUpdateValidate):
    VALIDATORS = [
        "validate_domain",
        "validate_ip",
        "validate_port",
        "validate_origin_url",
    ]
 
 
    def __init__(self, ip, port, origin_url, domain):
        self.ip = ip
        self.domain = domain
        self.port = port
        self.origin_url = origin_url
        self.message = ""
 
 
    def validate_domain(self):
        success, message = self.domain_validate(self.domain)
        if not success:
            self.message = "域名不合法"
            return False
        return True, ""
 
class UserValidate(EmailValidate):
    VALIDATORS = [
        "validate_email",
        "validate_phone",
        ]
 
    def run_validators(self, validators):
        for validator in validators:
            if hasattr(self, validator):
                func = getattr(self, validator)
                if not func():
                    return False
        return True
 
    def validate_params(self):
        return self.run_validators(self.VALIDATORS)
 
    def __init__(self, email, phone):
        self.email = email
        self.phone = phone
        self.message = ""
 
    def validate_email(self):
        success, message = self.email_validate()
        if not success:
            self.message = message
            return False
        return True
 
    def validate_phone(self):
        phone = self.phone
        if not str(phone).isdigit():
            self.message = "电话号码不合法"
            return False
        reg = re.compile("^[0-9]{7,12}$")
        success = reg.match(phone)
        if not success:
            self.message = "电话号码不合法"
            return False
        return True

用法: 在需要验证的python文件中导入validate.py,然后类似如下代码:

def create_user(request):
    params = request.POST
    user = User.objects.filter(email=params['email'])
    validate_user = UserValidate(params["email"], params["mobile_phone"])
    success = validate_user.validate_params()
    if not success:
        return render_json({'success': False, 'message': validate_user.message})
    if user.count() > 0:
        return render_json({'success': False, 'message': u'用户已存在!'})
    User.add(params['email'], params['password'], params['contact'], params['mobile_phone'], params['role'],
                params['comments'])
    return render_json({'success': True, 'message': u'添加成功!'})

上一篇:Python字符串的常用方法说明

下一篇:Python + Django项目常用装饰器及自定义函数