1.eval方法即可【字典字符串转字典】
file_content = eval(file_content)
2.urllib.request.Request发送post请求,发送json参数
from urllib.request import Request, urlopen
import json
调用代码片段:
url = 'http://www.abc.1201t.com/api-sss/tdd/woRegulationCreate'
header = {
'tokenStr': "MTc2OF90b2tlbl8xNTQxNDg5NjA3MzYxLCwsMTU0MTQ4OTYwNzM2MQ==",
'Content-Type': 'application/json'
}
post_data = {"evType": "曳引与强制驱动电梯",
"groupName": "半月保养(国际)",
"memo": "hui",
"count": "31/31",
"regullations":
[
{"name": "清洁",
"desc": "机房清洁",
"state": "1"}
]
}
# post_data = urlencode(post_data).encode('utf-8')
req = Request(url=url, data=json.dumps(post_data).encode('utf-8'), headers=header, method='POST')
file_content = urlopen(req).read().decode('utf-8')
print(type(file_content))
print(file_content)
亲测可行
备注:以下是get方式和post方式请求数据
from urllib.request import Request, urlopen
from urllib.parse import quote, urlencode
import json
from module.api_test.log_util import log
success_code = 0 # 请求成功的返回code
url = 'http://172.16.2.74:8080/workOrder/detail'
params = None
header = {
'Authorization': "MTc2OF90b2tlbl8xNTQzMjg1MjAyMDU3LCwsMTU0MzI4NTIwMjA1Nw==",
'Content-Type': 'application/json'
}
post_body = {}
def post_api(url, params: dict, header: dict, post_body: dict):
"""
尝试POST方式请求接口
:param url:
:param params:
:param header:
:param post_body:
:return:
"""
if header and "Content-Type" in header.keys() and header['Content-Type'] == 'application/json': # 请求参数是json
req = Request(url=url, data=json.dumps(post_body).encode('utf-8'), headers=header, method='POST')
else: # 请求参数是map
params = urlencode(params).encode('utf-8') # 编码请求参数
req = Request(url=url, data=params, headers=header, method='POST')
process_result(req)
def get_api(url, params: dict, header: dict):
"""
尝试GET方式请求接口
:param url:
:param params: quote(params[key], safe='/', encoding='utf-8', errors=None) 防止中文编码错误问题
:param header:
:return:
"""
get_params = None
if params:
for key in params.keys():
if params[key]:
if not get_params:
get_params = "?" + quote(key, safe='/', encoding='utf-8', errors=None) + "=" + quote(params[key],
safe='/',
encoding='utf-8',
errors=None)
else:
get_params += "&" + quote(key, safe='/', encoding='utf-8', errors=None) + "=" + quote(params[key],
safe='/',
encoding='utf-8',
errors=None)
if get_params:
url += get_params
if header:
req = Request(url=url, headers=header, method='GET')
else:
req = Request(url=url, method='GET')
process_result(req)
def process_result(req):
"""
处理请求返回结果
:param req:
:return:
"""
result_content = None
try:
result_content = urlopen(req).read().decode('utf-8')
result_content = json.loads(result_content)
if result_content['code'] and not result_content['code'] == success_code:
log('------操作失败------')
log('request_url:' + url)
log('request_params:' + str(params))
log('response:' + str(result_content))
else:
log('------操作成功------')
log(str(result_content))
except Exception as excp:
log('------请求异常------')
log('request_url:' + url)
log('request_params:' + str(params))
log('response:' + str(result_content))
log('error:' + str(excp))
if __name__ == '__main__':
# url = "http://172.16.2.74:8080/elevator/getEvList"
# params = {'cityId': "2282", "projectName": "花满楼", "page": "1", "pageSize": "11"}
# get_api(url, params, header)
# url = 'http://172.16.2.74:8080/alarm/wxAlarm'
# params = {
# "description": "",
# "evId": "197363018554679296",
# "openId": "o8xzN0eBwTNVYbnbxF7qf5H928gw",
# "trap": 1
# }
# post_api(url,params,header,params)
url = 'http://api.mmtt.ojict.com/api-elorr/elevatorInfo/updateElevatorFileNumber'
header = {
'tokenStr': "MTc2OF90b2tlbl8xNTQzMzk4NzEzMDUyLCwsMTU0MzM5ODcxMzA1Mg=="
}
params = {
"evId": "197363018554679296",
"fileNumber": "o8xzN0eBwTNVYbnbxF7qf5H928gw"
}
post_api(url, params, header, params)