python3 implementation of web terminal json communication protocol

  • 2020-05-19 05:02:09
  • OfStack

Previously, python3 was used to realize tcp protocol, and then the communication of http protocol was realized. Today, the company wants to make a functional automatic test system.

After 1 meeting in the afternoon, I found that the implementation of json format could be simpler by 1 point. The code is as follows:

The get protocol is very simple, it's directly accessible, the post protocol, it actually USES the data data, and the program automatically identifies the type.

There are three problems in the process of writing:

1 encountered an error in implementing the post protocol,

Roughly speaking, the problem of data format can be easily solved by changing to utf-8 format: bytes(data, 'utf8'),

2. The acquired json data encountered encoding problems when it encountered Chinese

Found show 0 xaa0xbb0xcc0xdd such coding, json utf8 loads call, use this code: 1. json loads (rawtext. decode (' utf8 '))

When 3 prints json, it displays a very long string of 1 line

It was very painful to see the long string, and I couldn't see the relationship between each pair of images in json at all. The Internet said that the json.tool method should be used to solve the problem, but it was for the command line.

The following code is used: print (json.dumps (jsonStr, sort_keys=False, ensure_ascii= False, indent=2)). It should be noted here that ensure_ascii must be False, otherwise there is Chinese in it

What you see is 0xx again, indent=2 means formatting json display, sort_keys means this json does not need sorting, right


#!/usr/bin/evn python3
#coding=utf-8

#  for web end json The communication library of the protocol, the communication protocol is json, outgoing data for json Format, as well as the received data json format 
#  The external call can be initialized first web_json Class, as follows: 
# get call 
# web = web_json("http://baidu.com/")
# params = "abcd/select/100000?userID=1234&groupID=79"
# web.url_get(params)
# 
# post call 
# web = web_json("http://baidu.com/")
# params = "abcd/select/100000"
# data = '{"name": "jack", "id": "1"}'
# web.url_post(params, data)

from urllib.request import urlopen
from urllib.parse import quote
import json

class web_json:
  def __init__(self, base_url):
    self.base_url = base_url
    
  def get_url_data(self, params, data):
    web = urlopen(self.base_url + params, data)
    print (web.url)
    print ("status: " , web.status)
    rawtext = web.read()
    jsonStr = json.loads(rawtext.decode('utf8'))  
    print (json.dumps(jsonStr, sort_keys=False, ensure_ascii= False, indent=2))
    return jsonStr    
  
  # get methods 
  def url_get(self, params):
    return self.get_url_data(params, None)
  
  # post methods 
  def url_post(self, params, data):
    data=bytes(data, 'utf8')
    return self.get_url_data(params, data)


Related articles: