def api_manager_manageFoodTruck(): if not hasattr(current_user, 'roles') or 'Manager' not in current_user.roles: return ErrorModel('No Privilege: Must be Manager').json() username = current_user.id data = json.loads(request.args.get('data') or '{}') foodTruckName = data.get('foodTruckName') or '' stationName = data.get('stationName') or '' staffCount = data.get('staffCount') low = None high = None if staffCount: low = staffCount.get('low') high = staffCount.get('high') hasRemainingCapacity = data.get('hasRemainingCapacity') if hasRemainingCapacity is None: hasRemainingCapacity = False callProcedure('mn_filter_foodTruck', [ username, foodTruckName, stationName, low, high, hasRemainingCapacity ]) ret = {} ret['table'] = select('mn_filter_foodTruck_result', '1 = 1', '*')['data'] callProcedure('mn_get_station', [username]) ret['stationList'] = select('mn_get_station_result', '1 = 1', '*')['data'] return SuccessModel(ret).json()
def api_manager_getAvailableStaff(): if not hasattr(current_user, 'roles') or 'Manager' not in current_user.roles: return ErrorModel('No Privilege: Must be Manager').json() username = current_user.id callProcedure('mn_view_foodTruck_available_staff', [username, None]) data = select('mn_view_foodTruck_available_staff_result', '1 = 1', '*')['data'] urlData = json.loads(request.args.get('data') or '{}') foodTruckName = urlData.get('foodTruckName') if foodTruckName: callProcedure('mn_view_foodTruck_staff', [foodTruckName]) newData = select('mn_view_foodTruck_staff_result', '1 = 1', '*')['data'] data = tuple(list(data) + list(newData)) for obj in data: staffUsername = mysqlDB.select( 'SELECT username from Staff NATURAL JOIN `User` WHERE CONCAT(firstName, " ", lastName) = %s', (obj.get('availableStaff') or obj.get('assignedStaff')))['data'][0]['username'] obj['username'] = staffUsername return SuccessModel(data).json()
def get_week_caps(): today = datetime.datetime.now().strftime("%Y%m%d") # 获取日期区间 date_range = get_date_range(today, delta_day=7) rows = [] row_title = ["日期", "SCP", "SCPAS", "CATAS", "短号短信下发量", "短号彩信下发量"] rows.append(row_title) for date in date_range: caps_sql = "select date,scp_caps,scpas_caps,catas_caps from caps where date = {}".format( date) vss_sql = "select vss_total,mms_total from vss where date = {}".format( date) # 提取一周的caps数据 caps_result = db.select(caps_sql) # 提取一周的短号短信数据 vss_result = db.select(vss_sql) try: caps_row = list(caps_result[0]) except IndexError: caps_row = [date, "", "", ""] try: vss_row = list(vss_result[0]) except IndexError: vss_row = ["", ""] row = caps_row + vss_row rows.append(row) caps_html = parseHtml(rows, title="周报数据", return_all=False) return caps_html
def fileDown(id): if not db.select(id): return 'no' else: result = db.select(id)[0] return send_file(result[2], mimetype=result[3], as_attachment=True, attachment_filename=result[1])
def api_customer_currentInformation(): if not hasattr(current_user, 'roles') or 'Customer' not in current_user.roles: return ErrorModel('No Privilege: Must be Customer').json() username = current_user.id ret = {} callProcedure('cus_current_information_basic', [username]) ret['basic'] = select('cus_current_information_basic_result', '1 = 1', '*')['data'] cleanDecimal(ret['basic'], 'balance', 2) callProcedure('cus_current_information_foodTruck', [username]) ret['foodTrucks'] = select('cus_current_information_foodTruck_result', '1 = 1', '*')['data'] return SuccessModel(ret).json()
def getUserRoles(username): res = select('login_classifier', '`username` = "{}"'.format(username), '`userType`') if len(res['data']) > 0: return res['data'][0]['userType'].split('-') else: return []
def api_customer_explore(): if not hasattr(current_user, 'roles') or 'Customer' not in current_user.roles: return ErrorModel('No Privilege: Must be Customer').json() data = json.loads(request.args.get('data') or '{}') buildingName = data.get('buildingName') stationName = data.get('stationName') buildingTag = data.get('buildingTag') foodTruckName = data.get('foodTruckName') food = data.get('food') ret = {} callProcedure( 'cus_filter_explore', [buildingName, stationName, buildingTag, foodTruckName, food]) ret['table'] = select('cus_filter_explore_result', '1 = 1', '*')['data'] ret['stationList'] = mysqlDB.select('SELECT stationName from Station;', ())['data'] ret['buildingList'] = mysqlDB.select('SELECT buildingName from Station;', ())['data'] return SuccessModel(ret).json()
def read(id,uid): isbigint(id) isbigint(uid) results = db.select('notes',where='id=$id and userid=$uid',vars=locals(), _test=is_debug) if not results: return False return results[0]
def get_patent_label_info(self): """ 获取 label_patent_industry 表中原始的专利-行业对应关系,并转化数据格式为: { patent_id: {label1, label2,...}, ... } :return: """ sql = """ select lp.patent_id, lp.industry_title from label_patent_industry lp where used = 1 """ data = db.select(sql) patent_id__info = {} for dic in data: if dic["patent_id"] in patent_id__info.keys(): patent_id__info[dic["patent_id"]].add(dic["industry_title"]) else: patent_id__info[dic["patent_id"]] = {dic["industry_title"]} patent_id_set = set() for dic in data: if dic["patent_id"] not in patent_id_set: patent_id_set.add(dic["patent_id"]) self.patent_id_list = list(patent_id_set) self.get_patent_vec_by_id_list() return patent_id__info
def api_admin_manageFood(): if not hasattr(current_user, 'roles') or 'Admin' not in current_user.roles: return ErrorModel('No Privilege: Must be Admin').json() data = json.loads(request.args.get('data') or '{}') foodName = data.get('name') sortBy = data.get('sortBy') isAsc = data.get('asc') if sortBy is not None: if isAsc: isAsc = 'ASC' else: isAsc = 'DESC' ret = {} callProcedure('ad_filter_food', [foodName, sortBy, isAsc]) result = select('ad_filter_food_result', '1 = 1', '*') if not result['okay']: return ErrorModel({'errno': 0}).json() ret['table'] = result['data'] result = mysqlDB.select('SELECT * FROM Food;', ()) if not result['okay']: return ErrorModel({'errno': 1}).json() ret['foodList'] = result['data'] return SuccessModel(ret).json()
def opened(uid): return list( db.select('notes', what='id,summary', where='userid=$uid and openorder>0', order="openorder", vars=locals(), _test=is_debug))
def group(gid): return list( db.select('notes', what='id,summary', where='groupid=$gid and status=1', order="openorder", vars=locals(), _test=is_debug))
def filter(**fields): filters = ' and '.join(['%s=%s' % (key, fields[key]) for key in fields]) return list( db.select('notes', what='id,summary', where=filters, order="lastmodifieddate desc", _test=is_debug))
def api_admin_getAvailableBuilding(): if not hasattr(current_user, 'roles') or 'Admin' not in current_user.roles: return ErrorModel('No Privilege: Must be Admin').json() callProcedure('ad_get_available_building', []) return SuccessModel( select('ad_get_available_building_result', '1 = 1', '*')['data']).json()
def api_admin_getStation(): if not hasattr(current_user, 'roles') or 'Admin' not in current_user.roles: return ErrorModel('No Privilege: Must be Admin').json() data = json.loads(request.args.get('data') or '{}') buildingName = data.get('buildingName') res = mysqlDB.select( 'SELECT `stationName` FROM `Station` WHERE `buildingName` = %s;', (buildingName))['data'] if len(res) == 0: return ErrorModel({'errno': 1}).json() stationName = res[0]['stationName'] callProcedure('ad_view_station', [stationName]) res = select('ad_view_station_result', '1 = 1', '*') return SuccessModel( select('ad_view_station_result', '1 = 1', '*')['data'][0]).json()
def api_admin_getBuilding(): if not hasattr(current_user, 'roles') or 'Admin' not in current_user.roles: return ErrorModel('No Privilege: Must be Admin').json() data = json.loads(request.args.get('data') or '{}') buildingName = data.get('buildingName') if buildingName: res = {} callProcedure('ad_view_building_general', [buildingName]) res['general'] = select('ad_view_building_general_result', '1 = 1', '*')['data'][0] callProcedure('ad_view_building_tags', [buildingName]) res['tags'] = select('ad_view_building_tags_result', '1 = 1', '*')['data'] return SuccessModel(res).json() return ErrorModel({'errno': 0}).json()
def read(id, uid): isbigint(id) isbigint(uid) results = db.select('notes', where='id=$id and userid=$uid', vars=locals(), _test=is_debug) if not results: return False return results[0]
def login(email,password): users = db.select('users',where='email=$email',vars=locals(), _test=is_debug) if not users: return False user = users[0] if user.password != password: return False return user
def api_customer_foodTruckMenu(): if not hasattr(current_user, 'roles') or 'Customer' not in current_user.roles: return ErrorModel('No Privilege: Must be Customer').json() data = json.loads(request.args.get('data') or '{}') foodTruck = data.get('foodTruck') callProcedure('mn_view_foodTruck_menu', [foodTruck]) ret = select('mn_view_foodTruck_menu_result', '1 = 1', 'foodName, price')['data'] cleanDecimal(ret, 'price', 2) return SuccessModel(ret).json()
def api_customer_orderHistory(): if not hasattr(current_user, 'roles') or 'Customer' not in current_user.roles: return ErrorModel('No Privilege: Must be Customer').json() username = current_user.id callProcedure('cus_order_history', [username]) ret = select('cus_order_history_result', '1 = 1', '*')['data'] cleanDecimal(ret, 'orderTotal', 2) formatDate(ret, 'date') formatOrderID(ret, 'orderID') return SuccessModel(ret).json()
def api_manager_foodTruckSummary(): if not hasattr(current_user, 'roles') or 'Manager' not in current_user.roles: return ErrorModel('No Privilege: Must be Manager').json() urlData = json.loads(request.args.get('data') or '{}') username = current_user.id foodTruckName = urlData.get('foodTruckName') stationName = urlData.get('stationName') dateRange = urlData.get('dateRange') dateFrom = None dateTo = None if dateRange: dateFrom = dateRange.get('dateFrom') dateTo = dateRange.get('dateTo') sortBy = urlData.get('sortBy') asc = urlData.get('asc') if sortBy: if not (asc == True): asc = 'DESC' else: asc = 'ASC' else: asc = None ret = {} callProcedure( 'mn_filter_summary', [username, foodTruckName, stationName, dateFrom, dateTo, sortBy, asc]) ret['table'] = select('mn_filter_summary_result', '1 = 1', '*')['data'] cleanDecimal(ret['table'], 'totalRevenue', 2) callProcedure('mn_get_station', [username]) ret['stationList'] = select('mn_get_station_result', '1 = 1', '*')['data'] return SuccessModel(ret).json()
def get_data_by_node(cluters): yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d") result = {} for x in cluters: cluter = x.split('-')[1] sql = "select max_cpu from as_pfmc where cluste='{}' and date='{}'".format( cluter, yesterday) data = db.select(sql) if data: result[x] = data[0][0] else: result[x] = 0 return result
def api_admin_manageBuildingAndStation(): if not hasattr(current_user, 'roles') or 'Admin' not in current_user.roles: return ErrorModel('No Privilege: Must be Admin').json() data = json.loads(request.args.get('data') or '{}') buildingName = data.get('buildingName') buildingTag = data.get('buildingTag') stationName = data.get('stationName') capacity = data.get('capacity') low = None high = None if capacity: low = capacity.get('low') high = capacity.get('high') callProcedure('ad_filter_building_station', [buildingName, buildingTag, stationName, low, high]) ret = {} ret['table'] = select('ad_filter_building_station_result', '1 = 1', '*')['data'] ret['buildingList'] = select('Building', '1 = 1', 'buildingName')['data'] ret['stationList'] = select('Station', '1 = 1', 'stationName')['data'] cleanDecimal(ret['table'], 'capacity', 0) return SuccessModel(ret).json()
def api_manager_summaryDetail(): if not hasattr(current_user, 'roles') or 'Manager' not in current_user.roles: return ErrorModel('No Privilege: Must be Manager').json() urlData = json.loads(request.args.get('data') or '{}') foodTruckName = urlData.get('foodTruckName') username = current_user.id callProcedure('mn_summary_detail', [username, foodTruckName]) ret = select('mn_summary_detail_result', '1 = 1', '*')['data'] cleanDecimal(ret, 'totalPurchase', 2) formatDate(ret, 'date') return SuccessModel(ret).json()
def get_data(dates, clustes, data_type): row_title = clustes[:] row_title.insert(0, '时间') rows = [] rows.append(row_title) for date in dates: row = [] row.append(date) for cluste in clustes: sql = "select {} from as_pfmc where date={} and cluste='{}'".format( data_type, date, cluste) result = db.select(sql) try: row.append(result[0][0]) except IndexError: row.append(None) rows.append(row) return rows
def api_user_login(): data = request.get_json() username = data.get('username') password = data.get('password') if username and password: callProcedure('login', [username, password]) if checkExist('login_result', '1 = 1', ()): username = select('login_result', '1 = 1', '`username`')['data'][0]['username'] user = User.get(username) if user is None: user = User(username, getUserRoles(username)) login_user(user) resp = make_response(SuccessModel().json()) resp.set_cookie('user-roles', json.dumps(user.roles)) return resp return ErrorModel('Login Failed').json()
def api_manager_getAvailableStation(): if not hasattr(current_user, 'roles') or 'Manager' not in current_user.roles: return ErrorModel('No Privilege: Must be Manager').json() data = json.loads(request.args.get('data') or '{}') foodTruckName = data.get('foodTruckName') callProcedure('mn_get_available_station', [foodTruckName]) data = select('mn_get_available_station_result', '1 = 1', '*')['data'] if foodTruckName: data = tuple( list( mysqlDB.select( 'SELECT stationName FROM FoodTruck WHERE foodTruckName = %s;', (foodTruckName))['data']) + list(data)) return SuccessModel(data).json()
def get_patent_vec_by_id_list(self): """ 根据专利id获取专利的向量 :param patent_id_list: :return: """ sql = """ select patent_id, vec from patent_vec where patent_id in ( """ for patent_id in self.patent_id_list: sql += str(patent_id) + "," sql = sql[0:-1] sql += ")" data = db.select(sql) for dic in data: if dic["patent_id"] not in self.patent_id_vec_dict.keys(): self.patent_id_vec_dict[dic["patent_id"]] = eval(dic["vec"])
def upload(): file = request.files['file'] if file and allowed_file(file.filename): filename = randFileName(file.filename) fullPath = os.path.join(savePath(), filename) file.save(fullPath) key = '' while True: key = encode(int("{}{}".format(curNum(), ranNum()))) if not db.select(key): break db.insert({ 'id': key, 'fileName': file.filename, 'realPath': fullPath, 'mime': file.content_type, 'fileSize': os.stat(fullPath).st_size }) return key
def construct_label_list(self): """ 获取标签列表,并将标签列表写入文件,形如: ------------------------------------------------------------------ | 互联互通 产品功耗 ... ------------------------------------------------------------------ :return: """ sql = """ select industry_title from label_patent_industry where used = 1 GROUP BY industry_title """ data = db.select(sql) self.label_list = [dic["industry_title"] for dic in data] self.write_label_list_to_file()
def api_user_regiser(): data = request.get_json() username = data.get('username') password = data.get('password') firstName = data.get('firstName') lastName = data.get('lastName') email = data.get('email') balance = data.get('balance') employeeType = data.get('employeeType') # call register procedure callProcedure('register', [ username, email, firstName, lastName, password, balance, employeeType ]) roles = getUserRoles(username) err_no = (select('err_msg', '1 = 1', '`err`')['data'][0]['err']) if err_no == 0: if not mysqlDB.tryCommit(): return ErrorModel({'errno': 3}).json() return SuccessModel({'roles': roles}).json() return ErrorModel({'errno': int(err_no - 1)}).json()
def auth(uid,secretkey): users = db.select('users',where="id=$uid and secretkey=$secretkey",vars=locals(), _test=is_debug) return users
def filter(**fields): filters = ' and '.join(['%s=%s' % (key,fields[key]) for key in fields]) filters += ' and status=1' return list(db.select('groups', what='id,name,notescount', where=filters, order = 'id', _test=is_debug))
def filter(**fields): filters = ' and '.join(['%s=%s' % (key,fields[key]) for key in fields]) return list(db.select('notes', what='id,summary', where=filters, order="lastmodifieddate desc", _test=is_debug))
def read(id,uid): results = db.select('groups',where='id=$id and userid=$uid',vars=locals(), _test=is_debug) if not results: return False return results[0]
def group(gid): return list(db.select('notes', what='id,summary', where='groupid=$gid and status=1', order="openorder",vars=locals(), _test=is_debug))
def deleted(uid): return list(db.select('notes', what='id,summary', where='userid=$uid and status=0', order="openorder",vars=locals(), _test=is_debug))