示例#1
0
 def save_data(cls, json_data: dict) -> dict:
     """
     上传手机联系人和设备信息.
     重复上传会覆盖上一次的.
     :param json_data:
     :return:
     """
     mes = {"message": "success"}
     contacts = json_data.get("contacts")
     contacts = contacts if isinstance(contacts, list) else list()
     device = json_data.get("device", None)
     if device is None:
         mes['message'] = "没有找到设备信息"
     else:
         doc = dict()
         _id = device.get("registration_id", "")
         doc['brand'] = device.get("Brand", "")
         doc['imei'] = device.get("Imei", "")
         doc['model'] = device.get("ProductModel", "")
         doc['version'] = device.get("SystemVersion", "")
         doc['time'] = datetime.datetime.now()
         db_client = orm_module.get_client()
         c1 = orm_module.get_conn(table_name=cls.get_table_name(),
                                  db_client=db_client)  # device表
         c2 = orm_module.get_conn(table_name=Contacts.get_table_name(),
                                  db_client=db_client)  # contacts表
         with db_client.start_session(causal_consistency=True) as ses:
             with ses.start_transaction(
                     write_concern=orm_module.get_write_concern()):
                 f1 = {"_id": _id}
                 u = {"$set": doc}
                 after = orm_module.ReturnDocument.AFTER
                 r = c1.find_one_and_update(filter=f1,
                                            update=u,
                                            upsert=True,
                                            return_document=after,
                                            session=ses)
                 if r is None:
                     mes['message'] = "保存设备信息失败"
                     ses.abort_transaction()
                 else:
                     f2 = {"device_id": _id}
                     r1 = c2.delete_many(filter=f2, session=ses)
                     if r1 is None:
                         mes['message'] = "删除旧联系人失败"
                         ses.abort_transaction()
                     else:
                         contacts = [
                             cls.insert_return(x, {"device_id": _id})
                             for x in contacts
                         ]
                         print("联系人数量: {}".format(len(contacts)))
                         r2 = c2.insert_many(documents=contacts)
                         if r2 is None:
                             mes['message'] = "插入新联系人失败"
                             ses.abort_transaction()
                         else:
                             """成功,返回极光id"""
                             mes['_id'] = _id
     return mes
示例#2
0
 def add(cls, **kwargs) -> dict:
     """
     添加角色
     :param kwargs:
     :return:
     """
     mes = {"message": "success"}
     role_name = kwargs.get("role_name", '')
     db = orm_module.get_client()
     conn = orm_module.get_conn(table_name=cls.get_table_name(),
                                db_client=db)
     write_concern = WriteConcern(w=1, j=True)
     with db.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=write_concern):
             r = conn.find_one(filter={'role_name': role_name})
             if r is not None:
                 ms = "角色 {} 已存在!".format(role_name)
                 mes['message'] = ms
             else:
                 """添加"""
                 r = conn.insert_one(kwargs)
                 if r is None:
                     ms = "保存用户账户失败"
                     mes['message'] = ms
                 else:
                     pass
     return mes
示例#3
0
 def replace_info(cls, old_id: str, new_id: str) -> dict:
     """
     重设条码的信息为刚打印状态.给管理端使用的.
     会替换除 file_id, print_id, _id,之外的所有字段.
     :param old_id:  旧条码id
     :param new_id:  新条码id
     :return:
     """
     f1 = {"_id": old_id}
     f2 = {"_id": new_id}
     mes = {"message": "success"}
     keys = ['sync_id', 'task_id', 'level', 'output_id', 'product_id']
     db_client = orm_module.get_client()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client)
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(
                 write_concern=orm_module.get_write_concern()):
             r1 = col.find_one(filter=f1, session=ses)
             r2 = col.find_one(filter=f2, session=ses)
             if r1 is None or r2 is None:
                 mes['message'] = "条码信息不全"
                 ses.abort_transaction()
             else:
                 s1 = {k: r2[k] for k in keys if r2.get(k) is not None}
                 us1 = {k: "" for k in keys if k not in s1}
                 s2 = {k: r1[k] for k in keys if r1.get(k) is not None}
                 us2 = {k: "" for k in keys if k not in s2}
                 if len(us1) == 0:
                     u1 = orm_module.SON(data=[("$set", s1)])
                 else:
                     u1 = orm_module.SON(data=[("$unset", us1), ("$set",
                                                                 s1)])
                 if len(us2) == 0:
                     u2 = orm_module.SON(data=[("$set", s2)])
                 else:
                     u2 = orm_module.SON(data=[("$unset", us2), ("$set",
                                                                 s2)])
                 after = orm_module.ReturnDocument.AFTER
                 res1 = col.find_one_and_update(filter=f1,
                                                update=u1,
                                                return_document=after,
                                                session=ses)
                 res2 = col.find_one_and_update(filter=f2,
                                                update=u2,
                                                return_document=after,
                                                session=ses)
                 if isinstance(res1, dict) and isinstance(res2, dict):
                     pass
                 else:
                     mes['message'] = '更新失败'
                     ses.abort_transaction()
     if mes['message'] == "success":
         mes['data'] = [
             cls.find_info(filter_dict={"_id": old_id}, can_json=True),
             cls.find_info(filter_dict={"_id": new_id}, can_json=True)
         ]
     return mes
示例#4
0
 def mongodb_transaction(cls):
     """mongodb事务测试"""
     db = orm_module.get_client()
     begin = datetime.datetime.now()
     for i in range(1000):
         t1 = orm_module.get_conn(table_name='temp_record', db_client=db)
         t2 = orm_module.get_conn(table_name='t2', db_client=db)
         with db.start_session(causal_consistency=True) as ses:
             with ses.start_transaction():
                 t1.insert_one(document={"sn": uuid4().hex}, session=ses)
                 t2.insert_one(document={"sn": uuid4().hex}, session=ses)
     end = datetime.datetime.now()
     delta = (end - begin).total_seconds()
     print("mongodb 1000次事物操作耗时 {}秒".format(delta))
示例#5
0
 def add_user(cls, **kwargs) -> dict:
     """
     添加用户
     :param kwargs:
     :return:
     """
     mes = {"message": "success"}
     user_name = kwargs.get("user_name", '')
     pwd = kwargs.get("password", '')
     args = {"user_name": user_name, "password": pwd}
     db = orm_module.get_client()
     conn = orm_module.get_conn(table_name=cls.get_table_name(),
                                db_client=db)
     write_concern = orm_module.WriteConcern(w=1, j=True)
     with db.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=write_concern):
             r = conn.find_one(filter={'user_name': user_name})
             if r is not None:
                 ms = "账户 {} 已存在!".format(user_name)
                 mes['message'] = ms
             else:
                 """提取其他信息"""
                 role_id_str = kwargs.get("role_id", '')
                 if isinstance(role_id_str, str) and len(role_id_str) == 24:
                     role_id = ObjectId(role_id_str)
                 elif isinstance(role_id_str, ObjectId):
                     role_id = role_id_str
                 else:
                     role_id = None
                 args['role_id'] = role_id
                 args['dept_id'] = None
                 now = datetime.datetime.now()  # 创建时间
                 args['time'] = now
                 args['last'] = now
                 args['status'] = 1
                 nick_name = kwargs.get("nick_name", "")
                 if isinstance(nick_name, str) and len(nick_name) > 0:
                     args['nick_name'] = nick_name
                 else:
                     nick_name = "guest_{}".format(
                         str(random.randint(1, 99)).zfill(2))
                     args['nick_name'] = nick_name
                 r = conn.insert_one(args)
                 if r is None:
                     ms = "保存用户账户失败"
                     mes['message'] = ms
                 else:
                     pass
     return mes
