axnsan12 / drf-yasg

Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
https://drf-yasg.readthedocs.io/en/stable/
Other
3.42k stars 439 forks source link

Incorrect regex output when generate swagger.json file #380

Closed haminhcong closed 5 years ago

haminhcong commented 5 years ago

When use drf-yasg with Django and django-rest-framework to generate swagger api document for my web service, i got following problem:

In my Django model, an user field use regex validator:

class UnicodeUsernameValidator(validators.RegexValidator):
    regex = r'^[\w.@+-]+$'
    message = _(
        'Enter a valid username. This value may contain only letters, '
        'numbers, and @/./+/-/_ characters.'
    )
    flags = 0

class User(models.Model):

    username_validator = UnicodeUsernameValidator()
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )

then when I generate json swagger document from localhost:8000/api/swagger.json, then in generated swagger json file, this regex r'^[\w.@+-]+$ is converted to an incorrect regex which contains two backslash:

"username": {
    "title": "Username",
    "description": "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
    "type": "string",
    "pattern": "^[\\w.@+-]+$",
    "maxLength": 150,
    "minLength": 1
}

Then when I use swagger codegen to generate client from this json document, the incorrect regex is used in client too, so my client is broken.

Can you help me check this behavior and fix it if it is a bug ?

Thank you.

haminhcong commented 5 years ago

Sorry. This is swagger codegen bug, not your bug.

https://github.com/swagger-api/swagger-codegen/issues/3703#issuecomment-357743875