Parse raw HTTP Headers

前端 未结 7 961

I have a string of raw HTTP and I would like to represent the fields in an object. Is there any way to parse the individual headers from an HTTP string?

\'GE         


        
相关标签:
7条回答
  • 2020-11-27 05:10

    They is another way, simpler and safer way to handle headers. More object oriented. With no need for manual parsing.

    Short demo.

    1. Parse them

    From str, bytes, fp, dict, requests.Response, email.Message, httpx.Response, urllib3.HTTPResponse.

    from requests import get
    from kiss_headers import parse_it
    
    response = get('https://www.google.fr')
    headers = parse_it(response)
    
    headers.content_type.charset  # output: ISO-8859-1
    # Its the same as
    headers["content-type"]["charset"]  # output: ISO-8859-1
    

    2. Build them

    This

    from kiss_headers import *
    
    headers = (
        Host("developer.mozilla.org")
        + UserAgent(
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0"
        )
        + Accept("text/html")
        + Accept("application/xhtml+xml")
        + Accept("application/xml", qualifier=0.9)
        + Accept(qualifier=0.8)
        + AcceptLanguage("en-US")
        + AcceptLanguage("en", qualifier=0.5)
        + AcceptEncoding("gzip")
        + AcceptEncoding("deflate")
        + AcceptEncoding("br")
        + Referer("https://developer.mozilla.org/testpage.html")
        + Connection(should_keep_alive=True)
        + UpgradeInsecureRequests()
        + IfModifiedSince("Mon, 18 Jul 2016 02:36:04 GMT")
        + IfNoneMatch("c561c68d0ba92bbeb8b0fff2a9199f722e3a621a")
        + CacheControl(max_age=0)
    )
    
    raw_headers = str(headers)
    

    Will become

    Host: developer.mozilla.org
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
    Accept: text/html, application/xhtml+xml, application/xml; q="0.9", */*; q="0.8"
    Accept-Language: en-US, en; q="0.5"
    Accept-Encoding: gzip, deflate, br
    Referer: https://developer.mozilla.org/testpage.html
    Connection: keep-alive
    Upgrade-Insecure-Requests: 1
    If-Modified-Since: Mon, 18 Jul 2016 02:36:04 GMT
    If-None-Match: "c561c68d0ba92bbeb8b0fff2a9199f722e3a621a"
    Cache-Control: max-age="0"
    

    Documentation for the kiss-headers library.

    0 讨论(0)
提交回复
热议问题