时如何在python中接收POST数据

时如何在python中接收POST数据

本文介绍了使用XMLHttpRequest()时如何在python中接收POST数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用XMLHttpRequest()时,我有两个关于接收数据的问题。
客户端是javascript。
服务器端是python。

I have two questions regarding receiving of data when using XMLHttpRequest().Client side is in javascript.Server side is in python.


  1. 如何在python端接收/处理数据?

  2. 如何回复HTTP请求?

客户端

    var http = new XMLHttpRequest();
    var url = "receive_data.cgi";
    var params = JSON.stringify(inventory_json);
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {
    //Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(params);

更新:
我知道我应该使用cgi.FieldStorage()但是究竟是怎么回事?尝试以我的邮件请求收到服务器错误结束。

UPDATE:I know i should use cgi.FieldStorage() but how exactly ?My attempt ended with me getting a Server error for the post request.

推荐答案

您不一定使用 cgi.FieldStorage 用于处理AJAX请求发送的POST数据。它与接收正常的POST请求相同,这意味着您需要获取请求的正文并处理该请求。

You don't necessarily use cgi.FieldStorage to handle POST data sent by an AJAX request. It is just the same as receiving a normal POST request, which means you need to get the request's body and process that.

import SimpleHTTPServer
import json

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.getheader('content-length'))
        body = self.rfile.read(content_length)
        try:
            result = json.loads(body, encoding='utf-8')
            # process result as a normal python dictionary
            ...
            self.wfile.write('Request has been processed.')
        except Exception as exc:
            self.wfile.write('Request has failed to process. Error: %s', exc.message)

这篇关于使用XMLHttpRequest()时如何在python中接收POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:02