如何使用BaseHTTPRequestHandler访问发送到我的服务器的数据?

时间:2013-07-17 03:28:50

标签: python post python-3.x basehttprequesthandler

我是Python的新手(使用v3.3)和网络编程,我整晚都在努力解决问题。我正在向我的服务器发出POST调用并发送一些数据,如下所示:

DATA = {"listName":"Test list","listDesc":"A test list with test stuff in it.","refreshMode":"Replace","DBKey":"1","UserDisplaySeq":"1"}
DATA = json.dumps(DATA)
METHOD = "POST"
DATA = DATA.encode("utf-8")
params = "account_id=acct 2"
try:
    URL = "http://localhost:8080/lists?" + quote_plus(params)
    request = urllib.request.Request(url=URL,data=DATA,method=METHOD)
    response = urllib.request.urlopen(request)
...

我还有一个请求处理程序编码如下(这里有很多打印语句用于调试目的):

class MyHandler(BaseHTTPRequestHandler):
...
def do_POST(self):
    length = int(self.headers['Content-Length'])
    print("HEADERS: ", self.headers)
    print (str(length))
    print(self.rfile)
    post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
    print(post_data)

这会将以下结果打印到控制台:

Starting thread
started httpserver...
HEADERS:  Accept-Encoding: identity
User-Agent: Python-urllib/3.3
Content-Length: 138
Content-Type: application/x-www-form-urlencoded
Host: localhost:8080
Connection: close


138
<_io.BufferedReader name=404>
{}

我的问题:
1)在服务器(do_POST)中,如何访问我认为我随请求发送的数据(即{“listName”:“测试列表”,“listDesc”:“测试......)?

2)我的请求是否首先发送数据?

3)是否存在以新手可访问的术语记录的地方?

2 个答案:

答案 0 :(得分:6)

试一试。我从an answer to another question

偷了它
def do_POST(self):
    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
    if ctype == 'multipart/form-data':
        postvars = cgi.parse_multipart(self.rfile, pdict)
    elif ctype == 'application/x-www-form-urlencoded':
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
    else:
        postvars = {}

    print(postvars.get("listName", "didn't find it"))

答案 1 :(得分:4)

1)在服务器(do_POST)中,如何访问我认为我发送请求的数据(即{&#34; listName&#34;:&#34;测试列表&#34; ,&#34; listDesc&#34;:&#34;测试......)?

您可以通过以下方式访问数据:

print self.rfile.read(length)。

确认这是有效的。你可以做其他解析工作。我建议使用simplejson来解码json字符串。     urllib.parse.parse_qs似乎没必要。

2)我的请求是否首先发送数据?

the code looks fine. to make sure it works, just try:

    curl -d "asdf" http://yourhost:yourport

to see if the server have same response. 
so you can know whether the server side or client side goes wrong.

3)是否存在以新手可访问的术语记录的地方?

the official document is always a good choice:
http://docs.python.org/2/library/basehttpserver.html