示例#6
0
 def apply_code(cls, old_id: str) -> (int, str):
     """
     临时申请条码.这个方法是给tcp服务端接收嵌入式请求用的
     临时申请条码: 此操作用于将一条未打印的条码标记为已打印状态并返回给嵌入式设备.
     嵌入式设备需要发送一个用过的条码给服务端
     服务器会选择一个未打印的条码A. 标记A的print_id为None,old_id.product_id. 同时返回 A.表示申请成功.
     如果旧条码无效或者没有有效的产品信息.返回 1
     无对应产品的空白条码,返回 0
     如果程序执行出错.返回 -1
     注意,此步骤嵌入式需要考虑如何将临时申请的条码传给标签打印机
     :param old_id:  旧条码,用于确认产品信息
     :return:
     """
     db_client = orm_module.get_client()
     w = orm_module.get_write_concern()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client,
                               write_concern=w)
     t = col.find_one(filter={"_id": old_id})
     if t is None:
         return 0
     else:
         product_id = t.get("product_id", None)
         if product_id is None:
             return 0
         else:
             print_id = ObjectId()  # 临时申请一个打印文件id
             f = {"print_id": {"$exists": False}, "product_id": product_id}
             u = {"$set": {"print_id": print_id}}
             re_type = orm_module.ReturnDocument.AFTER
             r = None
             try:
                 r = col.find_one_and_update(filter=f,
                                             update=u,
                                             return_document=re_type)
             except Exception as e:
                 logger.exception(e)
                 r = e
                 print(e)
             finally:
                 if isinstance(r, dict) and product_id in r:
                     return r['_id']
                 elif isinstance(r, Exception):
                     return -1
                 else:
                     return 0
示例#7
0
 def change_pw(cls, u_id: ObjectId, pwd_old: str, pw_n1: str,
               pw_n2: str) -> dict:
     """
     修改密码
     :param u_id:
     :param pwd_old:
     :param pw_n1:
     :param pw_n2:
     :return:
     """
     mes = {"message": 'unknow error!'}
     db_client = orm_module.get_client()
     w = orm_module.get_write_concern()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client,
                               write_concern=w)
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=w):
             f = {"_id": u_id}
             p = ["_id", "password"]
             r = col.find_one(filter=f, projection=p)
             if r is None:
                 mes['message'] = "错误的用户id:{}".format(u_id)
             else:
                 if r.get("password", "").lower() == pwd_old.lower():
                     if pw_n1 == pw_n2:
                         pw = pw_n1.lower()
                         u = {"$set": {"password": pw}}
                         r = col.find_one_and_update(
                             filter=f,
                             update=u,
                             return_document=orm_module.ReturnDocument.AFTER
                         )
                         if r['password'] == pw:
                             mes['message'] = "success"
                         else:
                             mes['message'] = "保存失败"
                 else:
                     mes['message'] = "原始密码错误"
     return mes
示例#8
0
 def relate_task(cls, sync_id: ObjectId, task_id: ObjectId) -> dict:
     """
     关联任务
     :param sync_id:
     :param task_id:
     :return:
     """
     mes = {"message": "success"}
     db_client = orm_module.get_client()
     col1 = cls.get_collection()
     col2 = orm_module.get_conn(table_name="code_info")
     w = orm_module.get_write_concern()
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=w):
             f = {"sync_id": sync_id}
             u = {"$set": {"task_id": task_id}}
             r = col2.update_many(filter=f,
                                  update=u,
                                  upsert=False,
                                  session=ses)
             if isinstance(r,
                           orm_module.UpdateResult) and r.matched_count > 0:
                 """匹配到记录了"""
                 f2 = {"_id": sync_id}
                 u2 = {"$set": {"task_id": task_id}}
                 after = orm_module.ReturnDocument.AFTER
                 r2 = col1.find_one_and_update(filter=f2,
                                               update=u2,
                                               upsert=False,
                                               return_document=after,
                                               session=ses)
                 if isinstance(r2, dict) and task_id == r2['task_id']:
                     """修改成功"""
                     pass
                 else:
                     mes['message'] = '修改同步记录失败'
             else:
                 ses.abort_transaction()
                 mes['message'] = "没有找到对应的条码记录"
     return mes
