Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up ProhibitSurrogateCharactersValidator #9492

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions rest_framework/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
object creation, and makes it possible to switch between using the implicit
`ModelSerializer` class and an equivalent explicit `Serializer` class.
"""
import re

from django.db import DataError
from django.utils.translation import gettext_lazy as _

Expand Down Expand Up @@ -197,13 +199,14 @@ def __eq__(self, other):


class ProhibitSurrogateCharactersValidator:
_regex = re.compile(r'[\ud800-\udfff]')

message = _('Surrogate characters are not allowed: U+{code_point:X}.')
code = 'surrogate_characters_not_allowed'

def __call__(self, value):
for surrogate_character in (ch for ch in str(value)
if 0xD800 <= ord(ch) <= 0xDFFF):
message = self.message.format(code_point=ord(surrogate_character))
if match := self._regex.search(str(value)):
message = self.message.format(code_point=ord(match.group()))
raise ValidationError(message, code=self.code)

def __eq__(self, other):
Expand Down
Loading