Processing HTTP GET input parameter on server side in python

假如想象 提交于 2019-11-28 20:27:57

You can parse the query of a GET request using urlparse, then split the query string.

from urlparse import urlparse
query = urlparse(self.path).query
query_components = dict(qc.split("=") for qc in query.split("&"))
imsi = query_components["imsi"]
# query_components = { "imsi" : "Hello" }

# Or use the parse_qs method
from urlparse import urlparse, parse_qs
query_components = parse_qs(urlparse(self.path).query)
imsi = query_components["imsi"] 
# query_components = { "imsi" : ["Hello"] }

You can confirm this by using

 curl http://your.host/?imsi=Hello
Ken Kinder

BaseHTTPServer is a pretty low-level server. Generally you want to use a real web framework that does this kind of grunt work for you, but since you asked...

First import a url parsing library. In Python 2,x it's urlparse. (In Python3, you'd use urllib.parse)

import urlparse

Then, in your do_get method, parse the query string.

imsi = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('imsi', None)
print imsi  # Prints None or the string value of imsi

Also, you could be using urllib in your client code and it would probably be a lot easier.

cgi module contains FieldStorage class which is supposed to be used in CGI context, but seems to be easily used in your context as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!