Пример #1
0
def dict_add_models(model_name, item):
    if not getattr(models, model_name):
        print("model name = {0} error ".format(model_name))
        return
    model_bean = eval(" models.{0}()".format(model_name))
    model_bean_key = model_bean.__table__.columns.keys()
    model_bean_key_without_line = list(
        map(lambda x: x.strip('_'), model_bean_key))
    lower_table_key = list(map(lambda x: x.lower().strip('_'),
                               model_bean_key))  # 数据库的字段转小写
    for item_key in item.keys():
        if item_key.lower() in lower_table_key:  # 如果json中的key同时也存在与数据库的话
            # 找到此key在model_beankey中的位置
            index = lower_table_key.index(item_key.lower())
            if item.get(item_key) is not None:  # 如果传入的字段有值
                setattr(model_bean, model_bean_key_without_line[index],
                        item.get(item_key))
    from WeiDian.service.DBSession import get_session
    session, status = get_session()
    if status:
        session.add(model_bean)
        session.commit()
        session.close()
        return
    raise Exception("session connect error")
Пример #2
0
def add_model(model_name, **kwargs):
    print(model_name)
    if not getattr(models, model_name):
        print("model name = {0} error ".format(model_name))
        return
    model_bean = eval(" models.{0}()".format(model_name))
    for key in model_bean.__table__.columns.keys():
        if key in kwargs:
            if kwargs.get(key):  # 如果传入的字段有值
                setattr(model_bean, key, kwargs.get(key))
    from WeiDian.service.DBSession import get_session
    session, status = get_session()
    if status:
        session.add(model_bean)
        session.commit()
        session.close()
        return
    raise Exception("session connect error")
Пример #3
0
def add_models(model_name, **kwargs):
    """
    kwargs的格式为:
    {
        'data': [
            {
                key: value,
                ...
            },
            {
                key: value,
                key: value,
                ...
            }
        ]
    }
    """
    print(model_name)
    if not getattr(models, model_name):
        print("model name = {0} error ".format(model_name))
        return
    model_bean_list = []  # 初始化一个列表, 以便稍后使用add_all
    items = kwargs['data']
    for item in items:
        model_bean = eval(" models.{0}()".format(model_name))  # 创建
        for key in model_bean.__table__.columns.keys():
            if key in item:
                if item.get(key):
                    setattr(model_bean, key, item.get(key))
        model_bean_list.append(model_bean)
    from WeiDian.service.DBSession import get_session
    session, status = get_session()
    if status:
        session.add_all(model_bean_list)
        session.commit()
        session.close()
        return
    raise Exception("session connect error")