def checkIfConfirmationCodeMatches(**params): print "check if confirmation code matches starts" if 'email' in params and 'code' in params: try: email = params['email'] print "email: " + email code = params['code'] print "code: " + code ConfirmationCode = Object.extend('ConfirmationCode') twentyMinutesAgo = datetime.datetime.now() - datetime.timedelta( minutes=20) print(twentyMinutesAgo) query1 = ConfirmationCode.query query2 = ConfirmationCode.query query3 = ConfirmationCode.query query1.equal_to('email', email) query2.equal_to('code', code) query3.greater_than_or_equal_to('updatedAt', twentyMinutesAgo) query12 = Query.and_(query1, query2) query = Query.and_(query12, query3) query_list = query.find() print "check if confirmation code matches ends" if len(query_list) == 0: return False else: return True except Exception as e: print e print "check if confirmation code matches ends" raise LeanEngineError('系统错误:无法验证验证码') else: print "email and code cannot be empty" print "check if confirmation code matches ends" raise LeanEngineError('邮箱以及验证码都不能为空')
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 before_todo_save(comment): comment_mail = comment.get('mail') comment_nick = comment.get('nick') logging.debug('评论人[%s]<------>评论邮箱[%s]' % (comment_nick, comment_mail)) if comment_mail.strip() == "" or comment_nick == "Anonymous": raise LeanEngineError(message='评论必填项为空')
def after_comment_save(comment): try: # 发送邮件 logging.debug('>>>>>>>>>>>>>>开始发送评论邮件提醒<<<<<<<<<<<<<<<<<%s' % comment) comment_mail_transfer(comment) except leancloud.LeanCloudError: raise LeanEngineError(message='An error occurred while trying to save the Post. ')
def getAttraction(**params): try: city = params.get('city') page = params.get('page', 0) except: raise LeanEngineError(501, 'Invalid argument.') array = [] Attraction = leancloud.Object.extend("Attraction") query = Attraction.query query.equal_to("area", city) query_list = query.find() for i in query_list: array.append({ "id": i.id, "title": i.get("title"), "price": i.get("price"), "recommend_num": i.get("recommend_num"), "image": i.get("image").url, "travel_note_num": i.get("travel_note_num"), }) result = { "next": -1, "array": array, } return result
def searchAttraction(**params): try: keyword = params.get('keyword') except: raise LeanEngineError(501, 'Invalid argument.') array = [] Attraction = leancloud.Object.extend("Attraction") query = Attraction.query query.contains("title", keyword) query_list = query.find() for i in query_list: array.append({ "id": i.id, "name": i.get("title"), # "price": i.get("price"), # "recommend_num": i.get("recommend_num"), "image": i.get("image"), "city": i.get("area"), # "travel_note_num": i.get("travel_note_num"), }) result = { "array": array, } return result
def likeComment(**params): try: id = params.get('id') like = params.get('like') except: raise LeanEngineError(501, 'Invalid argument.') current_user = travelNote_engine.current.user Comment = leancloud.Object.extend("Comment") comment = Comment.create_without_data(id) comment.fetch() CommentLike = leancloud.Object.extend("CommentLike") if like == 'true': commentLike = CommentLike() commentLike.set("comment", comment) commentLike.set("likeUser", current_user) commentLike.save() elif like == 'false': commentLike = CommentLike() query = CommentLike.query query.equal_to("comment", comment) query.equal_to("likeUser", current_user) query_list = query.find() for i in query_list: i.destroy() else: return { "status": -1, "messgae": "请求非法", } return { "status": 0, }
def after_event_save(event): print("after event save started") institution = event.get('institution') print "institution:" + institution Conversation = Object.extend('_Conversation') query1 = Conversation.query query2 = Conversation.query query1.equal_to('name', institution) query2.equal_to('sys', True) query = Query.and_(query1, query2) query_list = query.find() if len(query_list) == 0: raise LeanEngineError('没有找到系统对话') else: conversation = query_list[0] conversation_id = conversation.get('objectId') print "conversationId:" + conversation_id eventId = event.get('objectId') headers = {'Content-Type': 'application/json', \ 'X-LC-Id': APP_ID, \ 'X-LC-Key': MASTER_KEY + ',master'} data = {"from_peer": "sys", \ "message": "{\"_lctype\":-1,\"_lctext\":\"eventCreated\", \ \"_lcattrs\":{\"snType\":" + str(snEventCreated) + \ ",\"eventId\": \"" + eventId + "\"}}", \ "conv_id": conversation_id} requests.post(subscriber_url, data=json.dumps(data), headers=headers) print("after event save ended")
def getFullInfo(**params): current_user = cloud_userInfo.current.user if not current_user: raise LeanEngineError("401", "Unauthorized") phone = current_user.get("mobilePhoneNumber") nickname = current_user.get("nickname") introduction = current_user.get("introduction") user = { "phone": phone, "nickname": nickname, "introduction": introduction, } is_guide = current_user.get("is_guide") guide = {} # 根据用户查询导游信息 Guide = leancloud.Object.extend("Guide") query = Guide.query query.equal_to("user", current_user) query_list = query.find() # i是导游 for i in query_list: guide_id = i.id # 导游id introduction = i.get("about") max_num = i.get("max_num") price = i.get("price") city = i.get("area") sightseeings = [] sightseeing_names = [] features = i.get("features") # 根据导游id查询导游熟悉景点 GuideAttractionMap = leancloud.Object.extend("GuideAttractionMap") query = GuideAttractionMap.query query.equal_to("guide", i) query_list = query.find() # j是导游熟悉景点map的条目 for j in query_list: Attraction = leancloud.Object.extend("Attraction") attraction = Attraction.create_without_data(j.get("attraction").id) attraction.fetch() sightseeings.append(attraction.id) sightseeing_names.append(attraction.get("title")) guide = { "is_open": is_guide, "introduction": introduction, "max_num": max_num, "price": price, "city": city, "sightseeings": sightseeings, "sightseeing_names": sightseeing_names, "features": features } break result = {"user": user, "guide": guide} return result
def publishTravelNote(**params): try: guideID = params.get('guideID') target = params.get('target') peopleNum = params.get('peopleNum') theme = params.get('theme') path = params.get('path') startDate = params.get('startDate') endDate = params.get('endDate') spend = params.get('spend') content = params.get('content') title = params.get('title') except: raise LeanEngineError(501, 'Invalid argument.') try: current_user = travelNote_engine.current.user TravelNote = leancloud.Object.extend('TravelNote') User = leancloud.Object.extend("_User") # 这里是导游的用户id,不是导游id user = User.create_without_data(guideID) user.fetch() # 通过这个用户找到导游信息 Guide = leancloud.Object.extend('Guide') query = Guide.query query.equal_to("user", user) query_list = query.find() if len(query_list) <= 0: return { "code": -1, "msg": "Failed. Please check if the guideid is valid or if the user is a guide." } guide = query_list[0] newTravelNote = TravelNote() newTravelNote.set("guide", guide) newTravelNote.set("author", current_user) newTravelNote.set("area", target) newTravelNote.set("peopleNum", peopleNum) newTravelNote.set("title", title) newTravelNote.set("theme", theme) newTravelNote.set("path", path) newTravelNote.set("startDate", datetime.datetime.strptime(startDate, "%Y-%m-%d %H:%M:%S")) newTravelNote.set("endDate", datetime.datetime.strptime(endDate, "%Y-%m-%d %H:%M:%S")) newTravelNote.set("spend", spend) newTravelNote.set("content", content) newTravelNote.save() return { "code": 0, "id": newTravelNote.id } except Exception as e: print e.message return { "code": -1, "msg": e.message }
def subscribeToSystemConversation(**params): print "subscribe to system conversation starts" if 'clientId' in params and 'institution' in params: try: client_id = params['clientId'] print "clientId:" + client_id institution = params['institution'] print "institution:" + institution Conversation = Object.extend('_Conversation') query1 = Conversation.query query2 = Conversation.query query1.equal_to('name', institution) query2.equal_to('sys', True) query = Query.and_(query1, query2) query_list = query.find() if len(query_list) == 0: raise LeanEngineError('没有找到系统对话') else: conversation = query_list[0] conversation_id = conversation.get('objectId') print "conversationId:" + conversation_id headers = {'Content-Type': 'application/json', \ 'X-LC-Id': APP_ID, \ 'X-LC-Key': MASTER_KEY + ',master'} data = {"conv_id": conversation_id, "client_id": client_id} requests.post(subscription_url, data=json.dumps(data), headers=headers) print "subscribe to system conversation ends" return True except Exception as e: print e print "subscribe to system conversation ends" raise LeanEngineError('订阅系统通知失败,请稍后重试') else: print "client id and institution must not be empty" print "subscribe to system conversation ends" raise LeanEngineError('client id and institution must be not empty')
def checkIfEmailIsTaken(**params): print 'check if email is taken starts' if 'email' in params: try: email = params['email'] print "email: " + email query = Query('_User') query.equal_to('email', email) query_list = query.find() print('check if email is taken ends') if len(query_list) == 0: return False else: return True except Exception as e: print e print('check if email is taken ends') raise LeanEngineError('系统错误,无法查询邮箱是否占用') else: print "email cannot be empty" print('check if email is taken ends') raise LeanEngineError('没有提供邮箱地址')
def before_todo_save(todo): content = todo.get('content') if not content: raise LeanEngineError('内容不能为空') if len(content) >= 240: todo.set('content', content[:240] + ' ...') author = todo.get('author') if author: acl = ACL() acl.set_public_read_access(True) acl.set_read_access(author.id, True) acl.set_write_access(author.id, True) todo.set_acl(acl)
def editUserInfo(**params): current_user = cloud_userInfo.current.user if not current_user: raise LeanEngineError("401", "Unauthorized") try: filed = params.get('filed') data = params.get('data') except: raise LeanEngineError(501, 'Invalid argument.') try: current_user.set(filed, data) current_user.save() except: return { "status": -1, "message": '字段不存在或无权限修改', } return { "status": 0, }
def after_event_update(event): print("after event update called...") institution = event.get('institution') print "institution:" + institution Conversation = Object.extend('_Conversation') query1 = Conversation.query query2 = Conversation.query query1.equal_to('name', institution) query2.equal_to('sys', True) query = Query.and_(query1, query2) query_list = query.find() if len(query_list) == 0: raise LeanEngineError('没有找到系统对话') else: conversation = query_list[0] conversation_id = conversation.get('objectId') print "conversationId:" + conversation_id eventId = event.get('objectId') headers = {'Content-Type': 'application/json', \ 'X-LC-Id': APP_ID, \ 'X-LC-Key': MASTER_KEY + ',master'} data = {"from_peer": "sys", \ "message": "{\"_lctype\":-1,\"_lctext\":\"eventUpdated\", \ \"_lcattrs\":{\"snType\":" + str(snEventUpdated) + \ ",\"eventId\": \"" + eventId + "\"}}", \ "conv_id": conversation_id} requests.post(subscriber_url, data=json.dumps(data), headers=headers) # if event is finalized, send finalized message remain_people = event.get('remainingSeats') if remain_people <= 0: conversationPointer = event.get('conversation') conversation_id = conversationPointer.get('objectId') conversation = Query('_Conversation').get(conversation_id) if conversation.has(key_of_finalized_message) == False: finalizedMessage = "微活动约定成功!系统已经将对话设为私有。" finalizedMessage += "这条信息以下只有队员才可以发言!【日常小管家】" headers = {'Content-Type': 'application/json', \ 'X-LC-Id': APP_ID, \ 'X-LC-Key': MASTER_KEY + ',master'} data = {"from_peer": admin, \ "message": "{\"_lctype\":-1,\"_lctext\": \"" + finalizedMessage + "\", \ \"_lcattrs\":{\"reason\": \"finalized\"}}" , \ "conv_id": conversation_id, "transient": False} requests.post(messages_url, data=json.dumps(data), headers=headers) conversation.set(key_of_finalized_message, True) conversation.save()
def createSystemConversationIfNotExists(**params): print "create system conversation if not exists starts" if 'email' in params: try: email = params['email'] print "email:" + email suffix = email[email.find('@') + 1:] print "suffix:" + suffix institution = suffix[:suffix.find('.')] print "institution:" + institution Conversation = Object.extend('_Conversation') query1 = Conversation.query query2 = Conversation.query query1.equal_to('name', institution) query2.equal_to('sys', True) query = Query.and_(query1, query2) query_list = query.find() if len(query_list) == 0: headers = {'Content-Type': 'application/json', \ 'X-LC-Id': APP_ID, \ 'X-LC-Key': APP_KEY} data = {"name": institution, \ "sys": True} requests.post(conversation_url, data=json.dumps(data), headers=headers) print "create system conversation if not exists ends" return True except Exception as e: print e print "create system conversation if not exists ends" raise LeanEngineError('创建系统对话失败,请稍后重试') else: print "email cannot be empty" print "create system conversation if not exists ends" raise LeanEngineError('邮箱不能为空')
def commentTravelNote(**params): try: id = params.get('id') content = params.get('content') except: raise LeanEngineError(501, 'Invalid argument.') current_user = travelNote_engine.current.user TravelNote = leancloud.Object.extend("TravelNote") travelNote = TravelNote.create_without_data(id) travelNote.fetch() Comment = leancloud.Object.extend("Comment") comment = Comment() comment.set("TravelNote", travelNote) comment.set("comment_user", current_user) comment.set("content", content) comment.save() return { "status": 0, }
def favTravelNote(**params): try: id = params.get('id') like = params.get('like') except: raise LeanEngineError(501, 'Invalid argument.') current_user = travelNote_engine.current.user TravelNote = leancloud.Object.extend("TravelNote") travelNote = TravelNote.create_without_data(id) travelNote.fetch() TravelNoteFav = leancloud.Object.extend("TravelNoteFav") if like == 'true': travelNoteFav = TravelNoteFav() travelNoteFav.set("TravelNote", travelNote) travelNoteFav.set("favUser", current_user) travelNoteFav.save() travelNote.set("fav",travelNote.get("fav")+1) travelNote.save() elif like == 'false': travelNoteFav = TravelNoteFav() query = TravelNoteFav.query query.equal_to("TravelNote", travelNote) query.equal_to("favUser", current_user) query_list = query.find() for i in query_list: i.destroy() travelNote.set("fav",travelNote.get("fav")-1) travelNote.save() else: return { "status": -1, "messgae": "请求非法", } return { "status": 0, }
def getTravelNoteList(**params): try: city = params.get('city', '') keyword = params.get('keyword', '') # optional type = params.get('type', '') # optional order_by = params.get('order_by', -1) # optional category = params.get('category', '') # optional page = params.get('page', -1) # optional # # sightseeings = json.loads(params.get('sightseeings')) date = json.loads(params.get('date', 'null')) # optional spend = json.loads(params.get('spend', 'null')) # optional except: raise LeanEngineError(501, 'Invalid argument.') # 计算当前季度月份区间 current_year = datetime.datetime.now().year current_month = datetime.datetime.now().month if 1 <= current_month <= 3: month_low = 1 month_high = 3 elif 4 <= current_month <= 6: month_low = 4 month_high = 6 elif 7 <= current_month <= 9: month_low = 7 month_high = 9 else: month_low = 9 month_high = 12 # 查询游记 TravelNote = leancloud.Object.extend('TravelNote') if keyword == '': query = TravelNote.query else: query1 = TravelNote.query query2 = TravelNote.query query1.contains("title", keyword) query2.contains("content", keyword) query = leancloud.Query.or_(query1, query2) if city != '': query.equal_to("area", city) # 添加季度查询条件 if type == 'season': query.greater_than_or_equal_to("createdAt", datetime.datetime(current_year, month_low, 1, 0, 0, 0)) query.less_than("createdAt", datetime.datetime(current_year, month_high, 1, 0, 0, 0)) # 添加精品条件(大于100的都是精品) elif type == 'boutique': query.greater_than_or_equal_to("fav", 100) # 否则两个条件都不生效 else: pass # order_by字段 # 综合排序 if order_by == 1: query.add_descending("createdAt") # 收藏多 elif order_by == 2: query.add_descending("fav") # 游记的日期范围,包含查询 if date != None: query.greater_than_or_equal_to("createdAt", datetime.datetime.strptime(date[0], "%Y-%m-%d %H:%M:%S")) query.less_than("createdAt", datetime.datetime.strptime(date[1], "%Y-%m-%d %H:%M:%S")) # 开销, 两个int指范围,一个为-1时为不限,比如[-1, 100]指的是100元以下 if spend != None: if spend[0] != -1: query.greater_than_or_equal_to("spend", spend[0]) if spend[1] != -1: query.less_than_or_equal_to("spend", spend[1]) # 开始查询 query_list1 = query.find() # 根据category筛选 result_list = [] if category != '': TravelNoteTag = leancloud.Object.extend('TravelNoteTag') query = TravelNoteTag.query query.equal_to("name", category) query_list = query.find() TravelNoteTagMap = leancloud.Object.extend('TravelNoteTagMap') query = TravelNoteTagMap.query if len(query_list) != 0: query.equal_to("travelNoteTag", query_list[0]) query_list = query.find() else: query_list = [] for i in query_list: for j in query_list1: if j.id == i.get("travelNote").id: query11 = TravelNote.query a = query11.get(i.get("travelNote").id) result_list.append(a) break query_list1 = result_list array = [] for i in query_list1: pics = [] content = i.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # else: # picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append("http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg") # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(i.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("travelNote", i) query_list = query.find() commentNum = len(query_list) #查询收藏数量 TravelNoteFav = leancloud.Object.extend('TravelNoteFav') query = TravelNoteFav.query query.equal_to("TravelNote", i) query_list = query.find() favNum = len(query_list) i.set("like",favNum) i.save() array.append({ "id": str(i.id), "image": pics[0], "title": i.get("title"), "nickname": user.get("nickname"), "avatar": avatar_url, "favNum": favNum, "replyNum": commentNum, "price": i.get("spend"), "date": i.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), }) result = { "next": -1, "array": array } return result
def getTravelNoteContent(**params): current_user = travelNote_engine.current.user if not current_user: raise LeanEngineError("401", "Unauthorized") try: id = params.get('id') except: raise LeanEngineError(501, 'Invalid argument.') TravelNote = leancloud.Object.extend('TravelNote') travel = TravelNote.create_without_data(id) travel.fetch() # 查询是否收藏 TravelNoteFav = leancloud.Object.extend('TravelNoteFav') query = TravelNoteFav.query query.equal_to("TravelNote", travel) query.equal_to("favUser", current_user) query_list = query.find() if len(query_list) <= 0: isFaved = False else: isFaved = True # 查询是否点赞 TravelNoteLike = leancloud.Object.extend('TravelNoteLike') query = TravelNoteLike.query query.equal_to("TravelNote", travel) query.equal_to("likeUser", current_user) query_list = query.find() if len(query_list) <= 0: isLiked = False else: isLiked = True title = travel.get("title") content = travel.get("content") # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(travel.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None authorid = travel.get("author").id nickname = user.get("nickname") avatar = avatar_url author = { "id": authorid, "nickname": nickname, "avatar": avatar, } # 查询行程信息 date = (travel.get("startDate").strftime("%Y-%m-%d %H:%M:%S"), travel.get("endDate").strftime("%Y-%m-%d %H:%M:%S")) peopleNum = travel.get("peopleNum") theme = travel.get("theme") spend = travel.get("spend") path = travel.get("path") Guide = leancloud.Object.extend("Guide") guide1 = Guide.create_without_data(travel.get("guide").id) guide1.fetch() User = leancloud.Object.extend("_User") user1 = User.create_without_data(guide1.get("user").id) user1.fetch() guideName = user1.get("nickname") guide = user1.id journey = { "date": date, "peopleNum": peopleNum, "theme": theme, "spend": spend, "path": path, "guide": guide, "guideName": guideName, } # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("TravelNote", travel) query.include("thumbs") query.include("createAt") query_list = query.find() comments = [] for i in query_list: User = leancloud.Object.extend("_User") user = User.create_without_data(i.get("comment_user").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None authorid = user.id nickname = user.get("nickname") avatar = avatar_url # 查询评论是否被自己点赞 CommentLike = leancloud.Object.extend('CommentLike') query = CommentLike.query query.equal_to("comment", i) query_list = query.find() likeNum = len(query_list) CommentLike = leancloud.Object.extend('CommentLike') query = CommentLike.query query.equal_to("comment", i) query.equal_to("likeUser", current_user) query_list = query.find() if len(query_list) <= 0: isLiked = False else: isLiked = True comments.append({ "id": i.id, "avatar": avatar, "nickname": nickname, "date": i.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), "likeNum": likeNum, "content": i.get("content"), "isLiked": isLiked }) result = { "id": id, "title": title, "content": content, "author": author, "isLiked": isLiked, "isFaved": isFaved, "journey": journey, "comments": comments, } return result
def getGuideInfo(**params): try: id = params.get('id') # 用户id,是user的objectId,不是导游表的id except: raise LeanEngineError(501, 'Invalid argument.') # 根据用户id查询用户 User = leancloud.Object.extend("_User") user = User.create_without_data(id) user.fetch() # 根据用户查询导游信息 Guide = leancloud.Object.extend("Guide") query = Guide.query query.equal_to("user", user) query_list = query.find() # i是导游 for i in query_list: guide_id = i.id # 导游id labels = [] features = i.get("features") sightseeings = [] about = i.get("about") # 根据导游id查询导游标签 GuideNeedTagMap = leancloud.Object.extend("GuideNeedTagMap") query = GuideNeedTagMap.query query.equal_to("guide", i) query_list = query.find() # j是导游标签map的条目 for j in query_list: GuideNeedTag = leancloud.Object.extend("GuideNeedTag") guideNeedTag = GuideNeedTag.create_without_data( j.get("guideNeedTag").id) guideNeedTag.fetch() labels.append(guideNeedTag.get("name")) # 根据导游id查询导游熟悉景点 GuideAttractionMap = leancloud.Object.extend("GuideAttractionMap") query = GuideAttractionMap.query query.equal_to("guide", i) query_list = query.find() # j是导游熟悉景点map的条目 for j in query_list: Attraction = leancloud.Object.extend("Attraction") attraction = Attraction.create_without_data(j.get("attraction").id) attraction.fetch() sightseeings.append(attraction.get("title")) # 查询该导游的相关游记 TravelNote = leancloud.Object.extend("TravelNote") query = TravelNote.query query.equal_to("guide", i) query_list = query.find() travel_notes = [] for j in query_list: pics = [] content = j.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append( "http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg" ) # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(j.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("travelNote", j) query_list = query.find() commentNum = len(query_list) travel_notes.append({ "id": str(j.id), "image": pics[0], "title": j.get("title"), "nickname": user.get("username"), "avatar": avatar_url, "favNum": j.get("like"), "replyNum": commentNum, "price": j.get("spend"), "date": [ j.get("startDate").strftime("%Y-%m-%d %H:%M:%S"), j.get("endDate").strftime("%Y-%m-%d %H:%M:%S") ] }) result = { "labels": labels, "features": features, "sightseeings": sightseeings, "about": about, "travel_notes": travel_notes } return result
def getReceivedComment(**params): current_user = cloud_userInfo.current.user if not current_user: raise LeanEngineError("401", "Unauthorized") try: page = params.get('page') except: raise LeanEngineError(501, 'Invalid argument.') array = [] # 查询我的游记 TravelNote = leancloud.Object.extend("TravelNote") query = TravelNote.query query.equal_to("author", current_user) query_list = query.find() # j是游记 for j in query_list: # 这篇游记的图片、标题、发布时间 title = j.get("title") publishTime = j.get("createdAt") pics = [] content = j.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append( "http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg") # 查询谁评论了这篇游记 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("TravelNote", j) query_list1 = query.find() # k是评论了游记的记录 for k in query_list1: # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(k.get("comment_user").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None array.append({ "id": str(k.id), # 评论的id "image": pics[0], # 你游记的图片,或者你评论的那个游记的图片, "title": title, # 同上的那个游记的标题 "nickname": user.get("nickname"), # 评论的人的名字, "avatar": avatar_url, # 评论的人的头像 "time": k.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), # 评论的时间 "publishTime": publishTime.strftime("%Y-%m-%d %H:%M:%S"), # 同上的那个游记的发布时间 "comment": k.get("content") }) result = { "next": -1, "array": array, } return result
def getUserInfo(**params): try: id = params.get('id') except: raise LeanEngineError(501, 'Invalid argument.') # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(id) user.fetch() avatar = user.get("avatar") nickname = user.get("nickname") city = user.get("city") level = user.get("level") intro = user.get("introduction") is_guide = user.get("is_guide") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询该用户的游记 TravelNote = leancloud.Object.extend("TravelNote") query = TravelNote.query query.equal_to("author", user) query_list = query.find() moments = [] for j in query_list: pics = [] content = j.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append( "http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg") # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(j.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("travelNote", j) query_list = query.find() commentNum = len(query_list) moments.append({ "id": str(j.id), "image": pics[0], "title": j.get("title"), "nickname": user.get("nickname"), "avatar": avatar_url, "favNum": j.get("like"), "replyNum": commentNum, "price": j.get("spend"), "date": j.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), }) favorites = [] TravelNoteFav = leancloud.Object.extend("TravelNoteFav") query = TravelNoteFav.query query.equal_to("favUser", user) query_list = query.find() for j in query_list: pics = [] travelNote = TravelNote.create_without_data(j.get("TravelNote").id) travelNote.fetch() content = travelNote.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append( "http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg") # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(travelNote.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("travelNote", travelNote) query_list = query.find() commentNum = len(query_list) favorites.append({ "id": str(travelNote.id), "image": pics[0], "title": travelNote.get("title"), "nickname": user.get("nickname"), "avatar": avatar_url, "favNum": travelNote.get("like"), "replyNum": commentNum, "price": travelNote.get("spend"), "date": travelNote.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), }) result = { "avatar": avatar_url, "nickname": nickname, "city": city, "level": level, "intro": intro, "is_guide": is_guide, "moments": moments, "favorites": favorites, } return result
def getTravelNoteFromFollowee(**params): current_user = travelNote_engine.current.user if not current_user: raise LeanEngineError("401", "Unauthorized") else: Followee = leancloud.Object.extend('_Followee') query = Followee.query query.equal_to("user", current_user) query_list = query.find() result = [] array = [] # i = Followee for i in query_list: TravelNote = leancloud.Object.extend('TravelNote') query1 = TravelNote.query User = leancloud.Object.extend("_User") user = User.create_without_data(i.get("followee").id) user.fetch() query1.equal_to("author", user) query_list1 = query1.find() # j = TravelNote from i for j in query_list1: pics = [] content = j.get("content") if content != None: # picUrls_pre = re.findall('!\[.*?\]\(.*?\)', str(i.get("content"))) #MD的正则表达式 picUrls_pre = re.findall('<img.*?>', content) # html的提取img标签的正则表达式 else: picUrls_pre = [] # for url in picUrls_pre: # print url # c = re.compile('\]\(.*?\)', re.S) # v = c.findall(url)[0] # pics.append(v[2:-1]) # 读取src中的url,放在pics里 for group in picUrls_pre: match_obj = re.search('src="(.*?)"', group) picUrls = match_obj.groups() pics = list(picUrls) if len(pics) == 0: pics.append("http://lc-vqwqjioq.cn-n1.lcfile.com/72a3304b67086be0c5bd.jpg") # 查询author信息 User = leancloud.Object.extend("_User") user = User.create_without_data(j.get("author").id) user.fetch() avatar = user.get("avatar") if avatar: avatar_url = avatar.url else: avatar_url = None # 查询comment数量 Comment = leancloud.Object.extend("Comment") query = Comment.query query.equal_to("travelNote", j) query_list = query.find() commentNum = len(query_list) # 查询收藏数量 TravelNoteFav = leancloud.Object.extend('TravelNoteFav') query = TravelNoteFav.query query.equal_to("TravelNote", i) query_list = query.find() favNum = len(query_list) array.append({ "id": str(j.id), "image": pics, "title": j.get("title"), "nickname": user.get("nickname"), "avatar": avatar_url, "favNum": favNum, "replyNum": commentNum, "price": j.get("spend"), "date": j.get("createdAt").strftime("%Y-%m-%d %H:%M:%S"), "abstract": "XXXXXXX",#TODO "city": j.get("area") }) result = { "next": -1, "array": array } return result
def before_todo_save(todo): content = todo.get('content') if not content: raise LeanEngineError('内容不能为空') if len(content) >= 240: todo.set('content', content[:240] + ' ...')
def getBriefCityInfo(**params): weather_logo = { "晴": "https://cdn.heweather.com/cond_icon/100.png", "多云": "https://cdn.heweather.com/cond_icon/101.png", "少云": "https://cdn.heweather.com/cond_icon/102.png", "晴间多云": "https://cdn.heweather.com/cond_icon/103.png", "阴": "https://cdn.heweather.com/cond_icon/104.png", "有风": "https://cdn.heweather.com/cond_icon/200.png", "平静": "https://cdn.heweather.com/cond_icon/201.png", "微风": "https://cdn.heweather.com/cond_icon/202.png", "和风": "https://cdn.heweather.com/cond_icon/203.png", "清风": "https://cdn.heweather.com/cond_icon/204.png", "强风/劲风": "https://cdn.heweather.com/cond_icon/205.png", "疾风": "https://cdn.heweather.com/cond_icon/206.png", "大风": "https://cdn.heweather.com/cond_icon/207.png", "烈风": "https://cdn.heweather.com/cond_icon/208.png", "风暴": "https://cdn.heweather.com/cond_icon/209.png", "狂爆风": "https://cdn.heweather.com/cond_icon/210.png", "飓风": "https://cdn.heweather.com/cond_icon/211.png", "龙卷风": "https://cdn.heweather.com/cond_icon/212.png", "热带风暴": "https://cdn.heweather.com/cond_icon/213.png", "阵雨": "https://cdn.heweather.com/cond_icon/300.png", "强阵雨": "https://cdn.heweather.com/cond_icon/301.png", "雷阵雨": "https://cdn.heweather.com/cond_icon/302.png", "强雷阵雨": "https://cdn.heweather.com/cond_icon/303.png", "雷阵雨伴有冰雹": "https://cdn.heweather.com/cond_icon/304.png", "小雨": "https://cdn.heweather.com/cond_icon/305.png", "中雨": "https://cdn.heweather.com/cond_icon/306.png", "大雨": "https://cdn.heweather.com/cond_icon/307.png", "极端降雨": "https://cdn.heweather.com/cond_icon/308.png", "毛毛雨/细雨": "https://cdn.heweather.com/cond_icon/309.png", "暴雨": "https://cdn.heweather.com/cond_icon/310.png", "大暴雨": "https://cdn.heweather.com/cond_icon/311.png", "特大暴雨": "https://cdn.heweather.com/cond_icon/312.png", "冻雨": "https://cdn.heweather.com/cond_icon/313.png", "小到中雨": "https://cdn.heweather.com/cond_icon/314.png", "中到大雨": "https://cdn.heweather.com/cond_icon/315.png", "大到暴雨": "https://cdn.heweather.com/cond_icon/316.png", "暴雨到大暴雨": "https://cdn.heweather.com/cond_icon/317.png", "大暴雨到特大暴雨": "https://cdn.heweather.com/cond_icon/318.png", "雨": "https://cdn.heweather.com/cond_icon/399.png", "小雪": "https://cdn.heweather.com/cond_icon/400.png", "中雪": "https://cdn.heweather.com/cond_icon/401.png", "大雪": "https://cdn.heweather.com/cond_icon/402.png", "暴雪": "https://cdn.heweather.com/cond_icon/403.png", "雨夹雪": "https://cdn.heweather.com/cond_icon/404.png", "雨雪天气": "https://cdn.heweather.com/cond_icon/405.png", "阵雨夹雪": "https://cdn.heweather.com/cond_icon/406.png", "阵雪": "https://cdn.heweather.com/cond_icon/407.png", "小到中雪": "https://cdn.heweather.com/cond_icon/408.png", "中到大雪": "https://cdn.heweather.com/cond_icon/409.png", "大到暴雪": "https://cdn.heweather.com/cond_icon/410.png", "雪": "https://cdn.heweather.com/cond_icon/499.png", "薄雾": "https://cdn.heweather.com/cond_icon/500.png", "雾": "https://cdn.heweather.com/cond_icon/501.png", "霾": "https://cdn.heweather.com/cond_icon/502.png", "扬沙": "https://cdn.heweather.com/cond_icon/503.png", "浮尘": "https://cdn.heweather.com/cond_icon/504.png", "沙尘暴": "https://cdn.heweather.com/cond_icon/507.png", "强沙尘暴": "https://cdn.heweather.com/cond_icon/508.png", "浓雾": "https://cdn.heweather.com/cond_icon/509.png", "强浓雾": "https://cdn.heweather.com/cond_icon/510.png", "中度霾": "https://cdn.heweather.com/cond_icon/511.png", "重度霾": "https://cdn.heweather.com/cond_icon/512.png", "严重霾": "https://cdn.heweather.com/cond_icon/513.png", "大雾": "https://cdn.heweather.com/cond_icon/514.png", "特强浓雾": "https://cdn.heweather.com/cond_icon/515.png", "热": "https://cdn.heweather.com/cond_icon/900.png", "冷": "https://cdn.heweather.com/cond_icon/901.png", "未知": "https://cdn.heweather.com/cond_icon/999.png" } try: city = params['city'] except: raise LeanEngineError(501, 'Invalid argument.') # # 天气logo地址(旧版天气api,目前只使用天气图片img_url) # from weather_id import getWeatherId # weather_id = getWeatherId(city=city) # if weather_id != -1: # # url1 = "http://www.weather.com.cn/data/sk/" + weather_id + ".html" # url2 = "http://www.weather.com.cn/data/cityinfo/" + weather_id + ".html" # else: # return "No such city." # # r1 = requests.get(url1) # r2 = requests.get(url2) # # json_weather1 = json.loads(r1.content) # json_weather2 = json.loads(r2.content) # # temp = json_weather1["weatherinfo"]["temp"] # img1 = json_weather2["weatherinfo"]["img1"] # img_url = "http://m.weather.com.cn/img/b" + img1[1:] # 当前气温(新版天气api) tempurl = "https://www.sojson.com/open/api/weather/json.shtml?city=" + city r3 = requests.get(tempurl) json_weatherinfo = json.loads(r3.content) temp = json_weatherinfo["data"]["wendu"] weather_type = json_weatherinfo["data"]["forecast"][0]["type"] img_url = weather_logo.get(weather_type.encode("utf-8")) # 获得景点个数 Attraction = leancloud.Object.extend('Attraction') query = Attraction.query query.equal_to("area", city) query_list = query.find() attraction_num = len(query_list) # 主页背景图url AreaPic = leancloud.Object.extend('AreaPic') query = AreaPic.query query.equal_to("area", city) query_list = query.find() if len(query_list) != 0: areaPicUrl = query_list[0].get("pic").url else: areaPicUrl = None # 去过的人数 # TODO peopleBeenThereNum = 0 # 照片数量 # TODO photoNum = 0 result = { "temperature": temp, "weather_logo": img_url, "sceneryNum": attraction_num, "background": areaPicUrl, "peopleNum": peopleBeenThereNum, "photoNum": photoNum } return result