Pthon3 URL解码, Python3 httpserver案例 http post 内容提取

httpserver 简单案例

  1. http server 端
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
import logging
import base64
from urllib.parse import unquote

logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(name)s [ %(levelname)s ] %(funcName)s | %(lineno)d | %(message)s ')
logger = logging.getLogger(__name__)


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        print(content_length)
        body = self.rfile.read(content_length)
        try:
            # result = json.loads(body, encoding='utf-8')
            # print(body.decode('utf-8'))
            x_data = unquote(body.decode('utf-8'))
            wavData = x_data[23:]
            print(wavData)
            y_data = base64.b64decode(wavData.encode('utf-8'))
            print(y_data)
            with open('./myASRTFile/A4_48.wav', 'wb') as f:
                f.write(y_data)
            self.send_response(200)
            self.end_headers()
            response = BytesIO()
            response.write(b'This is POST request. ')
            response.write(b'Received: ')
            response.write(body[:23])
            self.wfile.write(response.getvalue())
        except Exception as exc:
            self.wfile.write('Request has failed to process. Error: %s' % exc.args[0])
            logger.error(exc)


if __name__ == '__main__':
    host = ('localhost', 8000)
    httpd = HTTPServer(host, SimpleHTTPRequestHandler)
    print("Starting server, listen at: %s:%s" % host)
    httpd.serve_forever()

接收post请求,并解析请求body ,使用urllib.parse里的unquote方法可以把被编码过的url里的内容解码还原。
把解析到的内容从字符串解析成二进制流写入文件

  1. http client
import base64
import requests


URL = 'http://127.0.0.1:8000/'

TOKEN = 'xxxxxxxxASRT'

with open('./A4_48.wav', 'rb') as f:
    x_data = f.read()
    # print(x_data)
    # print('=' * 90)
    y_data = base64.b64encode(x_data).decode('utf-8')
    # print(y_data)
    # print('=' * 90)
    # print(base64.b64decode(y_data.encode('utf-8')))
    # print(base64.b64decode(y_data) == x_data)
datas = {'token': TOKEN, 'wavs': y_data}

res = requests.post(url=URL, data=datas)
print(res.text)

把.wav文件以二进制流读取并处理成字符串使用post上传,达到上传文件的目的。

“”" 一个http简单的demo,新手或者没接触过的看一下就行了,不足之处烦请指出。我也是新手 “”"

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值