From 806aa0f41c7816b2859a6961939ed19499b73fe7 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Sat, 2 Apr 2016 14:38:33 +0200 Subject: improve .replace() and move it into netlib --- netlib/http/message.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'netlib/http/message.py') diff --git a/netlib/http/message.py b/netlib/http/message.py index b265ac4f..da9681a0 100644 --- a/netlib/http/message.py +++ b/netlib/http/message.py @@ -175,6 +175,25 @@ class Message(utils.Serializable): self.headers["content-encoding"] = e return True + def replace(self, pattern, repl, flags=0): + """ + Replaces a regular expression pattern with repl in both the headers + and the body of the message. Encoded body will be decoded + before replacement, and re-encoded afterwards. + + Returns: + The number of replacements made. + """ + # TODO: Proper distinction between text and bytes. + replacements = 0 + if self.content: + with decoded(self): + self.content, replacements = utils.safe_subn( + pattern, repl, self.content, flags=flags + ) + replacements += self.headers.replace(pattern, repl, flags) + return replacements + # Legacy @property -- cgit v1.2.3