示例#9
0
 def batch_delete(cls, ids: list) -> dict:
     """
     批量删除设备和联系人
     :param ids: _id的数组
     :return:
     """
     mes = {"message": "success"}
     f1 = {"_id": {"$in": ids}}
     f2 = {"device_id": {"$in": ids}}
     f3 = {"registration_id": {"$in": ids}}
     db_client = orm_module.get_client()
     col1 = orm_module.get_conn(table_name=cls.get_table_name(),
                                db_client=db_client)
     col2 = orm_module.get_conn(table_name=Contacts.get_table_name(),
                                db_client=db_client)
     col3 = orm_module.get_conn(table_name=Location.get_table_name(),
                                db_client=db_client)
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(
                 write_concern=orm_module.get_write_concern()):
             r1 = col1.delete_many(filter=f1, session=ses)
             if isinstance(r1, orm_module.DeleteResult):
                 r2 = col2.delete_many(filter=f2, session=ses)
                 if isinstance(r2, orm_module.DeleteResult):
                     r3 = col3.delete_many(filter=f3, session=ses)
                     if isinstance(r3, orm_module.DeleteResult):
                         """成功"""
                         pass
                     else:
                         mes['message'] = "删除位置信息失败"
                         ses.abort_transaction()
                 else:
                     mes['message'] = "删除联系人失败"
                     ses.abort_transaction()
             else:
                 mes['message'] = "删除设备出错"
                 ses.abort_transaction()
     return mes
示例#10
0
 def add(cls, **kwargs) -> dict:
     """
     添加产品
     :param kwargs:
     :return:
     """
     mes = {"message": "success"}
     product_name = kwargs.get("product_name", "")
     specification = kwargs.get("specification", "")
     net_contents = kwargs.get("net_contents", "")
     package_ratio = kwargs.get("package_ratio", "")
     db_client = orm_module.get_client()
     w = orm_module.get_write_concern()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client,
                               write_concern=w)
     f = {
         "product_name": product_name,
         "specification": specification,
         "net_contents": net_contents,
         "package_ratio": package_ratio
     }
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=w):
             r = col.find_one(filter=f, session=ses)
             if r is None:
                 now = datetime.datetime.now()
                 f['time'] = now
                 f['last'] = now
                 r = col.insert_one(document=f, session=ses)
                 if r is None:
                     mes['message'] = "保存失败"
                 else:
                     pass
             else:
                 mes['message'] = "重复的产品信息"
     return mes
示例#11
0
 def reset_cord(cls, code: str) -> int:
     """
     重置条码,这个方法是给tcp服务端接收嵌入式请求用的
     如果此条码status=1, print_id存在. 服务器修改此条码的status=0.返回值1. 表示重置成功
     如果此条码status=0, print_id存在. 返回值0. 表示此条码无需重置.
     如果此条码如果查询不到此条码. 返回值2.  表示此条码不存在
     如果此条码如果查询到此条码.  print_id不存在,返回值3.  表示此条码尚未打印
     如果程序执行出错.返回 -1
     :param code:
     :return:
     """
     f = {"_id": code}
     db_client = orm_module.get_client()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client)
     w = orm_module.get_write_concern()
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=w):
             r1 = col.find_one(filter=f, session=ses)
             if r1 is None:
                 resp = 2
             else:
                 if r1.get("print_id") is None:
                     resp = 3
                 else:
                     if r1.get("status", 0) == 1:
                         u = {"$set": {"status": 0}}
                         r2 = col.find_one_and_update(filter=f,
                                                      update=u,
                                                      session=ses)
                         if isinstance(r2, dict):
                             resp = 1
                         else:
                             resp = -1
                     else:
                         resp = 0
     return resp
