解析URL查询字符串的最佳方法

问题描述:

在python中解析URL查询字符串(例如,表单附加到URL的数据)中的数据的最佳方法是什么?我的目标是接受表单数据并将其显示在同一页面上。我研究了几种不太适合我的方法。

What is the best way to parse data out of a URL query string (for instance, data appended to the URL by a form) in python? My goal is to accept form data and display it on the same page. I've researched several methods that aren't quite what I'm looking for.

我正在创建一个简单的Web服务器,目的是学习套接字。此Web服务器不会用于测试目的。

I'm creating a simple web server with the goal of learning about sockets. This web server won't be used for anything but testing purposes.

GET /?1pm=sample&2pm=&3pm=&4pm=&5pm= HTTP/1.1
Host: localhost:50000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.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
Connection: keep-alive
Referer: http://localhost:50000/?1pm=sample&2pm=&3pm=&4pm=&5pm=


urllib.parse模块是你的朋友: https://docs.python.org/3/library/urllib.parse.html

The urllib.parse module is your friend: https://docs.python.org/3/library/urllib.parse.html

查看 urllib.parse.parse_qs (解析查询字符串,即通过GET或f发送到服务器的表单数据POST发布的orm数据,至少对于非多部分数据)。还有 cgi.FieldStorage 用于解释多部分数据。

Check out urllib.parse.parse_qs (parsing a query-string, i.e. form data sent to server by GET or form data posted by POST, at least for non-multipart data). There's also cgi.FieldStorage for interpreting multipart-data.

有关解析其余HTTP交互的信息,请参阅 RFC2616 ,这是HTTP / 1.1协议规范。

For parsing the rest of an HTTP interaction, see RFC2616, which is the HTTP/1.1 protocol specification.