1. 程式人生 > 實用技巧 >Python Http請求json包解析庫

Python Http請求json包解析庫

httpparser介紹

:1.解析位元組型別的http與https請求資料

:2.支援已k-v形式修改請求資料

:3.支援重新編碼請求資料

原始碼

import json
__author = "-ling"

def parser(request_data):
    # 獲取請求的三個段:
    # 1.請求方法 URI協議 版本
    # 2.請求頭(Request Header)
    # 3.請求正文
    index0 = request_data.find(b"\r\n\r\n")
    request_predata = request_data[0:index0]
    index1 
= request_predata.find(b"\r\n") # 請求方法 URI協議 版本 request_first_data = request_predata[0:index1].decode("utf-8") request_first = {} count = 0 list = ["method", 'url', 'version'] for line in request_first_data.split(" "): if line != "": request_first[list[count]]
= line count += 1 # print("解析請求方法 URI協議 版本:",request_first) # 請求頭(Request Header) request_header_data = request_predata[index1:].decode("utf-8") request_headers = {} for line in request_header_data.split("\r\n"): if line != "": line = line.replace("
","") restemp = line.split(":") if restemp[0] == "Host" and len(restemp) == 3: restemp[1] = restemp[1] + ":" +restemp[2] request_headers[restemp[0]] = restemp[1] # print("請求頭(Request Header):",request_headers) # 請求正文 request_nextdata = request_data[index0:].decode("utf-8") request_content_temp = request_nextdata.replace("\r\n", "") request_content = None if request_content_temp != "": request_content = json.loads(request_content_temp) # print("請求正文:",request_content) else: pass # print("無請求正文!") return request_first,request_headers,request_content,request_nextdata def update_first_data(request_first_data,field,data): request_first_data[field] = data def update_request_headers(request_headers,field,data): request_headers[field] = data def update_request_content(request_content,field,data): request_content[field] = data def encode(request_first_data,request_headers,request_content): request_data = b"" list = ["method", 'url', 'version'] for key in list: request_data += (request_first_data[key] + " ").encode("utf-8") request_data += "\r\n".encode("utf-8") for key in request_headers.keys(): request_data += (key + ":" + request_headers[key]).encode("utf-8") request_data += "\r\n".encode("utf-8") request_data += "\r\n".encode("utf-8") if request_content != None: request_data += json.dumps(request_content).encode("utf-8") # print("重新編碼以後的資料:",request_data.decode("utf-8")) return request_data

如何使用

1.解析請求資料

request_first,request_headers,request_content,request_nextdata = httpparser.parser(request_data)

2.修改或者增加各個部分的欄位使用

update_first_data :修改第一行欄位資料
update_request_headers :修改請求頭或者增加請求頭欄位
update_request_content :修改請求內容欄位或者增加請求內容

3.再編碼三個部分的資料

encode(request_first_data,request_headers,request_content)