management: Extract parse_headers in send_webhook_fixture_message.

This way other devtools such as the integrations development panel
could also use the method.
This commit is contained in:
Hemanth V. Alluri 2019-05-16 11:54:23 +05:30 committed by Tim Abbott
parent 5b4979806c
commit 64b4fd5923
1 changed files with 15 additions and 9 deletions

View File

@ -9,6 +9,20 @@ from django.test import Client
from zerver.lib.management import ZulipBaseCommand, CommandError from zerver.lib.management import ZulipBaseCommand, CommandError
from zerver.models import get_realm from zerver.models import get_realm
def parse_headers(custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]:
""" The main aim of this method is be to convert regular HTTP headers into a format that
Django prefers. Note: This function throws a ValueError and thus it should be used in a
try/except block. """
headers = {}
if not custom_headers:
return None
custom_headers_dict = ujson.loads(custom_headers)
for header in custom_headers_dict:
if len(header.split(" ")) > 1:
raise ValueError("custom header '%s' contains a space." % (header,))
headers["HTTP_" + header.upper().replace("-", "_")] = str(custom_headers_dict[header])
return headers
class Command(ZulipBaseCommand): class Command(ZulipBaseCommand):
help = """ help = """
Create webhook message based on given fixture Create webhook message based on given fixture
@ -50,16 +64,8 @@ approach shown above.
self.add_realm_args(parser, help="Specify which realm/subdomain to connect to; default is zulip") self.add_realm_args(parser, help="Specify which realm/subdomain to connect to; default is zulip")
def parse_headers(self, custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]: def parse_headers(self, custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]:
headers = {}
if not custom_headers:
return None
try: try:
custom_headers_dict = ujson.loads(custom_headers) return parse_headers(custom_headers)
for header in custom_headers_dict:
if len(header.split(" ")) > 1:
raise ValueError("custom header '%s' contains a space." % (header,))
headers["HTTP_" + header.upper().replace("-", "_")] = str(custom_headers_dict[header])
return headers
except ValueError as ve: except ValueError as ve:
raise CommandError('Encountered an error while attempting to parse custom headers: {}\n' raise CommandError('Encountered an error while attempting to parse custom headers: {}\n'
'Note: all strings must be enclosed within "" instead of \'\''.format(ve)) 'Note: all strings must be enclosed within "" instead of \'\''.format(ve))