递归与树的写法
data:
data=[ {"cat_id":1,"name":"北京","parent_id":0}, {"cat_id":2,"name":"上海","parent_id":0}, {"cat_id":3,"name":"沙河","parent_id":1}, {"cat_id":4,"name":"sb镇","parent_id":3}, {"cat_id":5,"name":"昌平","parent_id":1}, {"cat_id":6,"name":"青浦","parent_id":2}, ]
#需求 ''' 问题: 我们数据不是有序的,但是我们要排序,并归类,把父集放在子集的前面,辈分等级通过level标明 '''
实现的方法
res=[] def get_son(data,level=0,parent_id=0,is_clear=True): if is_clear: res.clear() for item in data: if item['parent_id']==parent_id: item['level']=level res.append(item) get_son(data,level=level+1,parent_id=item['cat_id'],is_clear=False) return res
实现树状的等级分类
''' 问题: 因为前端,需要通过循环多少成来,展示多个等级 for item in data: print(item.name) for item1 in item.children item1.name 归档:我要把我的子集,都放在我的children列表里面 '''
def get_tree(data): lists=[] tree={} for i in data: tree[i['cat_id']]=i for item in data: if not item['parent_id']: lists.append(tree[item['cat_id']]) else: if "children" not in tree[item['parent_id']]: tree[item['parent_id']]['children']=[] tree[item['parent_id']]['children'].append(tree[item['cat_id']]) return lists
分析
多种支付的设计
例如实现微信或支付宝等支付接口的封装.
封装的支付接口方法
class Notity(APIView): def post(self,request,paymethon): pay_file = importlib.import_module(f"app01.Pay.{paymethon}") pay_class = getattr(pay_file, paymethon) data=pay_class().notity(request.data) if data['status']=="success": models.Order.objects.filter(order_id=data['order']).updata(pay_status=1)
pay.Alipay.py
class Alipay(): def pay(self): pass "order/notify/Alipay" def notity(self,data): data['shangcheng_id'] data['sucess'] if data['sucess']="00": return_data['stauts']="success" return_data['order_id'] = data['shangcheng_id'] return return_data else: pass
pay.Wxpay.py
import time from app01.wx import settings class Wxpay: def pay(self,order_data): self.order_id = order_data["order_id"] self.open_id = order_data['open_id'] self.ip = order_data['ip'] data_body = self.get_body_data() import requests url = "https://api.mch.weixin.qq.com/pay/unifiedorder" response = requests.post(url, data_body.encode("utf-8"), headers={'content-type': "application/xml"}) res_dict = self.xml_to_dic(response.content) timeStamp = str(int(time.time())) paySign = self.get_pay_sign(res_dict, timeStamp) data_dic = { 'timeStamp': timeStamp, 'nonceStr': res_dict['nonce_str'], 'package': f"prepay_id={res_dict['prepay_id']}", 'signType': 'MD5', "paySign": paySign, } return data_dic