python http服务 post

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a1368783069/article/details/87472835

环境: node, python3.6
使用node.js 的request模块发送 post请求,请求参数放在body中。服务端使用python3 http.server搭建服务。

nodejs 请求

var request = require('request');
var qs = require('querystring')


var xml_data = "<note><to>George</to><from>John</from><heading>Reminder</heading><body>Don't forget the meeting!</body></note>"

var data =  qs.stringify({q: xml_data})
request({
  url: 'http://127.0.0.1:7700/parse',
  method: 'POST',
  body: data,
}, function(error, resp, body){
  try {
  var  r =  JSON.parse(body)
  if (r.returncode == 0) {
     console.log("success !");
  } else {
    console.log("ERROR ", r.message);
  }
  } catch (e) {
       console.log("error");
   }
});

发送的请求参数在body中。

python3 server:

import json
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs, unquote
PORT = 7700
class HandleServer(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        query = urlparse(self.path)
        returncode, msg = 0, "success"
        if query.path.strip("/") == urlparse("/parse/").path.strip("/") :
            if True:
                qdata = self.rfile.read(int(self.headers['content-length'])).decode("utf-8")
                params = parse_qs(unquote(qdata))
                q = params.get("q", [""])[0]
            except Exception as e: 
                print(e)
                returncode, msg = 2000, "ERROR"
        else:
            returncode, msg = 1000, "url path should be /parse" 
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        output = {"returncode": returncode, "message": msg}
        self.wfile.write(json.dumps(output).encode("utf-8"))


handler = HandleServer

with socketserver.TCPServer(("", PORT), handler) as httpd:
    print("server starting..", PORT)
    httpd.serve_forever()

说明:
对于post中,参数放在请求url后面的,使用 self.path 来获取。

关于读取请求中的body数据: rfile - An io.BufferedIOBase input stream, ready to read from the start of the optional input data.

猜你喜欢

转载自blog.csdn.net/a1368783069/article/details/87472835
今日推荐