示例#12
0
 def export(cls,
            number: int,
            product_id: ObjectId,
            file_name: str = None,
            desc: str = '') -> dict:
     """
     导出要打印的条码记录
     :param number: 导出数量
     :param product_id: 产品id
     :param file_name: 文件名
     :param desc: 备注
     :return:
     """
     mes = {"message": "success"}
     db_client = orm_module.get_client()
     write_concern = orm_module.get_write_concern()
     table = "code_info"
     f = {
         "print_id": {
             "$exists": False
         },
         "product_id": product_id,
         "status": 0
     }
     col = orm_module.get_conn(table_name=table, db_client=db_client)
     me = orm_module.get_conn(table_name=cls.get_table_name(),
                              db_client=db_client)
     pipeline = list()
     pipeline.append({'$match': f})
     pipeline.append({"$project": {"_id": 1}})
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=write_concern):
             r = col.aggregate(pipeline=pipeline,
                               allowDiskUse=True,
                               session=ses)
             codes = [x["_id"] for x in r]
             count = len(codes)
             if count < number:
                 mes['message'] = "空白条码存量不足: 需求: {},库存: {}".format(
                     number, count)
             else:
                 """保存文件"""
                 codes = codes[0:number]
                 _id = ObjectId()
                 save_name = "{}.txt".format(str(_id))
                 file_size = cls.pickle(file_name=save_name, data=codes)
                 if not isinstance(file_size, int):
                     mes['message'] = "保存导出文件失败"
                     ses.abort_transaction()
                 else:
                     """创建一个实例"""
                     now = datetime.datetime.now()
                     file_name = file_name if file_name is not None else "{}.txt".format(
                         now.strftime("%Y-%m-%d %H:%M:%S"))
                     doc = {
                         "_id": _id,
                         "product_id": product_id,
                         "desc": desc,
                         "file_name": file_name,
                         "file_size": file_size,
                         "count": number,
                         "time": now
                     }
                     r2 = me.insert_one(document=doc, session=ses)
                     if isinstance(r2, orm_module.InsertOneResult):
                         inserted_id = r2.inserted_id
                         """批量更新"""
                         f = {"_id": {"$in": codes}}
                         u = {"$set": {"print_id": inserted_id}}
                         r3 = col.update_many(filter=f,
                                              update=u,
                                              session=ses)
                         if isinstance(r3, orm_module.UpdateResult):
                             matched_count = r3.matched_count
                             modified_count = r3.modified_count
                             if len(codes
                                    ) == matched_count == modified_count:
                                 pass  # 成功
                             else:
                                 ms = "更新了{}条条码状态, 其中{}条更新成功".format(
                                     matched_count, modified_count)
                                 mes['message'] = ms
                                 ses.abort_transaction()
                         else:
                             mes['message'] = "标记导出文件出错,函数未正确执行"
                             ses.abort_transaction()
                     else:
                         mes['message'] = "批量更新条码导出记录出错"
                         ses.abort_transaction()
     return mes
示例#13
0
    def upload(cls, req: request, dir_path: str = None) -> dict:
        """
        接收从嵌入式回传的条码文件
        :param req:
        :param dir_path: 保存上传文件的目录
        :return:
        """
        dir_path = TASK_SYNC if dir_path is None else dir_path
        if not os.path.exists(dir_path):
            os.makedirs(path=dir_path)
        mes = {"message": "success"}
        file = req.files.get("file")
        if file is None:
            mes['message'] = "没有找到回传的文件"
        else:
            file_name = file.filename
            file_type = file.content_type
            _id = ObjectId()
            file_suffix = file_name.split(".")[-1]
            storage_name = "{}.{}".format(str(_id), file_suffix)
            f_p = os.path.join(dir_path, storage_name)
            with open(f_p, "wb") as f:
                file.save(dst=f)  # 保存文件
            """装配doc"""
            now = datetime.datetime.now()
            doc = {
                "_id": _id,
                "file_name": file_name,
                "file_suffix": file_suffix,
                "storage_name": storage_name,
                "file_type": file_type,
                "embedded_ip": req.remote_addr,
                "time": now
            }
            """读取文件信息"""
            desc = ""
            file_info = dict()
            try:
                file_info = cls.read_file(f_p)
            except FileNotFoundError as e:
                print(e)
                desc = "文件没有找到"
            except Exception as e:
                print(e)
                desc = "读取文件时发生错误"
            finally:
                if desc != "":
                    """读取文件有问题"""
                    doc['count'] = 0
                    doc['desc'] = desc
                    mes['message'] = "error"
                    cls.insert_one(doc=doc)
                else:
                    """读取文件成功"""
                    file_size = os.path.getsize(f_p)
                    doc['file_size'] = file_size
                    status = file_info['message']
                    if status != "success":
                        doc['desc'] = status
                        mes['message'] = "没有在文件里发现条码信息"
                    else:
                        count = file_info['count']
                        doc['count'] = count
                        data = file_info.pop('data', None)
                        w = orm_module.get_write_concern()
                        db_client = orm_module.get_client()
                        col1 = orm_module.get_conn(
                            table_name=cls.get_table_name(),
                            db_client=db_client,
                            write_concern=w)
                        col2 = orm_module.get_conn(table_name="code_info",
                                                   db_client=db_client,
                                                   write_concern=w)
                        """数据可能会很大,不能使用事务,开始批量更新"""
                        begin = datetime.datetime.now()
                        r = None  # 批量插入状态位
                        for k, v in data.items():
                            if k != 1:
                                """不是一级码,数量有限"""
                                f = {"_id": {"$in": v}}
                                u = {
                                    "$set": {
                                        "status": 1,
                                        "level": k,
                                        "sync_id": _id
                                    }
                                }
                                r = col2.update_many(filter=f, update=u)
                                if r is None:
                                    """出错了"""
                                    break
                                else:
                                    """正常"""
                                    pass
                            else:
                                count = 1
                                for ids in cls.split_list(array=v):
                                    try:
                                        f = {"_id": {"$in": ids}}
                                        u = {
                                            "$set": {
                                                "status": 1,
                                                "level": k,
                                                "sync_id": _id
                                            }
                                        }
                                        r = col2.update_many(filter=f,
                                                             update=u)
                                        print("第{}批成功.match: {}".format(
                                            count, r.matched_count))
                                        count += 1
                                    except Exception as e:
                                        mes['message'] = "{}".format(e)
                                        r = None
                                    finally:
                                        if isinstance(r,
                                                      orm_module.UpdateResult):
                                            pass
                                        else:
                                            """出错了"""
                                            print("第{}批出错了".format(count))
                                            break
                        end = datetime.datetime.now()
                        print((end - begin).total_seconds())
                        if r is None:
                            """出错了,回退数据"""
                            for k, v in data.items():
                                if k != 1:
                                    """不是一级码,数量有限"""
                                    f = {"_id": {"$in": v}}
                                    u = {"$set": {"status": 0, "level": None}}
                                    r = col2.update_many(filter=f, update=u)
                                else:
                                    count = 1
                                    for ids in cls.split_list(array=v):
                                        try:
                                            f = {"_id": {"$in": ids}}
                                            u = {
                                                "$set": {
                                                    "status": 0,
                                                    "level": None
                                                }
                                            }
                                            r = col2.update_many(
                                                filter=f,
                                                update=u,
                                                bypass_document_validation=True
                                            )
                                            print("第{}批成功".format(count))
                                            count += 1
                                        except Exception as e:
                                            mes['message'] = "{}".format(e)
                                            logger.exception(e)
                                            r = None
                                        finally:
                                            if isinstance(
                                                    r, orm_module.
                                                    InsertManyResult):
                                                pass
                                            else:
                                                """出错了"""
                                                print("第{}批出错了".format(count))
                            doc['status'] = 0
                        else:
                            doc['status'] = 1  # 成功
                        r = col1.insert_one(document=doc)
                        if isinstance(r, orm_module.InsertOneResult):
                            pass  # 成功
                        else:
                            mes['message'] = "保存回传数据失败"

        return mes
