6

我是 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":"Test list","listDesc":"A test...) ?

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

3) 是否有地方以新手可访问的术语记录这一点?

4

2 回答 2

9

试试这个。我从另一个问题的答案中偷了它

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"))
于 2013-07-17T03:37:26.733 回答
4

1) 在服务器 (do_POST) 中,我如何访问我认为与我的请求一起发送的数据(即 {"listName":"Test list","listDesc":"A test...)?

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

打印 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
于 2013-07-17T04:04:21.353 回答