url.py 1.21 KB
Newer Older
1
2
3
4
5
from django.core.validators import URLValidator
from rest_framework.validators import ValidationError


def validate_extension(allowed_extensions, string):
6
7
8
    allowed_extensions = [
        allowed_extension.lower() for allowed_extension in allowed_extensions
    ]
9
    try:
10
        if string.split(".")[-1].lower() not in allowed_extensions:
11
            raise ValidationError(
12
13
                "The file you submitted has an unauthorized extension"
            )
14
15
16
17
18
19
    except KeyError:
        raise ValidationError("File extension not recognized")


def validate_url(config, string):
    string = str(string)
20
    validate = URLValidator(schemes=("http", "https", "ftp", "ftps"))
21
22
    validate(string)
    try:
23
        validators = config["validators"]
24
25
        for validator in validators:
            validator_content = validators[validator]
26
            if validator == "extension":
27
                validate_extension(validator_content, string)
28
            elif validator == "max_length":
Florent Chehab's avatar
Florent Chehab committed
29
                if len(string) > validator_content:
30
                    raise ValidationError("Your url is too long !")
31
32
33
34
35
            else:
                raise Exception("Dev, you have implement something here...")

    except KeyError:
        pass