There is an HTTP request stored in a string variable. For example:

POST /api/integration/test.json HTTP/1.1 Host: 192.168.0.221:1028 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate X-Compress: off Connection: keep-alive Upgrade-Insecure-Requests: 1 Content-Type: multipart/form-data; boundary=---------------------------16270120918082 Content-Length: 693 -----------------------------16270120918082 Content-Disposition: form-data; name="field1" field1value -----------------------------16270120918082 Content-Disposition: form-data; name="field2" field2value -----------------------------16270120918082 Content-Disposition: form-data; name="file"; filename="1.json" Content-Type: application/octet-stream { "ipAddress":"192.168.0.221", "port":1028, } -----------------------------16270120918082-- 

Question: how in Python to parse this string into some object that provides a convenient interface for accessing the request data (especially the body)?

I used HttpParser when there were enough GET requests. The module is good for heading parsing, but it does almost nothing with the body.

  • The English version contains similar questions. Here are examples, stackoverflow.com/questions/4685217/parse-raw-http-headers and stackoverflow.com/questions/3214073/parse-raw-http-in-python - sys_dev
  • I would use the features of the native modules urllib and cgi - andreymal
  • one
    just in case I will mention: if this question somehow relates to your previous questions about the exchange of data between C ++ and Python applications: instead of sending strings containing an HTTP request, using named pipes (named pipe / fifo), you can connect to the specified address by socket API, using any C ++ http-client, and on the side of Python use a ready-made http-server and any web-framework that you like. Here is a complete example using flask and mod_wsgi . If this is a brute force, call cgi.FieldStorage() with hands to recognize the multipart. - jfs
  • @jfs is a task just for self-development. Yes, all the last questions are somehow related to each other) Thanks for the info! At the moment I want to make an independent transceiver and script handler that I would tune to the desired protocol. - AccumPlus
  • @jfs is it possible to have some kind of parsing? Honestly, I could not find the right one. Here I have a line, as in the question. What to do next with her? - AccumPlus

0