Python一些可能用的到的函数系列16 flask数据处理对象

黄景胜
2023-12-01

说明

在网络交互中,为了顺利进行数据对接,通常会把结果包成一个层级字典。例如:

  • res_dict
    • status
    • msg
    • data
      • data1
      • data2

这样写起来会比较费事,本篇将这样一些消息内容封装为对象,减少冗余代码。

目标

将res_dict的处理封装为对象

def get_api_input_apiregister(input_handler):
    input_data = input_handler.get_json()
    res_dict = {}

    res_dict['data'] = {}
    res_dict['data']['email'] = input_data.get('email')
    res_dict['data']['username'] = input_data.get('username') or input_data.get('email')
    res_dict['data']['password'] = input_data.get('password')
    res_dict['data']['mobile'] = input_data.get('mobile')

    if res_dict['data']['email'] is None or str(res_dict['data']['password']).strip() =='':
        res_dict['status'] = False 
        res_dict['msg'] = '邮件不能为空'
        return res_dict
    if res_dict['data']['password'] is None or str(res_dict['data']['password']).strip() =='' :
        res_dict['status'] = False 
        res_dict['msg'] = '密码不能为空'
        return res_dict    

    return res_dict 

内容

WebMsg

对象的名字就叫这个吧,主要就是为了写起来方便一些,避免重复。

import time 
class WebMsg:
    status = None 
    msg = None 
    duration = None 
    data = {}

    # 初始化名称
    def __init__(self, name):
        self.name = name
        self.start_ts = int(time.time()* 1000)

    # 转化为字典
    def to_dict(self):
        self.duration = int(time.time()* 1000) - self.start_ts
        return dict(self)
    
    # 字典的键
    def keys(self):
        return ('name','status', 'msg', 'duration','data')
    # 字典的值
    def __getitem__(self, item):
        return getattr(self, item) 

使用

def get_api_input_apiregister(input_handler):
    input_data = input_handler.get_json()
    web1 = WebMsg('input')

    # res_dict = {}

    # res_dict['data'] = {}
    # res_dict['data']['email'] = input_data.get('email')
    # res_dict['data']['username'] = input_data.get('username') or input_data.get('email')
    # res_dict['data']['password'] = input_data.get('password')
    # res_dict['data']['mobile'] = input_data.get('mobile')
    web1.data['email'] = input_data.get('email')
    web1.data['username'] = input_data.get('username') or input_data.get('email')
    web1.data['password'] = input_data.get('password')
    web1.data['mobile'] = input_data.get('mobile')

    if web1.data['email'] is None or str(web1.data['password']).strip() =='':
        web1.status = False 
        web1.msg = '邮件不能为空'
        return web1.to_dict()
    if web1.data['password'] is None or str(web1.data['password']).strip() =='' :
        web1.status = False 
        web1.msg = '密码不能为空'
        return web1.to_dict()

    web1.status =True 
    web1.msg ='ok'   
    return web1.to_dict() 
---

In [204]: data_dict = {}
     ...: data_dict['email'] = 'test@test.com'
     ...: data_dict['username'] = 'andy'
     ...: data_dict['password'] = 1123
     ...: data_dict['mobile'] = 123
     ...:
     ...: resp = req.post(url, json=data_dict)
     ...: print(json.loads(resp.text))
     ...:
{'data': {'email': 'test@test.com', 'mobile': 123, 'password': 1123, 'username': 'andy'}, 'duration': 0, 'msg': 'ok', 'name': 'input', 'status': True}

这个版本稍微精简了一点,并且结构上看起来也好一些了(用对象的属性代替了字典的层级)。也可以把一些附件的值,比如duration(执行时间)或者日志之类的包在一起,可以省事。

这只是个示意,具体使用的时候可以对WebMsg进行继承和重写。get_api_input_apiregister的大部分数据判断和处理可以进一步封装到这个新对象里面,这样在视图函数里就很精简了。

btw,本想着直接在函数里面json.dumps的,不过还是算了参考这篇文章

 类似资料: