python 模拟http请求服务端,完成对异步回调接口的监听

1.背景
项目上暴露的翻译接口支持异步调用,调用参数中可以根据填写的回调地址完成请求实际响应数据的发送。异步翻译调用接口简单易懂。但是测试接口实际功能时,就需要模拟一个http客户端用来接收异步返回的响应数据,用以验证接口功能的完整性。
2.异步请求接口
异步请求接口,功能表现为发送请求后会先返回一个请求状态的响应数据,一般表示服务端已经接受请求,请求成功。请求参数中会带有回调地址,待请求服务端完成请求处理后会根据回调地址,发送响应数据(发送响应的服务端可理解为客户端)

body = {
        "id":time.time(),  ###任务id,string 
        "itsType":type, ###翻译方向
        "itsText":txt, ###翻译原始内容
        "callbackUrl":callback ###翻译请求回调地址

    }

3.模拟http服务端 响应请求

# -*-coding:u8-*-
import time
import json
import socket
import threading

encoding = 'utf-8'
BUFSIZE = 102400

###接收回调内容 并进行解析和响应 
def handle_client(client):
        data = client.recv(BUFSIZE)
        callback_data = ''
        string = bytes.decode(data, encoding)

        split_result = string.split("\r\n\r\n")
        print(split_result)
###获取响应内容的字节长度
        content_length = int(split_result[0].replace(" ", "").split(":")[-1])
        print (content_length)
        #time.sleep(100)
        callback_data = split_result[-1].encode("utf-8")
        # print "content_length : " + str(content_length)
        # print callback_data
        # print "callback_length : " + str(len(callback_data))
        while True:
            # print len(callback_data)
            # print content_length
            if len(callback_data) == content_length:
                start_time = time.time()
                try:
                    if (callback_data):
                    ##转化字节内容为json格式
                        json_callback = json.loads(callback_data.decode("utf-8"))
                        print (json_callback)
                        req_time =json_callback["id"]
                        fulltext = json_callback["fullText"]
                        print (req_time,fulltext)
                        #allback_obj = json.loads(callback_data, encoding="utf-8")
                        # print callback_obj["id"]
                        # print callback_obj["languageResult"]
                        #cost_time = start_time - float(callback_obj["id"])
                        #print (cost_time)
                        ####构造响应回调请求的信息并发送
                        responseHeaderLines = "HTTP/1.1 200 OK\r\n"
                        responseHeaderLines += "\r\n"
                        responseBody = "hello world"
                        response = responseHeaderLines + responseBody
                        b_response=response.encode(encoding="utf-8")
                        client.send(b_response)
                        #conn.send(b_response)
                        #client.send()
                        content_length += 1
                        #client.close()
                    else:
                        print ("callback_data is null !")
                        #######client.close()
                        return 0,0
                except Exception as e:
                	print(e)



if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(("10.5.124.17", 9011))  ##绑定ip和端口
    server_socket.listen(0)
    client, cltadd = server_socket.accept()
    #while True:
    handle_client(client)



4.发送请求查看回调监听表现
发送异步回调请求


#coding=utf-8
import requests
import json
import socketserver
#import soc
import  time
def post_trans_asyn(txt,type,callback):
    host = "http://10.5.4.20:9800/txt/its"
    body = {
        "id":time.time(),
        "itsType":type,
        "itsText":txt,
        "callbackUrl":callback

    }
    print ("hello world")
    post_res = requests.post(url=host,json=body)
    print (post_res.text)
if __name__=='__main__':
    tran_text="Det her vil tage hele dagen."
    type = "dacn"
    callback = "http://10.5.124.17:9011"
    post_trans_asyn(tran_text,type,callback)

你可能感兴趣的:(python,http,socket)