Application PB "Protocol Buffer" of the HTTP protocol

"Protocol Buffer" series of tutorials

1. The basic format using the definition of "Protocol_Buffer" the
application 2. PB "Protocol Buffer" of the HTTP protocol


Client code

This example demonstrates, respectively, the communication http + json http + manner of communication Protocol Buffer;
this example test case qtaf management framework, the actual application may be set as needed, can be only concerned with core logic;

# -*- coding: utf-8 -*-

from testbase.testcase import TestCase
from testbase import datadrive
from testbase.retry import Retry
import requests,json
import sys
from test_pb2 import Person

class Case001(TestCase):
    '''http_client
    '''
    owner = "enbowang"
    status = TestCase.EnumStatus.Ready
    priority = TestCase.EnumPriority.Normal
    timeout = 1

    #从这里开始进入核心逻辑
    def run_test(self):
        #json方式模拟
        self.start_step("http+json 请求测试")
        url = "http://127.0.0.1:8080/http_json"
        body = b'{"name":"xx.xxx"}'
        response = requests.post(url,data=body)
        self.log_info("body:" + str(body))
        self.log_info('响应状态:'+ str(response.status_code))
        self.log_info('响应内容:'+ str(response.text))

        #Protocol Buffer方式模拟,PB格式定义请见该系列上一篇文章
        self.start_step("http+Protocol Buffer 请求测试")
        url = "http://127.0.0.1:8080/http_proto"
        person = Person()
        person.name = "xx.xxx"
        person.id = 123456
        body = person.SerializeToString()
        response = requests.post(url,data=body)
        self.log_info("body:" + str(body))
        self.log_info('响应状态:'+ str(response.status_code))
        self.log_info('响应内容:'+ str(response.text))

if __name__ == '__main__':
    Case001().debug_run()

Server code

The service uses webpy achieved
were achieved with PB data analysis by the analyzing data json

# coding:utf-8
import web,json
from test_pb2 import Person
urls = (
    '/http_json', 'index',
    '/http_proto','pb'
    )

#json请求进入该逻辑
class index:
    def GET(self):
        return "Hello"
    def POST(self):
        data = web.data()
        result = json.loads(data)
        return result['name']

#pb请求进入该逻辑
class pb:
    def GET(self):
        return "Hello"
    def POST(self):
        data = web.data()
        person = Person()
                    person.ParseFromString(data)    #反序列化
        return person.name

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()

Client results are as follows

Application PB "Protocol Buffer" of the HTTP protocol

Guess you like

Origin blog.51cto.com/13384175/2408749