【问题标题】:Process HTTP headers from uasyncio.start_server()处理来自 uasyncio.start_server() 的 HTTP 标头
【发布时间】:2022-10-15 03:53:33
【问题描述】:

我正在尝试使用 uasyncio 的 start_server 类制作一个处理 HTTP 标头的程序,在打印从 Web 请求收到的数据后,我可以看到我试图在 Access-Control-Request-Headers 中读取的名称标头,但无法读取存储在标头中的实际数据.

相关代码:

async def conn(reader, writer):
    try:
        while True:
            res = await reader.read(4096)
            if(str(res) != "b''"):
                print(res)
            writer.write("Recieved!")
            await writer.drain()
    except:
        print("Err")
    print("Client disconnected")
    reader.wait_closed()


async def main():
    anim = uasyncio.create_task(animation())
    serv = await uasyncio.start_server(conn, '0.0.0.0', 80, 10)
    while True:
        await uasyncio.sleep_ms(1000)

有人能指出我正确的方向或链接一些示例代码来阅读标题吗?

【问题讨论】:

    标签: http-headers micropython


    【解决方案1】:

    标头遵循请求行,这对我有用:

        # print("Client connected")
        
        request_line = await reader.readline()
        # print("Request:", request_line)
    # We are not interested in HTTP request headers, skip them
        header = b""
        while header != b"
    ":
          header = await reader.readline()
          # print('Header:', str(header) )
    

    【讨论】:

      【解决方案2】:

      您需要彻底阅读 HTTP 协议。使用 readline() 读取标题,因为它们由 .如果遇到 即空白行,您遇到了标题的结尾。

      因此,从标题列表中,您可以查找您所追求的标题。

      关于你的字节到 ascii 这样做

      items = await reader.readline()
      
      items = items.decode('ascii').strip()
      

      【讨论】:

        【解决方案3】:

        下面的函数将处理整个 HTTP 请求。您应该能够从res = await reader.read(4096) 给它您的缓冲区并从返回值中提取标题。

        例如:

        req_buffer = await reader.read(4096)
        req = parse_http_request(req_buffer)
        print(req['headers'])
        

        这是函数定义...

        # Given a raw HTTP request, return a dictionary with individual elements broken out.
        # Takes a buffer containing the HTTP request sent from the client.
        # Returns a dictionary containing method, path, query, headers, body, etc. or None if parsing fails.
        def parse_http_request(req_buffer):
            req = {}
            req_buffer_lines = req_buffer.decode('utf8').split('
        ')
            req['method'], target, req['http_version'] = req_buffer_lines[0].split(' ', 2)  # Example: GET /route/path HTTP/1.1
            if (not '?' in target):
                req['path'] = target
            else:  # target can have a query component, so /route/path could be something like /route/path?state=on&timeout=30
                req['path'], query_string = target.split('?', 1)
                req['query'] = Thimble.parse_query_string(query_string)
        
            req['headers'] = {}
            for i in range(1, len(req_buffer_lines) - 1):
                if (req_buffer_lines[i] == ''):  # Blank line signifies the end of headers.
                    break
                else:
                    name, value = req_buffer_lines[i].split(':', 1)
                    req['headers'][name.strip()] = value.strip()
        
            req['body'] = req_buffer_lines[len(req_buffer_lines) - 1]  # Last line is the body (or blank if no body.)
                
            return req
        

        【讨论】:

          猜你喜欢
          • 2013-06-02
          • 2019-12-27
          • 2016-02-23
          • 2017-06-17
          • 1970-01-01
          • 1970-01-01
          • 2011-02-02
          • 1970-01-01
          相关资源
          最近更新 更多