def user_info_by_username(username, showfunc=showo_inDict): query = Query("_User") query.include("sioeyeInfo") query.include("sioeyeInfo.avatar") query.equal_to('username', username) user = query.first() user_info = user.get("sioeyeInfo") user_avatar = user_info.get("avatar") (u, ui, ua) = (None, None, None) if user is not None: print "=== user ===" showfunc(user) u = user if user_info is not None: print "=== user info ===" showfunc(user_info) ui = user_info if user_avatar is not None: print "=== user avatar===" showfunc(user_avatar) ua = user_avatar # print "%s: %s" % (username, user_info.get("sioeyeId")) print "------------ next ------------" return u, ui, ua
def user_by_username(username): query = Query("_User") query.equal_to('username', username) user = query.first() # if user is not None: # showo_inDict(user) return user
def see_record_num(period_label_dic): valid_num=0 valid_period=[] ####init connect_db() #####get all UserSensor = Object.extend('UserSensor') query = Query(UserSensor) # for label,periods in period_label_dic.items(): for period in periods: stamp_range=generate_stamp(period) # query.equal_to("deviceId",device).not_equal_to("events",None).\ equal_to("sensorType",sensor).\ less_than("timestamp", stamp_range[1]).greater_than("timestamp",stamp_range[0]) #equal_to("motion",class_type).\ if query.count()>10: valid='valid' valid_num+=query.count() valid_period.append([label,period]) else:valid='not valid' print label,period,'count',query.count(),valid print 'total valid record:',valid_num
def is_exit(str): global category query = Query('Reading') query.equal_to('title', str) query.equal_to('category', category) querys = query.find() return len(querys) > 0
def changeServerFileName(position,newName): query = Query(allPictures) query.equal_to('position', position) pictures = query.find() pictureSelect = pictures[0] pictureSelect.set('image_src', newName) pictureSelect.save()
def json_index(index): print 'get result from index',index try: query =Query(DeviceKey) query.equal_to('index',index) devicekey=query.first() key=devicekey.id lat = devicekey.get('lat') lng = devicekey.get('lng') except: return jsonify(error='invalid index') try: data=get_latest(key) except: return jsonify(error='no data',key=key) ch2o = data.get('ch2o') if ch2o ==65535: ch2o=0 ch2o =round(ch2o*1.32/1000,2) data.set('ch2o',ch2o) tem =round(data.get('t')/10.0-40.0,1) hum =data.get('h') nosie =data.get('noise') pm =data.get('pm') ch2o =data.get('ch2o') return jsonify(key = key,tem=tem,hum=hum,noise=nosie,pm=pm,ch2o=ch2o,createdAt=data.created_at,index=index,heze_rate= 80,tem_od=23.3,hum_od=12,pm_od=100,longitude=lng,latitude=lat)
def queryOneDataByPosition(position): query = Query(allPictures) query.equal_to('position', position) pictures = query.find() if len(pictures) > 0: return pictures[0].get('image_src') return ""
def result_index(index): print 'get result from index',index try: query =Query(DeviceKey) query.equal_to('index',index) devicekey=query.first() device_name = devicekey.get('name_cn') key=devicekey.id except: return jsonify(error='invalid index') try: data=get_latest(key) hour=data.created_at.hour+8 ch2o = data.get('ch2o') if ch2o ==65535: ch2o=0 ch2o =round(ch2o*1.32/1000,2) data.set('ch2o',ch2o) except: return jsonify(error='invalid key') try: local_time=utc2local(data.created_at) except: print 'local time change error' local_time = data.created_a #pm =average_pm(24,key) pm =min_pm(key) noise = min_noise(key) return render_template('result.html', esp_test=data,local_time=local_time,pm=pm,noise=noise,index=index,device_name = device_name)
def get_sport_data_dict(self, app_table=APPLICATION_CLASS, field_name="app", kind=None): try: field = "sport" app = self.get_the_app(kind=kind) static_info_table = STATIC_INFO_TABLE DbTable = Object.extend(static_info_table) query = Query(DbTable) query.equal_to(field_name, app) query.exists(field) result_list = query.find() length = len(result_list) if length == 0: print "error: application not exists in table %s" % (str(static_info_table)) return {} elif length > 1: print "error: multi application exists in table %s" % (str(static_info_table)) # return 0 app_static_info = result_list[0] data_dict = app_static_info.get(field) # return age_and_gender_dict except LeanCloudError, e: raise e
def _latest_convs_by_creater(username): cq = Query("_Conversation") creater = user_by_username(username) cq.equal_to("c", creater.id) cq.descending("createdAt") convs = cq.find() return convs
def traverse_point(subject, point_type, items, parent=None, prefix=''): for i, el in enumerate(items): # print prefix, i, el.label.a.string, is_leaf = el.ul is None origin_url = el.label.a['href'] data = { 'origin_url': origin_url, 'is_leaf': is_leaf, 'type': point_type, 'order': i, 'subject': subject, 'text': el.label.a.string } query = Query(Point) query.equal_to('origin_url', origin_url) try: point = query.first() except LeanCloudError: point = Point(**data) else: for k, v in data.items(): point.set(k, v) if parent: point.set('parent', parent) point.save() if not is_leaf: traverse_point(subject, point_type, el.ul, point, '--' + prefix)
def get_occupation_data_dict(table_name='WeightedStaticInfo',tracker_list=None): try: field_name = 'user' DBTable = Object.extend(table_name) gender_type_list =['man','woman'] age_type_list = ['16down','16to35','35to55','55up'] dataDict ={gender_type:{age_type:0 for age_type in age_type_list} for gender_type in gender_type_list} # new_data_dict = {key:[0 for i in range(4)] for key in dataDict.keys()} total_count = len(tracker_list) for index, tracker in enumerate(tracker_list): query = Query(DBTable) query.equal_to(field_name,tracker) query.select('age','gender') result_list = query.find() length = len(result_list) if length!=1: print 'error: the length of result_list is %s with index: %s with tracker_objectId: %s' %(str(length),str(index),tracker.id) if length >=1: result = result_list[0] else: continue print 'index: %s gender: %s age: %s ' %(str(index),str(result.get('gender')),str(result.get('age'))) gender = 'man' if result.get('gender') >0 else 'woman' age_info_dict= result.get('age') dataDict[gender][age_info_dict.keys()[0]] += 1 # dataDict ={'man' if staticInfo.get('gender') >0 else 'woman':dataDict['man' if staticInfo.get('gender') >0 else 'woman'][staticInfo.get('age').keys()[0]] +=1 for staticInfo in staticInfoList} # for index ,age_type in enumerate(age_type_list): # for gender_type in dataDict.keys(): # new_data_dict[gender_type][index] = dataDict[gender_type][age_type] known_count = sum(dataDict['man'].values())+sum(dataDict['woman'].values()) dataDict['unknown'] = total_count -known_count except LeanCloudError, e: raise e
def sync_local(): files = [ f for f in os.listdir(SYNC_DIR) if os.path.isfile(os.path.join(SYNC_DIR, f)) ] for f in files: fileName = f filePath = os.path.join(SYNC_DIR, f) if not (fileName.endswith('.jpeg') or fileName.endswith('.png') or fileName.endswith('.jpeg')): continue print('\n' + filePath) # 计算照片模糊 Hash 值 im = Image.open(filePath) hash_meta = dhash(im) # 查询 LeanCloud,从本地移除重复照片 query = Query(Photo) query.equal_to('dhash', hash_meta) results = query.find() if len(results) != 0: print "duplicate: (local=%s, leancloud=%s)" % (fileName, results[0].get('url')) os.rename(filePath, os.path.join(SYNC_DIR_DUPLICATED, fileName)) continue # keep original file name for use in case originFileName = fileName millis = int(round(time.time() * 1000)) hashFileName = hashids.encode(millis) + fileName[fileName.rfind('.')+1 :] os.rename(filePath, os.path.join(SYNC_DIR, hashFileName)) # 解析 meta 信息 meta = parseImageMeta(hashFileName, im) # 保存链接与 meta 到 LeanCloud avosPhoto = savePhoto(meta)
def create_demo_application(table_name='DemoApplication'): all_real_app = get_all_real_applications() DbTable = Object.extend(table_name) for index, app in enumerate(all_real_app): db_table = DbTable() relation = app.relation('tracker') # query = Query(DbTable) query = relation.query() user_list = query.find() relation = db_table.relation('tracker') for user in user_list: ADbTable = Object.extend('Tracker') query = Query(ADbTable) query.equal_to('objectId',user.id) result_list = query.find() if result_list: tracker = result_list[0] relation.add(tracker) else: print 'tracker not exists and objectId is: %s' %(str(user.id)) db_table.set('app_name',app.get('app_name')) db_table.set('origin_name',app.get('name')) db_table.save()
def is_exit(str): global category global type_name query = Query('Reading') query.equal_to('source_url', str) querys = query.find() return len(querys) > 0
def is_exit(url): global category query = Query('Reading') query.equal_to('category', category) query.equal_to('source_url', url) querys = query.find() return len(querys) > 0
def connect_dev_and_real_app(table_name='Developer'): all_real_app = get_all_real_applications() DbTable = table_name query = Query(DbTable) query.less_than('createdAt',current_time) query.exists('objectId') query.equal_to('username','heamon7') dev = query.find()[0] # total_count=query.count() # query_times=(total_count+query_limit-1)/query_limit # user_list = [] # for index in range(query_times): # query = Query(DbTable) # query.exists('objectId') # query.less_than('createdAt',current_time) # query.ascending('createdAt') # query.limit(query_limit) # query.skip(index*query_limit) # user_list.extend(query.find()) # return user_list # all_installation = get_all_installation() # print 'already get all installation ,length is %s' %(str(len(all_installation))) for app in all_real_app: app.set('developer',dev) app.save()
def dislike(**params): card_id = params['cid'] user_id = params['uid'] card = Card.create_without_data(card_id) user = User.create_without_data(user_id) query = Query(Like) query.equal_to('card', card) query.equal_to('user', user) count = query.count() if count > 0: try: likes = query.first() likes.destroy() card.increment('likes', -1) card.fetch_when_save = True card.save() return {'code': 200, 'message': 'ok'} except LeanCloudError as e: result = {'code': e.code, 'message': e.error} return result else: result = {'code': 400, 'message': '点赞记录不存在'} return result
def isExit(title): global category query = Query('HJWordStudyCList') query.equal_to('category', category) query.equal_to('title', title) querys = query.find() return len(querys) > 0
def changeServerFileName(position, newName): query = Query(allPictures) query.equal_to('position', position) pictures = query.find() pictureSelect = pictures[0] pictureSelect.set('image_src', newName) pictureSelect.save()
def set_activity(uid, money, calories, est_price): now = datetime.datetime.now() month = now.year*100 + now.month query = Query(Activity) query.equal_to("uid", uid) query.equal_to("start_time", month) if query.count() == 0: ubers = money/est_price entry = Activity() entry.set("uid", uid) entry.set("start_time", month) entry.set("duration", 30) entry.set("budget_money", money) entry.set("budget_ubers", ubers) entry.set("budget_cal", calories) entry.set("curr_money", 0) entry.set("curr_cal", 0) entry.set("curr_time", 0) entry.set("curr_ubers", 0) # todo: duration, time! entry.save() else: ubers = money/est_price entry = query.first() entry.set("budget_money", money) entry.set("budget_cal", calories) entry.set("budget_ubers", ubers) entry.save()
def is_exit(str): query = Query('DailySentence') query.equal_to('dateline', str) querys = query.find() size = len(querys) # print size return size
def get_readys(): ''' 返回当前准备好的人 ''' user_query = Query(User) user_query.equal_to('ready', True) return user_query.find()
def run(): while 1: query = Query(Business) query.equal_to('geo_point', None) current_business = query.first() temp = current_business.address.values() current_address = " ".join(temp).replace("(", " ").replace(")", " ").replace(u'号', " ") try: lat, lon = get_coordinates(current_address) if lat == None or lon == None: print(1) lat, lon = get_coordinates(temp[1]+" "+temp[0]+" "+temp[2]) if lat == None or lon == None: print(2) lat, lon = get_coordinates(temp[0] + " " + temp[1]) if lat == None or lon == None: print(3) lat, lon = get_coordinates(current_address[:current_address.find(u'号')]) if lat == None or lon == None: print(4) lat, lon = get_coordinates(temp[0]+" "+temp[2]) if lat == None or lon == None: print(5) lat, lon = get_coordinates(current_address.translate(None, string.digits)) except (ValueError, TypeError): lat = 0 lon = 0 print("ERROR: ", current_business.attributes) print("----------------------------------------------") point = GeoPoint(latitude=lat, longitude=lon) current_business.set("geo_point", point) current_business.save()
def get_tracker_data(table_name=None,tracker_list=None,field_name=None): DBTable = Object.extend(table_name) tracker_data_dict = {} for index,tracker in enumerate(tracker_list): #这样处理是因为可能一个user的记录超过了一次可以读取的数量(1K条) query = Query(DBTable) query.equal_to(field_name,tracker) query.less_than('createdAt',currentTime) total_count=query.count() # print 'TotalCount %s' %str(total_count) query_times=(total_count+query_limit-1)/query_limit #如果想在这里按timestamp排序取出每个user的记录是不靠谱的,可能读取时还有插入,而且timestamp介于之间 for index in range(query_times): # print 'querying index: %s' %str(index) query = Query(DBTable) query.equal_to(field_name,tracker) query.less_than('createdAt',currentTime) query.ascending('createdAt') query.limit(query_limit) query.skip(index*query_limit) if tracker in userDataDict.keys(): tracker_data_dict.get(tracker).extend(query.find()) else : tracker_data_dict[tracker]=query.find() return tracker_data_dict
def consume(self): queue = SQS() rs = queue.read() print 'Start consuming:' for record in rs: mailId = record.get_body() print mailId Timer = Object.extend('Timer') timerQuery = Query(Timer) timerQuery.equal_to('mailId', mailId) firstTimer = timerQuery.first() if firstTimer.get('status') != 'sent': Mail = Object.extend('Mail') query = Query(Mail) mailObj = query.get(mailId) sender = mailer() mailToSent = { 'to':mailObj.get('to'), 'html':mailObj.get('html'), 'subject':mailObj.get('subject') } sender.send(mailToSent) firstTimer.set('status','sent') firstTimer.save() queue.remove(record) return self;
def uploadUser(): username = genPhoneNum() deviceId = genID() providerName = random.choice(("中国移动", "中国联通", "中国电信")) model = random.choice(('MX4 Pro', 'MI 4 LTE', 'SM-G9009W')) sdkVersion = random.choice(('19', '17', '21')) releaseVersion = random.choice(('4.3', '4.4.4', '4.1.2')) user = User() query = Query(User) query.equal_to('username', username) if(query.find()): username = genPhoneNum() user.set("username", username) user.set("password", "123456") user.set("deviceId", deviceId) user.set("providerName", providerName) user.set("model", model) user.set("sdkVersion", sdkVersion) user.set("releaseVersion", releaseVersion) user.set("value", 0) user.sign_up() user.set("mobilePhoneNumber", username) user.save()
def __init__(self): leancloud.init(settings.APP_ID, master_key=settings.MASTER_KEY) QuestionFollowee = Object.extend('Followee' + self.userDataId) questionFollowee = QuestionFollowee() # query = Query(QuestionFollowee) query.equal_to('followerLinkId',self.userLinkId) curTime = datetime.now() query.less_than('createdAt', curTime) followeeCount = query.count() print "followeeNumbers: %s" % str(questionNum) queryLimit = 500 queryTimes = int(followeeCount +queryLimit -1) / queryLimit self.urls = [] for index in range(queryTimes): query = Query(QuestionFollowee) query.less_than('createdAt', curTime) query.equal_to('followerLinkId',self.userLinkId) query.descending('createdAt') query.limit(queryLimit) query.skip(index * queryLimit) query.select('followeeDataId') quesRet = query.find() for ques in quesRet: self.followeeDataIdList.extend(ques.get('followeeDataId'))
def active_device_by_username(username): user = user_by_username(username) dq = Query("Device") dq.equal_to("caster", user) dq.equal_to("status", "Active") device_list = dq.find() return device_list
def validate_weuser(): code = request.args.get('code') if code: url = str.format( 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' % (wechat.conf.appid, wechat.conf.appsecret, str(code))) else: return None resp = requests.get(url) authorize_result = json.loads(resp.text) openid = authorize_result.get('openid') token = authorize_result.get('access_token') # userinfo = wechat.get_user_info(openid) if openid: logger.debug("wechat openId: %s, token: %s", openid, str(token)) else: logger.debug("wechat openid invalidated!!!") try: query = Query(WeUsers) query.equal_to('openid', openid) wuser = query.find() if len(wuser) > 0: wuser = wuser[0] else: logger.debug('try to retrieve userinfo') wechathandler.get_user_info(openid, token) # wuser = wechathandler.retrieve_weuser(openid) return wuser except leancloud.LeanCloudError: logger.warning("WeUser not found")
def result_index(index): print 'get result from index', index try: query = Query(DeviceKey) query.equal_to('index', index) devicekey = query.first() device_name = devicekey.get('name_cn') key = devicekey.id except: return jsonify(error='invalid index') try: data = get_latest(key) hour = data.created_at.hour + 8 ch2o = data.get('ch2o') if ch2o == 65535: ch2o = 0 ch2o = round(ch2o * 1.32 / 1000, 2) data.set('ch2o', ch2o) except: return jsonify(error='invalid key') try: local_time = utc2local(data.created_at) except: print 'local time change error' local_time = data.created_a #pm =average_pm(24,key) pm = min_pm(key) noise = min_noise(key) return render_template('result.html', esp_test=data, local_time=local_time, pm=pm, noise=noise, index=index, device_name=device_name)
def create_new_app(self, app_name): try: if not app_name: return 0 user = self.user.become(self.session_token) print "Got the user" Application = Object.extend(APPLICATION_CLASS) application = Application() query = Query(Application) query.equal_to("user", user) query.equal_to("app_name", app_name) if query.find(): print "Application name exists!" return 0 else: print "Application name not exists! " application.set("app_name", app_name) application.set("user", user) application.save() app_id = application.id app_key = (signer.sign(app_id).split(app_id + "."))[1] # app_key = app_id+"this is app_key" application.set("app_id", app_id) application.set("app_key", app_key) application.save() return 1 except LeanCloudError, e: print e return 0
def process_sj_range(item): code = item['code'].strip() if not code: return data = { 'page_num': int(item['page_num']), 'code': code, 'type': 'sj', 'subject': item['subject'] } query = Query(Range) query.equal_to('code', code) query.equal_to('type', 'sj') try: one = query.first() except LeanCloudError: one = Range() last_page_num = 0 one.set('state', 0) else: last_page_num = one.get('page_num') if last_page_num != data['page_num']: one.set('state', 0) else: one.set('state', 1) for k, v in data.items(): one.set(k, v) one.set('last_page_num', last_page_num) one.save() return item
def get_tracker_of_app(self, app_id=""): try: self.tracker_list = [] # user = self.user.become(self.session_token) Application = Object.extend("Application") query = Query(Application) # query.equal_to('user', user) # app_id = 'demo 55f7e36f60b2fe7115171b4b' print "@@@@@@@@@@@@@@@@@@" + app_id query.equal_to("app_id", app_id) app_list = query.find() if len(app_list) != 1: return [] the_app = app_list[0] # Tracker = Object.extend('BindingInstallation') # query = Query(Tracker) # query.equal_to('application', the_app) # app_list = query.find() relation = the_app.relation("tracker") print relation, return 1 except LeanCloudError, e: print e return 0
def get_field_data_dict(table_name='WeightedStaticInfo',tracker_list=None): try: field_name = 'field' tracker_field_name = 'user' DBTable = Object.extend(table_name) data_dict ={} # new_data_dict = {key:[0 for i in range(4)] for key in dataDict.keys()} total_count = len(tracker_list) for index, tracker in enumerate(tracker_list): query = Query(DBTable) query.equal_to(tracker_field_name,tracker) query.select(field_name) result_list = query.find() length = len(result_list) # 以后这个地方的判断还需要修改 if length!=1: print 'error: the length of result_list is %s with index: %s with tracker_objectId: %s' %(str(length),str(index),tracker.id) if length >=1: result = result_list[0] else: continue print 'index: %s field_name: %s: result: %s ' %(str(index),str(field_name),str(result.get(field_name))) field_key= result.get(field_name).keys()[0] if field_key in data_dict.keys(): data_dict[field_key] += 1 else: data_dict[field_key] = 1 known_count = sum(data_dict.values()) data_dict['unknown'] = total_count - known_count except LeanCloudError, e: raise e
def is_exit(name, url): query = Query('Caricature') query.equal_to('name', name) query.equal_to('url', url) querys = query.find() return len(querys) > 0
def get_event_to_location_data(self, event_name=None, app_table=APPLICATION_CLASS, kind=None): # print app_table try: app = self.get_the_app(kind=kind) db_name = "FakeEventActivity" DbTable = Object.extend(db_name) query = Query(DbTable) # 这里只是测试知道是少于1K条的 query.equal_to("application", app) query.exists("location_dict") if event_name: query.equal_to("event_name", event_name) # query.equal_to('application_id',application_id) query.descending("createdAt") query.limit(1) result_list = query.find() if result_list: # event_name = result_list[0].get('event_name') # activity_statistics_dict = {result_list[0].get('event_name'):result_list[0].get('activity_dict')} statistics_dict = result_list[0].get("location_dict") else: statistics_dict = [] except LeanCloudError, e: raise e
def clear_feed(name, day): oldest = datetime.now() - timedelta(days=day) query = Query(Feed) query.equal_to('name', name).less_than("time", oldest) for e in query.find(): print('delete old feed: %s (%s)' % (e.get('title').encode('utf-8'), e.get('time'))) e.destroy()
def get_all_feed(name): try: query = Query(Feed) query.equal_to('name', name).descending("time") return query.find() except LeanCloudError, e: if e.code == 101: return [] else: raise (e)
def getOnePictureByPosition(position): query = Query(allPictures) query.equal_to('position', position) pictures = query.find() if len(pictures) > 0: return pictures[0] else: return None
def is_exist(post_id): query = Query(Search) query.equal_to('post_id', post_id) try: obj = query.first() print 'post_id exist', post_id return True except: # not exist return False
def getType(type_name): query = Query('HJWordStudyCategory') query.equal_to('name', type_name) querys = query.find() if len(querys) > 0: data = querys[0] return data.get('type_code') else: print 'not exit'
def init_developer_with_user_id(self, user_id): query = Query(User) query.equal_to("objectId", user_id) result = query.find() if len(result) == 1: return result[0] else: print len(result) print user_id
def get_latest(key): try: query = Query(test_esp) query.equal_to('key', key) query.descending('createdAt') latest = query.first() return latest except: rasie
def get_lastest_item_id(): query = Query('Reading') query.equal_to('category', 'composition') query.equal_to('source_name', '恒星英语') query.descending("item_id") query.limit(1) querys = query.find() itemId = querys[0].get("item_id") return itemId
def requestConfirmationCode(**params): print 'request confirmation code starts' if 'email' in params: try: fromaddr = "*****@*****.**" toaddr = params['email'] print "toaddr: " + toaddr password = "******" code = ''.join(choice(digits) for i in xrange(6)) # code = "123456" print "code: " + code ConfirmationCode = Object.extend('ConfirmationCode') query = Query(ConfirmationCode) query.equal_to('email', toaddr) query_list = query.find() if len(query_list) > 0: concode = query_list[0] concode.set('code', code) concode.save() else: concode = ConfirmationCode() concode.set('email', toaddr) concode.set('code', code) concode.save() message = MIMEMultipart() message['From'] = fromaddr message['To'] = toaddr message['Subject'] = "【USC日常】你的注册验证码是 " + code body = "" body += "同学你好!\n\n你正在注册使用USC日常,你的验证码是 " body += code body += ".\n此验证码将会在20分钟后失效,请尽快验证。\n\n\n" body += "\n如果你并没有注册USC日常,请忽略此邮件。\n" body += "\n\nbest," body += "\nUSC日常APP" message.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', '587') server.ehlo() server.starttls() server.login(fromaddr, password) text = message.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print 'request confirmation code ends' return True except Exception as e: print e print 'request confirmation code ends' raise LeanEngineError('发送验证码失败,请稍后重试') else: print "email cannot be empty" print 'request confirmation code ends' raise LeanEngineError('邮箱地址不能为空')
def min_pm(key): query = Query(test_esp) query.equal_to('key', key) query.descending('createdAt') pm = [] query.limit(60) results = query.find() for result in results: pm.append(result.get('pm')) pm.reverse() return pm
def querySmslog(smscode): try: mytest = Object.extend("smscodelog") query = Query(mytest) # query.not_equal_to("status", 4) # query.not_equal_to("status", 5) query.equal_to("smscode",smscode) olds = query.first except Exception,e: print 'e=',
def get_lastest_item_id(): query = Query('Reading') query.equal_to('category', 'shuangyu_reading') query.equal_to('source_name', '恒星英语') query.descending("item_id") query.limit(1) querys = query.find() if len(querys) == 0: return 0 else: return querys[0].get("item_id")
def min_noise(key): query = Query(test_esp) query.equal_to('key', key) query.descending('createdAt') noise = [] query.limit(60) results = query.find() for result in results: noise.append(result.get('noise')) noise.reverse() return noise
def get_lastest_item_id(): query = Query('Reading') query.equal_to('category', 'composition') query.equal_to('source_name', '水滴英语作文网') query.descending("item_id") query.limit(1) querys = query.find() if len(querys) == 0: return 0 else: return querys[0].get("item_id")
def get_lastest_item_id(): global source_name global category query = Query('Reading') query.equal_to('category', category) query.descending("item_id") query.limit(1) querys = query.find() if len(querys) == 0: return 0 else: return querys[0].get("item_id")
def is_exit(name, url, update, views): query = Query('Caricature') query.equal_to('name', name) query.equal_to('url', url) querys = query.find() # if len(querys) > 0: # data = querys[0] # data.set('update', update) # data.set('views', views) # data.save() # print 'update success' return len(querys) > 0
def change_name(index): if request.method == 'POST': name_cn = request.form.get('name_cn') if (name_cn == ''): name_cn = None query = Query(DeviceKey) query.equal_to('index', index) devicekey = query.first() devicekey.set('name_cn', name_cn) devicekey.save() return redirect('/status') else: return render_template('changename.html')
def get_user_num(page_url): ''' 查询页面用户数 :param page_url: :return: 当前页面用户数 ''' cls_page = Object.extend('UserInPage') query_page = Query(cls_page) query_page.equal_to('page_url', page_url) try: result = query_page.first() except Exception, e: return 0
def average_pm(num, key): query = Query(test_esp) query.equal_to('key', key) query.descending('createdAt') pm = [] for i in range(1, 24): query.limit(60) results = query.find() pm.append(average(results, 60)) query.skip(60 * i) pm.reverse() print pm return pm
def insert_or_update(model, cond, data, saving=True): query = Query(model) for k, v in cond.items(): query.equal_to(k, v) try: one = query.first() except LeanCloudError: one = model() for k, v in data.items(): one.set(k, v) if saving: one.save() return one