python http服务 post

8 篇文章 0 订阅

环境: 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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值