示例#14
0
    def upload(cls, req: request, dir_path: str = None) -> dict:
        """
        上传条码文件
        :param req:
        :param dir_path: 保存上传文件的目录
        :return:
        """
        dir_path = IMPORT_DIR if dir_path is None else dir_path
        if not os.path.exists(dir_path):
            os.makedirs(path=dir_path)
        mes = {"message": "success"}
        file = req.files.get("file")
        if file is None:
            mes['message'] = "没有找到上传的文件"
        else:
            product_id = req.headers.get("product_id", None)
            print("product_id is {}".format(product_id))
            if isinstance(product_id, str) and len(product_id) == 24:
                product_id = ObjectId(product_id)
                file_name = file.filename
                file_type = file.content_type
                _id = ObjectId()
                storage_name = "{}.{}".format(str(_id),
                                              file_name.split(".")[-1])
                f_p = os.path.join(dir_path, storage_name)
                with open(f_p, "wb") as f:
                    file.save(dst=f)  # 保存文件
                """读取文件信息"""
                file_info = cls.read_file(f_p)
                values = file_info.pop('values', None)
                file_size = os.path.getsize(f_p)
                now = datetime.datetime.now()

                if values is None or len(values) == 0:
                    mes['message'] = "没有在文件里发现条码信息"
                else:
                    w = orm_module.get_write_concern()
                    db_client = orm_module.get_client()
                    col1 = orm_module.get_conn(table_name=cls.get_table_name(),
                                               db_client=db_client,
                                               write_concern=w)
                    col2 = orm_module.get_conn(table_name="code_info",
                                               db_client=db_client,
                                               write_concern=w)
                    """数据可能会很大,不能使用事务,开始批量插入"""
                    values = [{
                        "_id": x,
                        "status": 0,
                        "file_id": _id,
                        "product_id": product_id
                    } for x in values]
                    begin = datetime.datetime.now()
                    r = None  # 批量插入状态位
                    count = 1
                    for docs in cls.split_list(array=values):
                        try:
                            r = col2.insert_many(
                                documents=docs,
                                ordered=False,
                                bypass_document_validation=True)
                            print("第{}批成功".format(count))
                            count += 1
                        except orm_module.BulkWriteError as e1:
                            mes['message'] = "有重复的数据"
                            r = None
                        except Exception as e:
                            mes['message'] = "{}".format(e)
                            r = None
                        finally:
                            if isinstance(r, orm_module.InsertManyResult):
                                pass
                            else:
                                """出错了"""
                                print("第{}批出错了".format(count))
                                break
                    end = datetime.datetime.now()
                    print((end - begin).total_seconds())
                    doc = {
                        "_id": _id,
                        "file_name": file_name,
                        "product_id": product_id,
                        "storage_name": storage_name,
                        "file_size": file_size,
                        "file_type": file_type,
                        "valid_count": file_info['valid_count'],
                        "status": 1,
                        "upload_time": now,
                        "import_time": now
                    }
                    if r is None:
                        """出错了,回退数据"""
                        col2.delete_many(filter={"file_id": _id})
                        doc['status'] = 0
                    else:
                        """成功"""
                        r = col1.insert_one(document=doc)
                        if isinstance(r, orm_module.InsertOneResult):
                            pass  # 成功
                        else:
                            mes['message'] = "保存导入记录失败"

            else:
                mes['message'] = "没有发现产品信息"
        return mes
示例#15
0
 def replace_code(cls, code_a: str, code_b: str) -> int:
     """
     条码替换,这个方法是给tcp服务端接收嵌入式请求用的
      嵌入式向服务器发出一条替换条码的信息,信息中顺序包含A和B两个条码. 意思是用B条码替换A条码的位置.
         如果 .A条码的status=1, print_id存在.且 B条码status=0, print_id存在.那么服务器将执行以下操作后返回1:
              1).设置A条码的status=0.B条码的status=1.
              2).如果A条码有parent_id,那么设置B.patent_id=A.parent_id
              3).搜寻数据库中,parent_id=A._id的条码,修改这些条码的parent_id=B._id
         如果 .A条码的status=1, print_id存在.且 B条码status=1, print_id存在.返回0.表示B条码已使用.
         如果 .A条码的status=1, print_id存在.且 B条码print_id不存在.返回2.表示B条码不可用.
         如果 .A条码的status=0, print_id存在.返回3.表示A条码无需替换
         如果 .A条码的print_id不存在.返回4.表示A条码未打印
         如果 .A条码不存在.返回5.表示A条码未打印
         如果程序执行出错.返回 -1
     :param code_a: 原来的条码
     :param code_b: 用于替换的条码
     :return:
     """
     db_client = orm_module.get_client()
     col = orm_module.get_conn(table_name=cls.get_table_name(),
                               db_client=db_client)
     w = orm_module.get_write_concern()
     with db_client.start_session(causal_consistency=True) as ses:
         with ses.start_transaction(write_concern=w):
             f = {"_id": code_a}
             r1 = col.find_one(filter=f, session=ses)
             if r1 is None:
                 resp = 5
             else:
                 if r1.get("print_id") is None:
                     resp = 4
                 else:
                     if r1.get("status", 0) == 0:
                         resp = 3
                     else:
                         r2 = col.find_one(filter={"_id": code_b})
                         if r2.get("print_id") is None:
                             resp = 2
                         else:
                             if r2.get("status", 0) == 1:
                                 resp = 0
                             else:
                                 f3 = {"_id": code_a}
                                 u3 = {"$set": {"status": 0}}
                                 f4 = {"_id": code_b}
                                 parent_id = r1.get("parent_id")
                                 if parent_id is None:
                                     u4 = {"$set": {"status": 1}}
                                 else:
                                     u4 = {
                                         "$set": {
                                             "status": 1,
                                             "parent_id": parent_id
                                         }
                                     }
                                 r3 = col.update_many(filter=f3, update=u3)
                                 r4 = col.update_many(filter=f4, update=u4)
                                 if r3 is None or r4 is None:
                                     resp = -1
                                 else:
                                     """更新code_a的children的parent_id"""
                                     f5 = {"parent_id": code_a}
                                     u5 = {"$set": {"parent_id": code_b}}
                                     col.update_many(filter=f5, update=u5)
                                     resp = 1
     return resp
示例#16
0
 def query_code(cls, code: str) -> int:
     """
     查询条码, 这个方法是给tcp服务端接收嵌入式请求用的
     如果条码信息status为0,且print_id不为空.表示条码信息可用.置此条码的status=1.返回1.
     如果码信息status为1,返回2, 表示这个条码已被使用
     如果码信息有查询到但是print_id为空.返回3. 条码没有打印过.
     如果码信息status为-1或者没有查询到对应的条码.返回4. 表示此条码无效.
     :param code:
     :return:
     """
     res = 4
     debug = False  # 当前保持测试模式
     begin = datetime.datetime.now()
     f = {"_id": code}
     if debug:
         """测试模式"""
         r = cls.find_one(filter_dict=f)
         if r is None:
             """没有查询到"""
             pass
         else:
             status = r.get("status", -1)
             print_id = r.get("print_id", None)
             if isinstance(print_id, ObjectId):
                 if status == 0:
                     res = 1
                 elif status == -1:
                     res = 3
                 else:
                     res = 2
             else:
                 """条码未打印"""
                 res = 3
     else:
         """生产模式"""
         db_client = orm_module.get_client()
         write_concern = orm_module.get_write_concern()
         col = orm_module.get_conn(table_name=cls.get_table_name(),
                                   db_client=db_client,
                                   write_concern=write_concern)
         with db_client.start_session(causal_consistency=True) as ses:
             with ses.start_transaction(write_concern=write_concern):
                 r = col.find_one(filter=f)
                 if r is None:
                     """没有查询到条码信息"""
                     pass
                 else:
                     status = r.get("status", -1)
                     print_id = r.get("print_id", None)
                     if isinstance(print_id, ObjectId):
                         if status == 0:
                             res = 1
                             """标记当前条码已被使用"""
                             u = {"$set": {"status": 1}}
                             return_document = orm_module.ReturnDocument.AFTER
                             r2 = col.find_one_and_update(
                                 filter=f,
                                 update=u,
                                 return_document=return_document)
                             if r2 is None:
                                 ms = "标记已用条码时出错,已用标记未写入, 条码: {}".format(
                                     code)
                                 logger.exception(msg=ms)
                             else:
                                 pass
                         elif status == -1:
                             res = 3
                         else:
                             res = 2
                     else:
                         """条码未打印"""
                         res = 3
         end = datetime.datetime.now()
         ms = (end - begin).total_seconds()
         print(ms)
     return res