增加xml返回值的基本处理逻辑

main
RogerWork 3 months ago
parent bc3e98ac08
commit e87526749f
  1. 27
      dspt_api/util/xml_util.py
  2. 65
      dspt_api/views.py

@ -0,0 +1,27 @@
import xml.etree.ElementTree as ET
def parse_dict_to_xml(_root, data):
for key, val in data.items():
child = ET.SubElement(_root, key)
if isinstance(val, str) or isinstance(val, int) or isinstance(val, float):
child.text = str(val)
else:
parse_dict_to_xml(child, val)
return _root
def get_xml(_data):
root = ET.Element('root')
xml_data = parse_dict_to_xml(root, _data)
xml_str = ET.tostring(xml_data, encoding='utf8', method='xml')
return xml_str
if __name__ == '__main__':
# failed_resp_data = {'url': '请检查foramt、pid参数', 'sig': ''}
# root = ET.Element('root')
# xml_data = parse_dict_to_xml(root, failed_resp_data)
# xml_str = ET.tostring(xml_data, encoding='utf8', method='xml')
# print(xml_str)
pass

@ -1,6 +1,7 @@
import datetime
import json
import requests
import xml.etree.ElementTree
from urllib.parse import urljoin
from django.db.models import Q
from django_filters.rest_framework import DjangoFilterBackend
@ -8,12 +9,14 @@ from django_redis import get_redis_connection
from rest_framework import filters
from rest_framework import viewsets
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse, HttpResponse
# from rest_framework.response import Response
from django.utils import timezone
from dspt_api.util.sign import Sign
from dspt_api.models import EcChannel, EcEnv, EcApi, EcApiParams, EcCinemaIds, EcRequestLog, EcApiGroup
from dspt_api.serializers import EcChannelSerializer, EcEnvSerializer, EcApiSerializer, EcApiParamsSerializer, \
EcCinemaIdsSerializer, EcRequestLogSerializer, EcApiGroupSerializer
from django.http.response import JsonResponse
from django.utils import timezone
from dspt_api.util.sign import Sign
from dspt_api.util.xml_util import get_xml
# Create your views here.
@ -75,6 +78,7 @@ def handle_request(_request):
member_type = req.get('member_type')
api = req.get('api')
params = json.loads(req.get('params'))
resp_format = params['format']
try:
base_url = EcEnv.objects.filter(Q(code=env) & Q(type=member_type)).values('host').first()['host']
except Exception as e:
@ -133,10 +137,23 @@ def general_api_url(request):
api api地址
params 请求参数
"""
# req = json.loads(request.body)
# params = json.loads(req.get('params'))
# resp_format = params['format']
req_obj, sig = handle_request(request)
failed_resp_data = {'url': '请检查foramt、pid参数', 'sig': ''}
result = {'url': req_obj.url, 'sig': sig}
if req_obj is False:
return JsonResponse({'url': '请检查foramt、pid参数', 'sig': ''})
return JsonResponse({'url': req_obj.url, 'sig': sig})
return JsonResponse(failed_resp_data)
return JsonResponse(result)
# if resp_format == 'xml':
# if req_obj is False:
# return HttpResponse(get_xml(failed_resp_data))
# return HttpResponse(get_xml(result))
# if resp_format == 'json':
# if req_obj is False:
# return JsonResponse(failed_resp_data)
# return JsonResponse(result)
# 对外接口,用于收集用户提交内容后发送请求
@ -149,6 +166,10 @@ def send_request(request):
3. 接口 api
4. 环境 env
"""
# 获取返回类型结果
req = json.loads(request.body)
params = json.loads(req.get('params'))
resp_format = params['format']
# 初始化redis
redis_conn = get_redis_connection()
user_ip = request.META.get('REMOTE_ADDR')
@ -156,34 +177,44 @@ def send_request(request):
api = web_req.get('api')
redis_key_api = f'dspt_api_{user_ip}_{api}'
# redis_key_user_data = f'dspt_api_{user_ip}_{api}_data'
# 发送请求
req, sig = handle_request(request)
failed_resp_data = {'url': '请检查foramt、pid参数', 'sig': ''}
# if resp_format == 'xml' and req is False:
# return HttpResponse(get_xml(failed_resp_data))
# if resp_format == 'json' and req is False:
# return JsonResponse(failed_resp_data)
if req is False:
return JsonResponse({'url': '请检查foramt、pid参数', 'sig': ''})
return JsonResponse(failed_resp_data)
response = requests.Session().send(req)
print('response', response)
print('response', response.content)
# 记录Redis
if redis_conn.exists(redis_key_api):
redis_conn.delete(redis_key_api)
else:
data = {
'request_url': req.url,
'response_data': response.json()
}
print(data)
redis_conn.set(redis_key_api, json.dumps(data), 10 * 60 * 60)
# redis_conn.delete(redis_key_user_data)
data = {
'request_url': req.url,
'format': resp_format,
'response_data': response.text
}
print(data)
redis_conn.set(redis_key_api, json.dumps(data), 10 * 60 * 60)
# redis_conn.delete(redis_key_user_data)
# 插入数据
db_data = {
'ip': user_ip,
'env': web_req.get('env'),
'request': req.url,
'response': response.json(),
'response': response.content,
'request_datetime': timezone.now(),
}
print(db_data)
EcRequestLog.objects.create(**db_data)
return JsonResponse(response.json())
return JsonResponse({'format': resp_format, 'data': response.text})
# if resp_format == 'xml':
# return HttpResponse(response.content)
# if resp_format == 'json':
# return JsonResponse(response.json())
# 对外接口,用于收集用户选择的数据,例如场次,卖品等,以便后续接口直接调用

Loading…
Cancel
Save