EN VI

Python - how do I concatenate the name:value pairs of request headers with the tab (\t) separator

2022-05-30 17:20:57

Python - how do I concatenate the name:value pairs of request headers with the tab (\t) separator such that name field is all in lower case?

Below are the points to be considered.

  1. Get the first header value for the name.

  2. Trim the leading and trailing white spaces.

  3. Replace all repeated white spaces with a single space.

  4. Concatenate the name, value pairs with the tab (\t)separator(name field is all in lower case).

  5. Terminate the headers with another tab (\t) separator.

    import re

    headers ={ "Accept" : "application/vnd.accept_header-status.v11+json", "Content-Type" : "application/vnd.content-type_header.v11+json" }

    canonicalize_headers='\t'.join(h for h in headers)

    print(canonicalize_headers)

Sample input:

Host: akaa-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx.aa-dev.net.net
 x-a: va
 x-c: "      xc        "
 x-b:    w         b

Sample Output:

POST\thttp\takaa-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx.aa-dev.net\t
 /sample-api/v1/property/?fields=x&format=json&cpcode=1234\tx-a:va\tx-b:w b\tx-c:" xc "\t\t\t

need to create a post request with signing headers

Solution:

From what I have understood, what you are looking for is:

def clean(headers):
    for k, v in headers.items:
        k = re.sub(r"\s+", " ", k.strip())
        yield f"{k.lower()}\t{v}"

canonicalize_headers = "\t".join(clean(headers))
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login