def collects(): # 收藏商品或店铺 req_data = request.get_json() token = req_data.get('token') if check_token(token): user_id = get_token_user_id(token) clt_id = req_data.get('clt_id') type_id = req_data.get('type_id') if (clt_id and type_id) is not None: dao = BaseDao() save_data = { 'user_id': user_id, 'clt_id': clt_id, 'type_id': type_id } result = dao.save('u_clt', **save_data) if result: return jsonify({'code': 200, 'msg': '收藏成功!'}) else: return jsonify({'code': 400, 'msg': '查询数据库失败!'}) elif clt_id is not None and type_id is None: # 取消收藏 if clt_id: dao = GoodsDao() delet = dao.del_collect(clt_id) if delet: return jsonify({'code': 200, 'msg': '该收藏信息已删除!'}) else: return jsonify({'code': 400, 'msg': '删除失败!'}) else: return jsonify({'code': 400, 'msg': '未接收到需要删除的ID!'}) else: return jsonify({'code': 400, 'msg': '请上传商铺或商品ID和type类型!'}) else: return jsonify({'code': 400, 'msg': 'token验证失败!'})
def addCrawlerDataListener(num,totle): date = datetime.datetime.now() time = date.strftime("%H:%M") cdl = CrawlerDataListener() cdl.id = str(uuid.uuid4()) cdl.count = num cdl.time = time cdl.totle = totle cdl.createTime = date logging.info("addCrawlerDataListener BaseDao.add") BaseDao.add(cdl)
def delDbSource(db_source_ids): sql = None if len(db_source_ids) == 1: sql = "update db_source set del_flag=1 where id='%s'" % db_source_ids[0] elif len(db_source_ids) > 1: temp_ids = [] for id in db_source_ids: temp_ids.append(id.encode(encoding='utf-8')) sql = "update db_source set del_flag=1 where id IN%s" % str( tuple(temp_ids)) BaseDao.execute(sql)
def query_users(): """ 查询用户列表 :return: """ request_params = loadParams() if request_params.has_key('userId'): userId = request_params['userId'] if userId == '-1': data = BaseDao.query(User, type=1) else: data = BaseDao.query(User, text('id="' + userId + '"'), type=0) return parseResponse(0, {"userlist": data})
def upload_avator(): # 上传的头像字段为 img # 表单参数: token try: file: FileStorage = request.files.get('img', None) token = request.args.get('token', None) if all((bool(file), bool(token))): # 验证文件的类型, png/jpeg/jpg, 单张不能超过2M # content-type: image/png, image/jpeg if file.content_type in ('image/png', 'image/jpeg'): filename = uuid.uuid4().hex \ + os.path.splitext(file.filename)[-1] file.save(filename) # 上传到oss云服务器上 key = oss.upload_file(filename) os.remove(filename) # 删除临时文件 # token = request.args.get('token') # 将key写入到DB中 id = get_token_user_id(token) sql = "update yl_user set photo=(%s) where id=%s" db = BaseDao() db.query(sql, key, id) return jsonify({ 'code': 200, 'msg': '上传文件成功', 'file_key': key }) else: return jsonify({ 'code': 201, 'msg': '图片格式只支持png或jpeg' }) return jsonify({ 'code': 100, 'msg': 'POST请求参数必须有img和token' }) except: return jsonify({ "code":400, "msg":"更换头像失败" })
def updateTaskJob(taskJob): taskJobDb = Session.query(TaskJob).filter(TaskJob.id == taskJob.id).first() LoggerDao.addTaskJobLogger(taskJobDb, LoggerDao.LoggerType.MOD, content=u"更新任务", status=taskJobDb.status) return BaseDao.updateByPrimary(taskJob, TaskJob)
def getTaskList(page=Page(1, 10), userId=None, paramMap=None, orderBy=text('task_job.create_time desc'), parentId=None): # sql = None # if(userId==None): # sql=text(" del_flag=0") # else: # sql=text("create_user_id='" + userId + "' and del_flag=0") queryParam = [] if parentId == None: queryParam.append( text( "(ifnull(task_job.parent_id,'')='' or task_job.parent_id='-1')" )) else: queryParam.append(TaskJob.parentId == parentId) if userId != None and userId != "-1" and userId != "": queryParam.append(TaskJob.createUserId == userId) queryParam.append(TaskJob.delFlag == False) queryParam = BaseDao.initialQueryParam(paramMap or {}, TaskJob, queryParam) taskList = apply(Session.query(TaskJob).filter, tuple(queryParam)) if orderBy == None: orderBy = text('task_job.create_time desc') if parentId == None: taskList = taskList.order_by(orderBy).offset(page.offset).limit( page.limit) taskList = taskList.all() count = apply(Session.query(TaskJob).filter, tuple(queryParam)).count() return {"taskList": taskList, "count": count}
def queryTaskStatusByTaskJobId(): params = loadParams() taskJobId = params["taskJobId"] data = BaseDao.query(TaskStatusInfoField, text('task_job_id="'+taskJobId+'"')) json = stringify(data).encode("utf8") # WebSocket.sendMessage("{'action':'queryTaskStatusByTaskJobId','data':" + json + ",'returnCode':'0','returnMsg':'SUCCESS'}") return parseResponse(0, {"data": data})
def connect_test(o_num, status): print(o_num, status) success = BaseDao().update('o_detail', 'o_status', status, 'o_num', o_num) if success: return redirect('http://10.35.161.62:8888/admin/orders/orderdetail/') else: return ('操作数据库失败!')
def baselist(cls, sql): dao = BaseDao() with dao.db as c: c.execute(sql) items = c.fetchall() api_logger.info('select %s ok!' % sql) return items
def getLogList(id, pageNo=1, pageSize=10): # sql=text("select * from task_job_history where task_job_id='%s' and del_flag=0 order by create_time desc limit"%(taskJobId)) return BaseDao.getPageResult( page=Page(pageNo, pageSize), paramMap={"taskJobHistoryId": id}, clzz=[LogInfo, JobTemplate], join=[JobTemplate, JobTemplate.id == LogInfo.jobTemplateId])
def update(self, userInfo): sql = """ UPDATE `old_blockchain`.`user_info` SET `publicKey` = %s, `privateKey` = %s, `address` = %s WHERE (ISNULL(`publicKey`)) AND (ISNULL(`privateKey`)) AND (ISNULL(`address`)) AND (`userId` = %s) AND ( `customerName` = %s ) LIMIT 1; """ array = [] array.append(userInfo.publicKey) array.append(userInfo.privateKey) array.append(userInfo.address) array.append(userInfo.userId) array.append(userInfo.customerName) try: baseDao = BaseDao.BaseDao() result = baseDao.executeGetAllSql(sql, array) print(result) return result except Exception as e: print(e)
def loadTemplate(page=Page(1,10),paramMap={},userId=None,orderBy=text(" job_template.create_time desc "),parentId=None): queryParam = [] # if parentId == None: # queryParam.append(text("(ifnull(job_template.parent_id,'')='' or job_template.parent_id='-1')")) # else: # queryParam.append(JobTemplate.parentId == parentId) if parentId is not None: queryParam.append(JobTemplate.parentId == parentId) if userId != None and userId != "-1" and userId != "": queryParam.append(TaskJob.createUserId == userId) if paramMap and paramMap.has_key("pageNo") and paramMap.has_key("pageSize"): page = Page(paramMap["pageNo"],paramMap["pageSize"]) queryParam.append(JobTemplate.delFlag == False) queryParam = BaseDao.initialQueryParam(paramMap or {}, JobTemplate, queryParam) filterQuery=Session.query(JobTemplate).filter taskList = apply(filterQuery, tuple(queryParam)) if orderBy == None: orderBy = text('task_job.create_time desc') if (parentId == None or parentId == '-1') and page!=None: taskList = taskList.order_by(orderBy).offset(page.offset).limit(page.limit) taskList = taskList.all() count = apply(filterQuery, tuple(queryParam)).count() # if paramMap.has_key('action'): # action = paramMap['action'] # if action == '1': # jobtemp = taskList[0] # jobtemplist = queryAllTempByTaskJob(jobtemp)#递归查询子模板 # if jobtemplist: # taskList.extend(jobtemplist) # count = len(taskList) return {"jobTemplateList": taskList, "count": count}
def get_result(table_name, field_name, field_id): sql = """select %s from %s where id='%s'""" % (field_name, table_name, field_id) result = BaseDao.execute(sql) if result and len(result.cursor._rows) > 0: return result.cursor._rows[0][0] return False
def updateAsset(self, usertAssetObject): sql = """ UPDATE `old_blockchain`.`user_asset` SET `status` = %s WHERE userAddress=%s and `assetAddress` = %s LIMIT 1; """ array = [] array.append(usertAssetObject.status) array.append(usertAssetObject.userAddress) array.append(usertAssetObject.assetAddress) try: baseDao = BaseDao.BaseDao() result = baseDao.executeGetAllSql(sql, array) print(result) return result except Exception as e: print(e) return
def getUserAccountCheckFromSql(self, userInfo): sql = """ SELECT userAddress, sum(money), GROUP_CONCAT( if ( status=0 and assetAddress!="",assetAddress,null) ) FROM user_asset LEFT JOIN user_info ON user_asset.userAddress = user_info.address WHERE userAddress=%s AND createTime > '2019-01-04 00:00:00' GROUP BY userAddress ORDER BY createTime DESC """ array = [] param = [] param.append(userInfo.address) print(sql) try: baseDao = BaseDao.BaseDao() result = baseDao.execteGetOneSql(sql, param) userAccountCheck = UserAccountCheck.UserAccountCheck() userAccountCheck.address = result[0] userAccountCheck.money = result[1] userAccountCheck.assetAddress = result[2] return userAccountCheck except Exception as e: print(e) pass
def getTaskList(page, userId=None, paramMap=None, orderBy=text('search_task_job.create_time desc'), parentId=None, status=None): queryParam = [] # if parentId == None: # queryParam.append(text("(ifnull(task_job.parent_id,'')='' or task_job.parent_id='-1')")) # else: # queryParam.append(SearchTaskJob.childIds == parentId) if userId != None and userId != "-1" and userId != "": queryParam.append(SearchTaskJob.createUserId == userId) queryParam.append(SearchTaskJob.delFlag == False) queryParam = BaseDao.initialQueryParam(paramMap or {}, SearchTaskJob, queryParam) taskList = apply(Session.query(SearchTaskJob).filter, tuple(queryParam)) if orderBy == None: orderBy = text('p_search_task_job.create_time desc') if status != None: taskList = taskList.filter(SearchTaskJob.status == status) if parentId == None: taskList = taskList.order_by(orderBy).offset(page.offset).limit( page.limit) taskList = taskList.all() count = apply(Session.query(SearchTaskJob).filter, tuple(queryParam)).count() return {"taskList": taskList, "count": count}
def setNewBassByCustomerName(self,customerName): headers = { 'Accept': "application/json", 'Content-Type': "application/json;charset=UTF-8" } # 字典转化为json try: baseDao = BaseDao.BaseDao() config = Config.Config() config.customerName = customerName configDao = ConfigDao() config = configDao.get(config) config = config.__dict__ configJson = json.dumps(config) # 打印字典 print(config) url = host + 'configProperties/add' data = configJson headers = headers result = baseDao.safeRequests(url, data, headers, "") if result.status_code == 200: jsonResult = result.json() if (jsonResult['retcode'] != 0): raise Exception("请求错误,请查看信息:", jsonResult) if jsonResult['data'] != '': return jsonResult['data'] else: print(Exception("错误信息", result.json())) except Exception as e: print(e)
def get_img_url(): try: token = request.args.get('token') id = get_token_user_id(token) sql = "select photo from yl_user where id=%s" db = BaseDao() key = db.query(sql, id)[0]['photo'] img_url = oss.get_small_url(key) return jsonify({ "code": 400, 'url': img_url }) except: return jsonify({ "code":400, "msg":"获取失败" })
def countObj(userId, clazz, paramMap): queryParam = [] queryParam.append(text("(ifnull(parent_id,'')='' or parent_id='-1')")) if userId != None and userId != "-1" and userId != "": queryParam.append(TaskJob.createUserId == userId) queryParam.append(clazz.delFlag == False) queryParam = BaseDao.initialQueryParam(paramMap, clazz, queryParam) return apply(Session.query(clazz.id).filter, tuple(queryParam)).count()
def updateDbSource(dbSource): return { "result": { "code": BaseDao.updateByPrimary(dbSource, DbSource), "databaseId": str(dbSource.id), "object": dbSource } }
def isTableExist(self,tablename): sql = """ SHOW TABLES LIKE '%s' """ % tablename rs =BaseDao.execute(sql) if(rs.rowcount == 1): return True else: return False
def addTaskJob(taskJob): taskJob.id = uuid.uuid1() createTime = taskJob.createTime tableName = taskJob.tableName taskJob.status = TaskStatus.WAITING if createTime == None: createTime = datetime.now() elif (type(createTime) == "string"): createTime = datetime.strptime(createTime, "%Y-%m-%d %H:%M").date() timeStr = createTime.strftime("%Y%m%d%H%M%S") if (tableName == None): tableName = "taskJob" taskJob.tableName = "%s_%s" % (tableName, timeStr) LoggerDao.addTaskJobLogger(taskJob, LoggerDao.LoggerType.ADD, content=u"创建任务", status=taskJob.status) BaseDao.add(taskJob)
def delete_order(self, p_num): dao = BaseDao() sql1 = "select id from tn_user where p_num=%s" % p_num with dao.db as c: c.execute(sql1) user_id = c.fetchone()[0]["id"] sql2 = "delete tn_order from tn_order,tn_user where tn_order.user_id=%s" % user_id with dao.db as c: c.execute(sql2)
def queryDbSourceList(paramMap): queryParam = [] queryParam.append(DbSource.delFlag == 0) queryParam = BaseDao.initialQueryParam(paramMap or {}, DbSource, queryParam) dbSourceList = apply(Session.query(DbSource).filter, tuple(queryParam)) sortlist = dbSourceList.order_by(DbSource.createTime).all() sortlist.reverse() newSortDbSourcelist = sortlist return newSortDbSourcelist
def c_presentation(self,course): # 介绍页 clist = ['id', 'name', 'img_url','description','degree', 'course_time', 'study_num', 'course_score','youneed_know', 'teacher_tell', 'teacher_id'] # 将字符串类型的列表数据转换为列表类型 course['youneed_know'],course['teacher_tell'] = eval(course['youneed_know']),eval(course['teacher_tell']) precourse = {k:course[k] for k in clist} # 对返回数据按前端需求筛选 t_info = BaseDao().list('teachers',('t_name','t_job','t_pic'), where='id',args=precourse['teacher_id'])[0] return {'precourse':precourse,'t_info':t_info}
def taskJobReTemplate(taskJobId,templates): oldtaskjobtemp = Session.query(TaskJobReTemplate).filter(TaskJobReTemplate.taskJobId==taskJobId).all() for oldemp in oldtaskjobtemp: oldemp.delFlag = True for template in templates: taskJobReT=Session.query(TaskJobReTemplate).filter(TaskJobReTemplate.taskJobId==taskJobId,TaskJobReTemplate.jobTemplateId==template.get("id")).first() if taskJobReT==None: taskJobReTemplate=TaskJobReTemplate() taskJobReTemplate.jobTemplateId=template.get("id") taskJobReTemplate.fieldIds=template.get("fieldIds") taskJobReTemplate.taskJobId=taskJobId taskJobReTemplate.delFlag=False Session.add(taskJobReTemplate) else: taskJobReT.fieldIds=template.get("fieldIds") taskJobReT.delFlag = False BaseDao.updateByPrimary(taskJobReT,TaskJobReTemplate) Session.flush() Session.commit()
def queryAllTempByTaskField(taskJobId): taskJobReTemplate = Session.query(TaskJobReTemplate).filter(TaskJobReTemplate.taskJobId == taskJobId).first() result = None if taskJobReTemplate is not None: jobTemplate = Session.query(JobTemplate).filter(JobTemplate.id == taskJobReTemplate.jobTemplateId).first() jobTemplate1 = Session.query(JobTemplate).filter(JobTemplate.parentId == jobTemplate.id).first() sql = "select w1.wechatImage,w1.detailURL,w3.title,w3.time,w3.organization from %s w1 join %s w3 on w1.id=w3.parent_id" % (jobTemplate.tableName,jobTemplate1.tableName) result = BaseDao.execute(sql) if result and len(result.cursor._rows) > 0: result= result.cursor._rows return {'result':result,'count':[[len(result)]]}
def addDbSource(dbSource): id = uuid.uuid1() dbSource.id = id dbSource.createTime = datetime.now() dbSource.delFlag = False return { "result": { "code": BaseDao.add(dbSource), "databaseId": str(id), "object": dbSource } }
def elegant_city(self): dao = BaseDao() city_list = ["当季精选", "海岛精选", "热门目的地"] city_dict = {} for i in range(len(city_list)): sql = "select name,img from cities where is_popular='%s'" % ( str(i + 2), ) with dao.db as c: c.execute(sql) items = c.fetchall() city_dict[city_list[i]] = items return city_dict