程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interface test encapsulates the sending of request, JSON processing, extraction and modification

編輯:Python

Python Interface test encapsulation request Sending of , Handle json Extraction of , modify .

Catalog

  • Python Interface test encapsulation request Sending of , Handle json Extraction of , modify .
    • Share a self encapsulated request Method of sending , An example of the request is attached
      • Code instance
    • Character conversion json,dict turn json, Character conversion dict
      • python Turn character to dict
      • python send dict turn json
      • python Turn character to json object
    • json adopt key and key The index of ( from 0 The first few from top to bottom key) obtain key Corresponding value
      • precondition : win cmd Installation dependency
      • Code instance
    • json adopt json Path modification json Value
      • precondition : win cmd Installation dependency
      • Code example
    • eval The function cannot make json Character to dict Solutions for

Share a self encapsulated request Method of sending , An example of the request is attached

To achieve the effect of

Code instance

def send_requests(method, url, request_data, headers=None):
""" :param method: :param url: :param request_data: :param headers: :return: The response object """
print(" launch HTTP request ")
# Convert the request data into a dictionary object .
print(f" The request header is :{
headers}")
print(" The request method is :{}".format(method))
print(" request url by :{}".format(url))
# The replacement of double quotation marks is to facilitate the verification of data in third-party tools 
request_data_info = str(request_data).replace("'", '"')
print(f" Request data is :{
request_data_info}")
method = str(method).lower() # Lowercase processing 
if method == "get":
# request_date For the dictionary 
request_result = requests.get(url=url, params=request_data, headers=headers)
elif method == "post_params":
# Handle post I won't support it json The situation of ,request_date For the dictionary 
request_result = requests.post(url=url, params=request_data, headers=headers)
else:
# post request_date by json
request_result = requests.post(url=url, json=request_data, headers=headers)
# Return response object 
return request_result
weather_api = {
"method": "get",
"url": "https://v0.yiketianqi.com/free/day",
"params": {

"appid": "83791773",
"appsecret": "a8UpKWz2",
"city": " wuhan "
}}
print(send_requests(weather_api["method"], weather_api["url"], weather_api["params"]).json())

Character conversion json,dict turn json, Character conversion dict

python Turn character to dict

json_str = """{"appid": "83791773", "appsecret": "a8UpK23Wz2", "city": " wuhan "}"""
# Qualified characters turn dict
print(type(eval(json_str)))

python send dict turn json

json_str = {
"appid": "83791773", "appsecret": "a8UpK312Wz2", "city": " wuhan "}
# dict turn json
json_str = json.dumps(json_str)
print(json_str, type(json_str))

python Turn character to json object

# Character conversion json object 
json_str = """{"appid": "83791773", "appsecret": "a8UpK213Wz2", "city": " wuhan "}"""
json_str = json.loads(json_str)
print(json_str)

json adopt key and key The index of ( from 0 The first few from top to bottom key) obtain key Corresponding value

precondition : win cmd Installation dependency

pip install jsonpath

Code instance

jsonStr = {
'nums': 2, 'cityid': '101200101', 'city': ' wuhan ', 'date': '2022-06-30', 'week': ' Thursday ',
'update_time': '10:22',
'wea': ' Fine ', 'wea_img': 'qing', 'tem': '31', 'tem_day': '34', 'tem_night': '26', 'win': ' Southeast wind ',
'win_speed': '1 level ', 'win_meter': '5km/h', 'air': '82', 'pressure': '1001', 'humidity': '69%',
"test1": {
'city': ' wuhan 2'}}
def jsonpath_match_by_key(json, key_name, index):
""" matching json All key value pairs in , Returns... Of the specified index key Of value :param json: json :param key_name: key :param index: Indexes :return: """
bool_root_match = jsonpath.jsonpath(json, f"$.{
key_name}")
match_list = []
if bool_root_match:
match_list.append({
key_name: bool_root_match[0]})
match_list2 = jsonpath.jsonpath(json, f"$..[?(@.{
key_name})]")
if match_list2:
match_list = match_list + match_list2
return match_list[index].get(key_name)
print(jsonpath_match_by_key(jsonStr, "city", 1))

Mainly used here jsonpath Filter expression implementation , For details, you can baidu

json adopt json Path modification json Value

precondition : win cmd Installation dependency

pip install jsonpath_ng

Code example

jsonStr = {
'nums': 2, 'cityid': '101200101', 'city': ' wuhan ', 'date': '2022-06-30', 'week': ' Thursday ',
'update_time': '10:22',
'wea': ' Fine ', 'wea_img': 'qing', 'tem': '31', 'tem_day': '34', 'tem_night': '26', 'win': ' Southeast wind ',
'win_speed': '1 level ', 'win_meter': '5km/h', 'air': '82', 'pressure': '1001', 'humidity': '69%',
"test1": {
'city': ' wuhan 2'}}
def alter_by_jsonpath(json, json_path: str, alter_value):
""" according to jsonpath Match and modify json Value """
jsonpath_expr = parse(json_path)
jsonpath_expr.find(json)
jsonpath_expr.update(json, alter_value)
return json
print(alter_by_jsonpath(jsonStr, "$.test1.city", "*****AAA******"))

eval The function cannot make json Character to dict Solutions for

json The string of cannot be used eval turn dict, Generally because json There are several special values in false,true,null
And in the python These are all capitalized ,null The corresponding is None

json_str = """{"appid": false, "appsecret": true, "city": null}"""
def handle_string_fit_eval(string) -> str:
""" Handle json Character satisfaction eval() :param string: :return: """
return str(string).replace('false', 'False').replace('true', 'True').replace(
'null', 'None')
sss = eval(handle_string_fit_eval(json_str))
print(sss)
print(type(sss))



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved