def changePwd(): if request.method == 'GET': if not session.get('username') == None: return render_template('user/changePwd.html', error='') else: return redirect(url_for('login')) elif request.method == 'POST': if not session.get('username') == None: username = session.get('username') oldpassword = request.form['oldpassword'] newpassword = request.form['newpassword'] newpassword1 = request.form['newpassword1'] (db, cursor) = connectdb() if cursor.execute( 'select id from user where username=%s and password=%s', [username, unicode(md5(oldpassword).hexdigest().upper())]) == 0: closedb(db, cursor) return render_template('user/changePwd.html', error='原始密码错误') elif not newpassword == newpassword1: closedb(db, cursor) return render_template('user/changePwd.html', error='两次密码输入不一致') else: cursor.execute( 'update user set password=%s where username=%s', [unicode(md5(newpassword).hexdigest().upper()), username]) closedb(db, cursor) return redirect(url_for('logout')) else: return redirect(url_for('login'))
def search(): recent = None hot = None (db, cursor) = connectdb() if not session.get('username') == None: # 获取当前用户的最近搜索记录 cursor.execute( "select * from search where username=%s and keyword!='' group by keyword,target order by timestamp desc limit 10", [session.get('username')]) recent = cursor.fetchall() # 获取热门搜索记录 cursor.execute( "select keyword, count(*) as count from search where timestamp > %s and keyword!='' and target='idea' group by keyword order by count(*) desc limit 10", [int(time.time()) - 3600 * 24 * 7]) hot = cursor.fetchall() # 获取各个类别的创意数量 cursor.execute( "select count(id) as count, category from idea where published=1 and locked=0 group by category" ) categoryStat = cursor.fetchall() temp = {} for item in categoryStat: temp[item['category']] = item['count'] categoryStat = temp closedb(db, cursor) return render_template('search/search.html', recent=recent, hot=hot, categoryStat=categoryStat)
def search(): recent = None hot = None (db,cursor) = connectdb() if not session.get('username') == None: # 获取当前用户的最近搜索记录 cursor.execute("select * from search where username=%s and keyword!='' group by keyword,target order by timestamp desc limit 10",[session.get('username')]) recent = cursor.fetchall() # 获取热门搜索记录 cursor.execute("select keyword, count(*) as count from search where timestamp > %s and keyword!='' and target='idea' group by keyword order by count(*) desc limit 10",[int(time.time())-3600*24*7]) hot = cursor.fetchall() # 获取各个类别的创意数量 cursor.execute("select count(id) as count, category from idea where published=1 and locked=0 group by category") categoryStat = cursor.fetchall() temp = {} for item in categoryStat: temp[item['category']] = item['count'] categoryStat = temp closedb(db,cursor) return render_template('search/search.html',recent=recent,hot=hot,categoryStat=categoryStat)
def api_chat_send(): data = request.form if validate(data['source'], data['token']): (db, cursor) = connectdb() # 验证成功 source = data['source'] target = data['target'] content = data['content'] timestamp = str(int(time.time())) cursor.execute("select nickname from user where username=%s", [target]) targetNickname = cursor.fetchone()['nickname'] cursor.execute("select nickname from user where username=%s", [source]) sourceNickname = cursor.fetchone()['nickname'] cursor.execute( "insert into chat(source,sourceNickname,target,targetNickname,content,timestamp) values(%s,%s,%s,%s,%s,%s)", [ source, sourceNickname, target, targetNickname, content, timestamp ]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_comment_praise(): (db, cursor) = connectdb() commentId = request.form['commentId'] if session.get('comments') == None: session['comments'] = {} if session['comments'].get(str(commentId)) == None: # 点赞评论 session['comments'][str(commentId)] = True cursor.execute('select praise from comment where id=%s', [commentId]) praise = int(cursor.fetchone()['praise']) + 1 cursor.execute('update comment set praise=%s where id=%s', [praise, commentId]) closedb(db, cursor) return json.dumps({"ok": True, "praise": praise, "action": "increase"}) else: # 取消赞评论 session['comments'].pop(str(commentId), None) cursor.execute('select praise from comment where id=%s', [commentId]) praise = int(cursor.fetchone()['praise']) - 1 cursor.execute('update comment set praise=%s where id=%s', [praise, commentId]) closedb(db, cursor) return json.dumps({"ok": True, "praise": praise, "action": "decrease"})
def changePwd(): if request.method == "GET": if not session.get("username") == None: return render_template("user/changePwd.html", error="") else: return redirect(url_for("login")) elif request.method == "POST": if not session.get("username") == None: username = session.get("username") oldpassword = request.form["oldpassword"] newpassword = request.form["newpassword"] newpassword1 = request.form["newpassword1"] (db, cursor) = connectdb() if ( cursor.execute( "select id from user where username=%s and password=%s", [username, unicode(md5(oldpassword).hexdigest().upper())], ) == 0 ): closedb(db, cursor) return render_template("user/changePwd.html", error="原始密码错误") elif not newpassword == newpassword1: closedb(db, cursor) return render_template("user/changePwd.html", error="两次密码输入不一致") else: cursor.execute( "update user set password=%s where username=%s", [unicode(md5(newpassword).hexdigest().upper()), username], ) closedb(db, cursor) return redirect(url_for("logout")) else: return redirect(url_for("login"))
def api_attachment_remove(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 attachmentId = data['attachmentId'] cursor.execute("select * from attachment where id=%s", [attachmentId]) attachment = cursor.fetchone() if attachment['username'] == data['username']: # 附件确实属于该用户 if (not attachment['fileType'] == 0) and (os.path.exists(WECOROOT + attachment['url'])): # 附件类型为图片或视频,则同时删除文件 os.remove(WECOROOT + attachment['url']) # 删除创意记录 cursor.execute('delete from attachment where id=%s', [attachmentId]) closedb(db, cursor) return json.dumps({"ok": True}) else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_idea_publish(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] cursor.execute("select owner from idea where id=%s", [ideaId]) # 创意确实属于用户 if cursor.fetchone()['owner'] == data['username']: cursor.execute("update idea set published=1 where id=%s", [ideaId]) closedb(db, cursor) return json.dumps({"ok": True}) # 创意不属于该用户 else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_idea_disfollow(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] username = data['username'] cursor.execute("select followIdeas from user where username = %s", [username]) followIdeas = cursor.fetchone()['followIdeas'] followIdeas = followIdeas.split(',') # 更新关注创意列表 if ideaId in followIdeas: followIdeas.remove(ideaId) temp = '' for item in followIdeas: if item == '': continue temp = temp + item + ',' followIdeas = temp[:-1] cursor.execute("update user set followIdeas = %s where username = %s", [followIdeas, username]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_idea_hot(): (db, cursor) = connectdb() offset = int(request.form['offset']) cursor.execute( 'select * from idea where published=1 and locked=0 order by praise desc, timestamp desc limit ' + str(offset * 10) + ',10') ideas = cursor.fetchall() closedb(db, cursor) # 转换时间戳 for item in ideas: temp = int(time.time()) - int(item['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp / 60) + 'm' elif temp < 3600 * 24: temp = str(temp / 3600) + 'h' else: temp = str(temp / (3600 * 24)) + 'd' item['timestamp'] = temp return json.dumps({"ok": True, "ideas": ideas})
def register(): if request.method == "GET": if not session.get("username") == None: return redirect(url_for("index")) else: return render_template("user/register.html") elif request.method == "POST": username = request.form["username"] password = request.form["password"] email = request.form["email"] (db, cursor) = connectdb() cursor.execute( "insert into user(username,nickname,password,email) values(%s,%s,%s,%s)", [username, username, unicode(md5(password).hexdigest().upper()), email], ) # 注册完毕,直接登录 cursor.execute( "update user set lastActive=%s, token=%s, TTL=100 where username=%s and email=%s", [str(int(time.time())), genKey(), username, email], ) cursor.execute("select username, token, lastActive from user where username=%s and email=%s", [username, email]) user = cursor.fetchone() closedb(db, cursor) session["username"] = user["username"] session["token"] = user["token"] session["lastActive"] = user["lastActive"] if not session.get("url") == None: url = session.get("url") session.pop("url", None) return redirect(url) else: return redirect(url_for("index"))
def idea_add_video(ideaId): if not session.get('username') == None: updateToken(session.get('username')) (db, cursor) = connectdb() image = request.files['content'] today = time.strftime('%Y%m%d', time.localtime(time.time())) filename = ( today + '_' + secure_filename(genKey()[:10] + '_' + image.filename)).lower() UPLOAD_FOLDER = '/static/uploads/video' filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) relapath = os.path.join(UPLOAD_FOLDER, filename) image.save(filepath) cursor.execute( "insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)", [ ideaId, 2, relapath, str(int(time.time())), session.get('username') ]) closedb(db, cursor) return redirect(url_for('idea', ideaId=ideaId)) else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def api_idea_recover(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] username = data['username'] cursor.execute("select owner from idea where id=%s", [ideaId]) owner = cursor.fetchone()['owner'] # 创意确实属于用户 if owner == username: cursor.execute("update idea set locked=0 where id=%s", [ideaId]) closedb(db, cursor) return json.dumps({"ok": True}) else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_attachment_edit(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 attachmentId = data['attachmentId'] cursor.execute("select * from attachment where id=%s", [attachmentId]) attachment = cursor.fetchone() if attachment['username'] == data['username']: # 附件确实属于该用户 cursor.execute("update attachment set url=%s where id=%s", [data['content'], attachmentId]) closedb(db, cursor) return json.dumps({"ok": True}) else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_idea_addText(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] cursor.execute("select owner from idea where id=%s", [ideaId]) # 创意确实属于用户 if cursor.fetchone()['owner'] == data['username']: timestamp = str(int(time.time())) cursor.execute( "insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)", [ideaId, 0, data['text'], timestamp, data['username']]) cursor.execute( "select id from attachment where ideaId=%s and fileType=0 and url=%s and timestamp=%s and username=%s", [ideaId, data['text'], timestamp, data['username']]) attachmentId = cursor.fetchone()['id'] closedb(db, cursor) return json.dumps({"ok": True, "attachmentId": attachmentId}) # 创意不属于该用户 else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def notice(): if session.get('username') == None: # 用户尚未登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login')) else: updateToken(session.get('username')) # 获取和当前用户有关的动态 (db, cursor) = connectdb() username = session.get('username') cursor.execute( "select * from activity where me=%s and checked=0 order by timestamp desc", [username]) activities = cursor.fetchall() activityCount = len(activities) cursor.execute( "select * from activity where me=%s order by timestamp desc", [username]) activities = cursor.fetchall() for item in activities: item['weekday'] = time.localtime(float(item['timestamp'])).tm_wday if item['weekday'] == 0: item['weekday'] = '星期一' elif item['weekday'] == 1: item['weekday'] = '星期二' elif item['weekday'] == 2: item['weekday'] = '星期三' elif item['weekday'] == 3: item['weekday'] = '星期四' elif item['weekday'] == 4: item['weekday'] = '星期五' elif item['weekday'] == 5: item['weekday'] = '星期六' elif item['weekday'] == 6: item['weekday'] = '星期日' item['timestamp'] = time.strftime( '%m-%d', time.localtime(float(item['timestamp']))) cursor.execute("update activity set checked=1 where me=%s", [username]) # 获取和当前用户有关的聊天信息 cursor.execute( "select source,sourceNickname,count(*) as count,content,timestamp from chat where target=%s and source!=%s and checked=0 group by source order by timestamp desc", [username, username]) chats = cursor.fetchall() for item in chats: item['timestamp'] = time.strftime( '%m-%d %H:%M', time.localtime(float(item['timestamp']))) cursor.execute("select portrait from user where username=%s", [item['source']]) item['portrait'] = cursor.fetchone()['portrait'] chatsCount = len(chats) closedb(db, cursor) return render_template('notice/notice.html', activities=activities, activityCount=activityCount, chats=chats, chatsCount=chatsCount)
def updateToken(username): (db,cursor) = connectdb() cursor.execute('select token,lastActive from user where username=%s',[username]) token = cursor.fetchone() closedb(db,cursor) if token['lastActive'] > session.get('lastActive') and (not token['token'] == session.get('token')): session['token'] = token['token'] session['lastActive'] = token['lastActive']
def api_idea_delete(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] username = data['username'] cursor.execute("select owner from idea where id=%s", [ideaId]) owner = cursor.fetchone()['owner'] # 创意确实属于用户 if owner == username: # 删除创意的缩略图 cursor.execute('select thumbnail,feature from idea where id=%s', [ideaId]) oldthumb = cursor.fetchone() print oldthumb oldfeature = oldthumb['feature'] oldthumb = oldthumb['thumbnail'] if (not oldthumb == '/static/img/idea.jpg') and ( os.path.exists(WECOROOT + oldthumb)): os.remove(WECOROOT + oldthumb) if (not oldfeature == '/static/img/idea.jpg') and ( os.path.exists(WECOROOT + oldfeature)): os.remove(WECOROOT + oldfeature) cursor.execute("delete from idea where id=%s", [ideaId]) cursor.execute("select ideas from user where username=%s", [username]) ideas = cursor.fetchone()['ideas'].split(',') # 从该用户的创意列表中去除该创意 if ideaId in ideas: ideas.remove(ideaId) temp = '' for item in ideas: if item == '': continue temp = temp + item + ',' ideas = temp[:-1] cursor.execute("update user set ideas = %s where username = %s", [ideas, username]) closedb(db, cursor) return json.dumps({"ok": True}) else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def login(): error = None if request.method == "GET": if not session.get("username") == None: return redirect(url_for("index")) else: return render_template("user/login.html", error=error) elif request.method == "POST": username = request.form["username"] if username == "": error = u"请输入账号或手机号" return render_template("user/login.html", error=error) password = request.form["password"] if password == "": error = u"请输入密码" return render_template("user/login.html", error=error) (db, cursor) = connectdb() if cursor.execute("select id from user where username=%s or email=%s", [username, username]) == 0: error = u"账号或手机号不存在" closedb(db, cursor) return render_template("user/login.html", error=error) elif ( cursor.execute( "select id from user where username=%s and password=%s", [username, unicode(md5(password).hexdigest().upper())], ) + cursor.execute( "select id from user where email=%s and password=%s", [username, unicode(md5(password).hexdigest().upper())], ) == 0 ): error = u"账号或密码错误" closedb(db, cursor) return render_template("user/login.html", error=error) else: cursor.execute( "update user set lastActive=%s,token=%s where username=%s or email=%s", [str(int(time.time())), genKey(), username, username], ) cursor.execute( "select username,lastActive,token from user where username=%s or email=%s", [username, username] ) user = cursor.fetchone() session["username"] = user["username"] session["token"] = user["token"] session["lastActive"] = user["lastActive"] closedb(db, cursor) if not session.get("url") == None: url = session.get("url") session.pop("url", None) return redirect(url) else: return redirect(url_for("index"))
def updateToken(username): (db, cursor) = connectdb() cursor.execute('select token,lastActive from user where username=%s', [username]) token = cursor.fetchone() closedb(db, cursor) if token['lastActive'] > session.get('lastActive') and ( not token['token'] == session.get('token')): session['token'] = token['token'] session['lastActive'] = token['lastActive']
def search_category(): (db, cursor) = connectdb() category = request.args.get('category') pageId = request.args.get('pageId') numPerPage = 10 # 计算该分类的创意数量 cursor.execute( 'select count(*) as count from idea where category=%s and published=1 and locked=0', [category]) count = cursor.fetchone()['count'] # 获取该分类的创意并分页 cursor.execute( 'select * from idea where category=%s and published=1 and locked=0 order by praise desc, timestamp desc limit %s,%s', [category, int(pageId) * numPerPage, numPerPage]) ideas = cursor.fetchall() # 转换时间戳 for item in ideas: temp = int(time.time()) - int(item['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp / 60) + 'm' elif temp < 3600 * 24: temp = str(temp / 3600) + 'h' else: temp = str(temp / (3600 * 24)) + 'd' item['timestamp'] = temp # 计算分页信息 start = int(pageId) - 3 end = int(pageId) + 3 total = int(math.ceil(float(count) / numPerPage)) - 1 if start < 0: start = 0 if end > total: end = total pages = [] for i in xrange(start, end + 1): pages.append(i) closedb(db, cursor) return render_template('search/search_category.html', category=category, count=count, start=start, end=end, current=int(pageId), pages=pages, total=total, ideas=ideas)
def api_user_follow(): data = request.form if validate(data['source'], data['token']): (db, cursor) = connectdb() # 验证通过 source = data['source'] target = data['target'] cursor.execute( "select nickname,followUsers from user where username = %s", [source]) nickname = cursor.fetchone() followUsers = nickname['followUsers'] nickname = nickname['nickname'] followUsers = followUsers.split(',') # 更新双方关注用户列表 if not target in followUsers: followUsers.append(target) temp = '' for item in followUsers: if item == '': continue temp = temp + item + ',' followUsers = temp[:-1] cursor.execute("update user set followUsers = %s where username = %s", [followUsers, source]) cursor.execute("select fans from user where username = %s", [target]) fans = cursor.fetchone()['fans'] fans = fans.split(',') if not source in fans: fans.append(source) temp = '' for item in fans: if item == '': continue temp = temp + item + ',' fans = temp[:-1] cursor.execute("update user set fans = %s where username = %s", [fans, target]) # 添加类别1动态,我被别人关注了 cursor.execute( "insert into activity(me,other,otherNickname,activityType,timestamp) values(%s,%s,%s,%s,%s)", [target, source, nickname, 1, str(int(time.time()))]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def idea_add_text(ideaId): if not session.get('username') == None: updateToken(session.get('username')) (db,cursor) = connectdb() text = request.form['content'] cursor.execute("insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)",[ideaId,0,text,str(int(time.time())), session.get('username')]) closedb(db,cursor) return redirect(url_for('idea', ideaId=ideaId)) else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def login(): error = None if request.method == 'GET': if not session.get('username') == None: return redirect(url_for('index')) else: return render_template('user/login.html', error=error) elif request.method == 'POST': username = request.form['username'] if username == '': error = u"请输入账号或手机号" return render_template('user/login.html', error=error) password = request.form['password'] if password == '': error = u"请输入密码" return render_template('user/login.html', error=error) (db, cursor) = connectdb() if cursor.execute("select id from user where username=%s or email=%s", [username, username]) == 0: error = u"账号或手机号不存在" closedb(db, cursor) return render_template('user/login.html', error=error) elif cursor.execute( "select id from user where username=%s and password=%s", [username, unicode(md5(password).hexdigest().upper()) ]) + cursor.execute( "select id from user where email=%s and password=%s", [username, unicode(md5(password).hexdigest().upper())]) == 0: error = u"账号或密码错误" closedb(db, cursor) return render_template('user/login.html', error=error) else: cursor.execute( "update user set lastActive=%s,token=%s where username=%s or email=%s", [str(int(time.time())), genKey(), username, username]) cursor.execute( "select username,lastActive,token from user where username=%s or email=%s", [username, username]) user = cursor.fetchone() session['username'] = user['username'] session['token'] = user['token'] session['lastActive'] = user['lastActive'] closedb(db, cursor) if not session.get('url') == None: url = session.get('url') session.pop('url', None) return redirect(url) else: return redirect(url_for('index'))
def api_user_exist_email(): (db,cursor) = connectdb() data = request.form count = cursor.execute("select email from user where email = %s", [data['email']]) closedb(db,cursor) if count > 0: return json.dumps({"ok": True, "exist": True}) else: return json.dumps({"ok": True, "exist": False})
def api_user_exist_email(): (db, cursor) = connectdb() data = request.form count = cursor.execute("select email from user where email = %s", [data['email']]) closedb(db, cursor) if count > 0: return json.dumps({"ok": True, "exist": True}) else: return json.dumps({"ok": True, "exist": False})
def chat(username): if session.get('username') == None: # 用户尚未登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login')) else: updateToken(session.get('username')) (db, cursor) = connectdb() # 用户已经登陆,获取所有聊天记录 me = session.get('username') cursor.execute( "select * from chat where (source=%s and target=%s) or (source=%s and target=%s) order by timestamp desc limit 100", [username, me, me, username]) chats = cursor.fetchall() chats = sorted(chats, key=lambda x: (x['timestamp'])) # 合并聊天时间戳 currentTime = 0 for item in chats: temp = float(item['timestamp']) if not currentTime == 0 and float( item['timestamp']) - currentTime < 600: item['timestamp'] = '' else: item['timestamp'] = (time.strftime( '%m月%d日 %H:%M', time.localtime(float(item['timestamp'])))).lstrip('0') currentTime = temp # 将消息设置为已读 cursor.execute( 'update chat set checked=1 where source=%s and target=%s', [username, me]) # 获取用户头像和昵称 cursor.execute("select portrait from user where username=%s", [me]) myPortrait = cursor.fetchone()['portrait'] cursor.execute("select nickname,portrait from user where username=%s", [username]) portrait = cursor.fetchone() targetNickname = portrait['nickname'] portrait = portrait['portrait'] closedb(db, cursor) return render_template('notice/chat.html', target=username, targetNickname=targetNickname, chats=chats, myPortrait=myPortrait, portrait=portrait)
def idea_add_text(ideaId): if not session.get('username') == None: updateToken(session.get('username')) (db, cursor) = connectdb() text = request.form['content'] cursor.execute( "insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)", [ideaId, 0, text, str(int(time.time())), session.get('username')]) closedb(db, cursor) return redirect(url_for('idea', ideaId=ideaId)) else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def api_idea_follow(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] username = data['username'] cursor.execute( "select nickname,followIdeas from user where username = %s", [username]) nickname = cursor.fetchone() followIdeas = nickname['followIdeas'] nickname = nickname['nickname'] # 更新关注创意列表 followIdeas = followIdeas.split(',') if not ideaId in followIdeas: followIdeas.append(ideaId) temp = '' for item in followIdeas: if item == '': continue temp = temp + item + ',' followIdeas = temp[:-1] cursor.execute("update user set followIdeas = %s where username = %s", [followIdeas, username]) # 添加类别2动态,我的创意被别人关注了 cursor.execute("select title,owner from idea where id=%s", [ideaId]) owner = cursor.fetchone() ideaTitle = owner['title'] owner = owner['owner'] cursor.execute( "insert into activity(me,other,otherNickname,ideaId,ideaTitle,activityType,timestamp) values(%s,%s,%s,%s,%s,%s,%s)", [ owner, username, nickname, ideaId, ideaTitle, 2, str(int(time.time())) ]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_user_follow(): data = request.form if validate(data['source'], data['token']): (db,cursor) = connectdb() # 验证通过 source = data['source'] target = data['target'] cursor.execute("select nickname,followUsers from user where username = %s", [source]) nickname = cursor.fetchone() followUsers = nickname['followUsers'] nickname = nickname['nickname'] followUsers = followUsers.split(',') # 更新双方关注用户列表 if not target in followUsers: followUsers.append(target) temp = '' for item in followUsers: if item == '': continue temp = temp + item + ',' followUsers = temp[:-1] cursor.execute("update user set followUsers = %s where username = %s", [followUsers, source]) cursor.execute("select fans from user where username = %s", [target]) fans = cursor.fetchone()['fans'] fans = fans.split(',') if not source in fans: fans.append(source) temp = '' for item in fans: if item == '': continue temp = temp + item + ',' fans = temp[:-1] cursor.execute("update user set fans = %s where username = %s", [fans, target]) # 添加类别1动态,我被别人关注了 cursor.execute("insert into activity(me,other,otherNickname,activityType,timestamp) values(%s,%s,%s,%s,%s)",[target,source,nickname,1,str(int(time.time()))]) closedb(db,cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def notice(): if session.get('username') == None: # 用户尚未登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login')) else: updateToken(session.get('username')) # 获取和当前用户有关的动态 (db,cursor) = connectdb() username = session.get('username') cursor.execute("select * from activity where me=%s and checked=0 order by timestamp desc",[username]) activities = cursor.fetchall() activityCount = len(activities) cursor.execute("select * from activity where me=%s order by timestamp desc",[username]) activities = cursor.fetchall() for item in activities: item['weekday'] = time.localtime(float(item['timestamp'])).tm_wday if item['weekday'] == 0: item['weekday'] = '星期一' elif item['weekday'] == 1: item['weekday'] = '星期二' elif item['weekday'] == 2: item['weekday'] = '星期三' elif item['weekday'] == 3: item['weekday'] = '星期四' elif item['weekday'] == 4: item['weekday'] = '星期五' elif item['weekday'] == 5: item['weekday'] = '星期六' elif item['weekday'] == 6: item['weekday'] = '星期日' item['timestamp'] = time.strftime('%m-%d', time.localtime(float(item['timestamp']))) cursor.execute("update activity set checked=1 where me=%s",[username]) # 获取和当前用户有关的聊天信息 cursor.execute("select source,sourceNickname,count(*) as count,content,timestamp from chat where target=%s and source!=%s and checked=0 group by source order by timestamp desc",[username,username]) chats = cursor.fetchall() for item in chats: item['timestamp'] = time.strftime('%m-%d %H:%M', time.localtime(float(item['timestamp']))) cursor.execute("select portrait from user where username=%s",[item['source']]) item['portrait'] = cursor.fetchone()['portrait'] chatsCount = len(chats) closedb(db,cursor) return render_template('notice/notice.html',activities=activities,activityCount=activityCount,chats=chats,chatsCount=chatsCount)
def idea_add_video(ideaId): if not session.get('username') == None: updateToken(session.get('username')) (db,cursor) = connectdb() image = request.files['content'] today = time.strftime('%Y%m%d', time.localtime(time.time())) filename = (today + '_' + secure_filename(genKey()[:10] + '_' + image.filename)).lower() UPLOAD_FOLDER = '/static/uploads/video' filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) relapath = os.path.join(UPLOAD_FOLDER, filename) image.save(filepath) cursor.execute("insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)",[ideaId,2,relapath,str(int(time.time())), session.get('username')]) closedb(db,cursor) return redirect(url_for('idea', ideaId=ideaId)) else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def api_idea_addImg(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] cursor.execute("select owner from idea where id=%s", [ideaId]) # 用户和创意匹配 if cursor.fetchone()['owner'] == data['username']: # 添加图片并保存至上传路径 imgBase = data['image'] imgBase = imgBase[imgBase.find('base64') + 7:] imageData = base64.b64decode(imgBase) today = time.strftime('%Y%m%d%H', time.localtime(time.time())) filename = today + '_' + genKey()[:10] + '.jpg' UPLOAD_FOLDER = '/static/uploads/img' filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) relapath = os.path.join(UPLOAD_FOLDER, filename) imageFile = open(filepath, 'wb') imageFile.write(imageData) imageFile.close() timestamp = str(int(time.time())) cursor.execute( "insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)", [ideaId, 1, relapath, timestamp, data['username']]) cursor.execute( "select id from attachment where ideaId=%s and fileType=1 and url=%s and timestamp=%s and username=%s", [ideaId, relapath, timestamp, data['username']]) attachmentId = cursor.fetchone()['id'] closedb(db, cursor) return json.dumps({"ok": True, "attachmentId": attachmentId}) else: closedb(db, cursor) return json.dumps({"ok": False, "error": "invalid token"}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_user_disfollow(): data = request.form if validate(data['source'], data['token']): (db, cursor) = connectdb() # 验证成功 source = data['source'] target = data['target'] # 更新双方关注列表 cursor.execute("select followUsers from user where username = %s", [source]) followUsers = cursor.fetchone()['followUsers'] followUsers = followUsers.split(',') if target in followUsers: followUsers.remove(target) temp = '' for item in followUsers: if item == '': continue temp = temp + item + ',' followUsers = temp[:-1] cursor.execute("update user set followUsers = %s where username = %s", [followUsers, source]) cursor.execute("select fans from user where username = %s", [target]) fans = cursor.fetchone()['fans'] fans = fans.split(',') if source in fans: fans.remove(source) temp = '' for item in fans: if item == '': continue temp = temp + item + ',' fans = temp[:-1] cursor.execute("update user set fans = %s where username = %s", [fans, target]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def api_idea_comment(): data = request.form if validate(data['username'], data['token']): (db, cursor) = connectdb() # 验证通过 ideaId = data['ideaId'] username = data['username'] timestamp = str(int(time.time())) content = data['content'] cursor.execute('select nickname,portrait from user where username=%s', [username]) nickname = cursor.fetchone() portrait = nickname['portrait'] nickname = nickname['nickname'] # 新增评论记录 cursor.execute( "insert into comment(username,nickname,portrait,ideaId,timestamp,content) values(%s,%s,%s,%s,%s,%s)", [username, nickname, portrait, ideaId, timestamp, content]) cursor.execute("select commentCount from idea where id=%s", [ideaId]) commentCount = int(cursor.fetchone()['commentCount']) + 1 cursor.execute("update idea set commentCount=%s where id=%s", [commentCount, ideaId]) # 添加类别3动态,我的创意被别人评论了 cursor.execute("select title,owner from idea where id=%s", [ideaId]) owner = cursor.fetchone() ideaTitle = owner['title'] owner = owner['owner'] cursor.execute( "insert into activity(me,other,otherNickname,ideaId,ideaTitle,comment,activityType,timestamp) values(%s,%s,%s,%s,%s,%s,%s,%s)", [ owner, username, nickname, ideaId, ideaTitle, content, 3, str(int(time.time())) ]) closedb(db, cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def search_category(): (db,cursor) = connectdb() category = request.args.get('category') pageId = request.args.get('pageId') numPerPage = 10 # 计算该分类的创意数量 cursor.execute('select count(*) as count from idea where category=%s and published=1 and locked=0',[category]) count = cursor.fetchone()['count'] # 获取该分类的创意并分页 cursor.execute('select * from idea where category=%s and published=1 and locked=0 order by praise desc, timestamp desc limit %s,%s',[category,int(pageId)*numPerPage,numPerPage]) ideas = cursor.fetchall() # 转换时间戳 for item in ideas: temp = int(time.time()) - int(item['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp/60) + 'm' elif temp < 3600 * 24: temp = str(temp/3600) + 'h' else: temp = str(temp/(3600*24)) + 'd' item['timestamp'] = temp # 计算分页信息 start = int(pageId) - 3 end = int(pageId) + 3 total = int(math.ceil(float(count) / numPerPage)) - 1 if start < 0: start = 0 if end > total: end = total pages = [] for i in xrange(start, end + 1): pages.append(i) closedb(db,cursor) return render_template('search/search_category.html', category=category, count=count, start=start, end=end, current=int(pageId), pages=pages, total=total, ideas=ideas)
def api_user_disfollow(): data = request.form if validate(data['source'], data['token']): (db,cursor) = connectdb() # 验证成功 source = data['source'] target = data['target'] # 更新双方关注列表 cursor.execute("select followUsers from user where username = %s", [source]) followUsers = cursor.fetchone()['followUsers'] followUsers = followUsers.split(',') if target in followUsers: followUsers.remove(target) temp = '' for item in followUsers: if item == '': continue temp = temp + item + ',' followUsers = temp[:-1] cursor.execute("update user set followUsers = %s where username = %s", [followUsers, source]) cursor.execute("select fans from user where username = %s", [target]) fans = cursor.fetchone()['fans'] fans = fans.split(',') if source in fans: fans.remove(source) temp = '' for item in fans: if item == '': continue temp = temp + item + ',' fans = temp[:-1] cursor.execute("update user set fans = %s where username = %s", [fans, target]) closedb(db,cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def index(): (db,cursor) = connectdb() cursor.execute('select * from idea where published=1 and locked=0 order by praise desc, timestamp desc limit 10') # 转换时间戳 ideas = cursor.fetchall() for item in ideas: temp = int(time.time()) - int(item['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp/60) + 'm' elif temp < 3600 * 24: temp = str(temp/3600) + 'h' else: temp = str(temp/(3600*24)) + 'd' item['timestamp'] = temp closedb(db,cursor) return render_template('index/index.html', ideas=ideas, hot=True)
def validate(username, token): (db,cursor) = connectdb() count = cursor.execute("select lastActive, TTL from user where username = %s and token = %s", [username, token]) if count == 0: closedb(db,cursor) return False else: closedb(db,cursor) return True user = cursor.fetchone() lastActive = user['lastActive'] TTL = user['TTL'] interval = 3600*24*7 # token有效期为7天,调用次数为100 if int(time.time()) - int(lastActive) > interval or TTL < 1: return False else: TTL = TTL - 1 cursor.execute("update user set TTL = %s where username = %s", [str(TTL), username]) return True
def api_idea_praise(): ideaId = request.form['ideaId'] if (not session.get('ideas') == None) and (not session['ideas'].get( str(ideaId)) == None): (db, cursor) = connectdb() if session['ideas'][str(ideaId)] == 0: # 点赞 cursor.execute('select praise from idea where id=%s', [ideaId]) praise = int(cursor.fetchone()['praise']) + 1 cursor.execute('update idea set praise=%s where id=%s', [praise, ideaId]) session['ideas'][str(ideaId)] = 1 closedb(db, cursor) return json.dumps({ "ok": True, "praise": praise, "action": "increase" }) else: # 取消赞 cursor.execute('select praise from idea where id=%s', [ideaId]) praise = int(cursor.fetchone()['praise']) - 1 cursor.execute('update idea set praise=%s where id=%s', [praise, ideaId]) session['ideas'][str(ideaId)] = 0 closedb(db, cursor) return json.dumps({ "ok": True, "praise": praise, "action": "decrease" }) else: return json.dumps({"ok": False})
def chat(username): if session.get('username') == None: # 用户尚未登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login')) else: updateToken(session.get('username')) (db,cursor) = connectdb() # 用户已经登陆,获取所有聊天记录 me = session.get('username') cursor.execute("select * from chat where (source=%s and target=%s) or (source=%s and target=%s) order by timestamp desc limit 100",[username,me,me,username]) chats = cursor.fetchall() chats = sorted(chats, key=lambda x:(x['timestamp'])) # 合并聊天时间戳 currentTime = 0 for item in chats: temp = float(item['timestamp']) if not currentTime == 0 and float(item['timestamp']) - currentTime < 600: item['timestamp'] = '' else: item['timestamp'] = (time.strftime('%m月%d日 %H:%M', time.localtime(float(item['timestamp'])))).lstrip('0') currentTime = temp # 将消息设置为已读 cursor.execute('update chat set checked=1 where source=%s and target=%s',[username,me]) # 获取用户头像和昵称 cursor.execute("select portrait from user where username=%s",[me]) myPortrait = cursor.fetchone()['portrait'] cursor.execute("select nickname,portrait from user where username=%s",[username]) portrait = cursor.fetchone() targetNickname = portrait['nickname'] portrait = portrait['portrait'] closedb(db,cursor) return render_template('notice/chat.html',target=username,targetNickname=targetNickname,chats=chats,myPortrait=myPortrait,portrait=portrait)
def index(): (db, cursor) = connectdb() cursor.execute( 'select * from idea where published=1 and locked=0 order by praise desc, timestamp desc limit 10' ) # 转换时间戳 ideas = cursor.fetchall() for item in ideas: temp = int(time.time()) - int(item['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp / 60) + 'm' elif temp < 3600 * 24: temp = str(temp / 3600) + 'h' else: temp = str(temp / (3600 * 24)) + 'd' item['timestamp'] = temp closedb(db, cursor) return render_template('index/index.html', ideas=ideas, hot=True)
def api_chat_send(): data = request.form if validate(data['source'], data['token']): (db,cursor) = connectdb() # 验证成功 source = data['source'] target = data['target'] content = data['content'] timestamp = str(int(time.time())) cursor.execute("select nickname from user where username=%s",[target]) targetNickname = cursor.fetchone()['nickname'] cursor.execute("select nickname from user where username=%s",[source]) sourceNickname = cursor.fetchone()['nickname'] cursor.execute("insert into chat(source,sourceNickname,target,targetNickname,content,timestamp) values(%s,%s,%s,%s,%s,%s)",[source,sourceNickname,target,targetNickname,content,timestamp]) closedb(db,cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def register(): if request.method == 'GET': if not session.get('username') == None: return redirect(url_for('index')) else: return render_template('user/register.html') elif request.method == 'POST': username = request.form['username'] password = request.form['password'] email = request.form['email'] (db, cursor) = connectdb() cursor.execute( "insert into user(username,nickname,password,email) values(%s,%s,%s,%s)", [ username, username, unicode(md5(password).hexdigest().upper()), email ]) # 注册完毕,直接登录 cursor.execute( "update user set lastActive=%s, token=%s, TTL=100 where username=%s and email=%s", [str(int(time.time())), genKey(), username, email]) cursor.execute( "select username, token, lastActive from user where username=%s and email=%s", [username, email]) user = cursor.fetchone() closedb(db, cursor) session['username'] = user['username'] session['token'] = user['token'] session['lastActive'] = user['lastActive'] if not session.get('url') == None: url = session.get('url') session.pop('url', None) return redirect(url) else: return redirect(url_for('index'))
def validate(username, token): (db, cursor) = connectdb() count = cursor.execute( "select lastActive, TTL from user where username = %s and token = %s", [username, token]) if count == 0: closedb(db, cursor) return False else: closedb(db, cursor) return True user = cursor.fetchone() lastActive = user['lastActive'] TTL = user['TTL'] interval = 3600 * 24 * 7 # token有效期为7天,调用次数为100 if int(time.time()) - int(lastActive) > interval or TTL < 1: return False else: TTL = TTL - 1 cursor.execute("update user set TTL = %s where username = %s", [str(TTL), username]) return True
def idea(ideaId): # 如果创意已被锁定,则给出错误提示 # TO DO if not session.get('username') == None: updateToken(session.get('username')) (db,cursor) = connectdb() # 缓存该创意的阅读、点赞等用户行为 if session.get('ideas') == None: session['ideas'] = {} # 阅读量+1 if not session['ideas'].has_key(str(ideaId)): cursor.execute('select readCount from idea where id=%s', [ideaId]) readCount = int(cursor.fetchone()['readCount']) + 1 cursor.execute('update idea set readCount=%s where id=%s', [readCount,ideaId]) session['ideas'][str(ideaId)] = 0 # 获取创意信息 cursor.execute('select * from idea where id=%s', [ideaId]) idea = cursor.fetchone() idea['timestamp'] = time.strftime('%m-%d %H:%M', time.localtime(float(idea['timestamp']))) # 判断当前用户是否已经喜欢该创意 liked = False username = session.get('username') if (not username == None) and (not username == idea['owner']): cursor.execute('select followIdeas from user where username=%s',[username]) if ideaId in cursor.fetchone()['followIdeas'].split(','): liked = True else: liked = False # 获取该创意所有附件 cursor.execute("select * from attachment where ideaId=%s order by timestamp asc",[ideaId]) attachments = cursor.fetchall() for item in attachments: item['timestamp'] = time.strftime('%m-%d %H:%M', time.localtime(float(item['timestamp']))) if item['fileType'] == 0: item['url'] = item['url'].split('\n') temp = [] for i in item['url']: i = i.strip() if not i == '': temp.append(i) item['url'] = temp if item['fileType'] == 2: temp = item['url'].rfind('.') item['suffix'] = item['url'][(temp+1):] # 获取该创意所有评论 cursor.execute("select * from comment where ideaId=%s order by praise desc, timestamp desc", [ideaId]) comments = cursor.fetchall() for item in comments: item['timestamp'] = time.strftime('%m-%d %H:%M', time.localtime(float(item['timestamp']))) commentsCount = len(comments) # 获取该创意发起人粉丝人数 cursor.execute("select nickname,fans from user where username=%s",[idea['owner']]) user = cursor.fetchone() fans = len(user['fans'].split(',')) idea['nickname'] = user['nickname'] # 获取热门标签以供编辑 category = ['社会创新','设计','生活','城市','娱乐','健康','旅行','教育','运动','产品','艺术','科技','工程','广告','其他'] hotTags = {} for item in category: cursor.execute("select tag from ideaTagStat where category=%s and tag!=%s order by count desc limit 10",[item,item]) hotTags[item] = cursor.fetchall() if not session.get('username') == None: cursor.execute("update user set TTL=100 where username=%s",[session.get('username')]) closedb(db,cursor) return render_template('idea/idea.html', idea=idea, liked=liked, attachments=attachments, comments=comments, commentsCount=commentsCount, fans=fans, hotTags=hotTags)
def api_user_edit(): data = request.form if validate(data['username'], data['token']): (db,cursor) = connectdb() # 验证成功 nickname = data['nickname'] gender = data['gender'] tags = data['tags'] description = data['description'] email = data['email'] wechat = data['wechat'] hobby = data['hobby'] location = data['location'] # 统计用户tag次数 for tag in tags.split(' '): if tag == '': continue cursor.execute("select count from userTagStat where tag=%s and gender=%s",[tag,gender]) record = cursor.fetchone() if record == None: cursor.execute("insert into userTagStat(tag,gender,count) values(%s,%s,1)",[tag,gender]) else: count = int(record['count']) + 1 cursor.execute("update userTagStat set count=%s where tag=%s and gender=%s",[count,tag,gender]) cursor.execute("update user set nickname=%s, gender=%s,tags=%s,description=%s,email=%s,wechat=%s,hobby=%s,location=%s where username=%s", [nickname,gender,tags,description,email,wechat,hobby,location,data['username']]) # 处理用户头像 if data.has_key('portrait'): # 生成新的头像图片 portrait = data['portrait'] portrait = portrait[portrait.find('base64')+7:] imageData = base64.b64decode(portrait) today = time.strftime('%Y%m%d%H', time.localtime(time.time())) filename = today + '_' + genKey()[:10] + '.jpg' UPLOAD_FOLDER = '/static/uploads/img' filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) relapath = os.path.join(UPLOAD_FOLDER, filename) imageFile = open(filepath,'wb') imageFile.write(imageData) imageFile.close() # 删除旧的头像图片 cursor.execute('select portrait from user where username=%s',[data['username']]) oldportrait = cursor.fetchone()['portrait'] if (not oldportrait == '/static/img/user.png') and (os.path.exists(WECOROOT + oldportrait)): os.remove(WECOROOT + oldportrait) cursor.execute("update user set portrait=%s where username=%s",[relapath,data['username']]) # 更新该用户所有创意的头像路径 cursor.execute("select ideas from user where username=%s",[data['username']]) myIdeas = cursor.fetchone()['ideas'].split(',') for item in myIdeas: if item == '': continue cursor.execute("update idea set portrait=%s where id=%s",[relapath,item]) # 更新该用户所有评论的头像路径 cursor.execute("update comment set portrait=%s where username=%s",[relapath,data['username']]) closedb(db,cursor) return json.dumps({"ok": True}) else: # 验证失败 return json.dumps({"ok": False, "error": "invalid token"})
def idea_new(): if request.method == 'GET': # 用户已经登陆 if not session.get('username') == None: updateToken(session.get('username')) # 获取热门标签 category = ['社会创新','设计','生活','城市','娱乐','健康','旅行','教育','运动','产品','艺术','科技','工程','广告','其他'] hotTags = {} (db,cursor) = connectdb() for item in category: cursor.execute("select tag from ideaTagStat where category=%s and tag!=%s order by count desc limit 10",[item,item]) hotTags[item] = cursor.fetchall() closedb(db,cursor) return render_template('idea/idea_new.html',hotTags=hotTags) # 用户尚未登录 else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login')) elif request.method == 'POST': # 用户已经登陆 if not session.get('username') == None: # 新增创意数据 (db,cursor) = connectdb() username = request.form['username'] title = request.form['title'] category = request.form['category'] tags = request.form['tags'] # content = request.form['content'] timestamp = str(int(time.time())) cursor.execute('select nickname,portrait from user where username=%s',[username]) portrait = cursor.fetchone() nickname = portrait['nickname'] portrait = portrait['portrait'] # 保存封面图片 # imgBase = request.form['thumbnail'] # imgBase = imgBase[imgBase.find('base64')+7:] # imageData = base64.b64decode(imgBase) # today = time.strftime('%Y%m%d%H', time.localtime(time.time())) # temp = genKey()[:10] # filename = today + '_' + temp + '.jpg' # UPLOAD_FOLDER = '/static/uploads/img' # filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) # relapath = os.path.join(UPLOAD_FOLDER, filename) # imageFile = open(filepath,'wb') # imageFile.write(imageData) # imageFile.close() # imgBase = request.form['feature'] # imgBase = imgBase[imgBase.find('base64')+7:] # imageData = base64.b64decode(imgBase) # filename = today + '_' + temp + '_thumb.jpg' # filepath = os.path.join(WECOROOT + UPLOAD_FOLDER, filename) # relapath1 = os.path.join(UPLOAD_FOLDER, filename) # imageFile = open(filepath,'wb') # imageFile.write(imageData) # imageFile.close() # 新增创意并添加内容 # cursor.execute('insert into idea(title,category,tags,timestamp,owner,nickname,portrait,thumbnail,feature) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)',[title,category,tags,timestamp,username,nickname,portrait,relapath,relapath1]) cursor.execute('insert into idea(title,category,tags,timestamp,owner,nickname,portrait) values(%s,%s,%s,%s,%s,%s,%s)',[title,category,tags,timestamp,username,nickname,portrait]) # 获取新增创意id cursor.execute('select id from idea where title=%s and category=%s and tags=%s and timestamp=%s and owner=%s',[title,category,tags,timestamp,username]) ideaId = cursor.fetchone()['id'] # cursor.execute("insert into attachment(ideaId,fileType,url,timestamp,username) values(%s,%s,%s,%s,%s)",[ideaId,0,content,str(int(time.time())), username]) # 将该id添加至用户的创意列表中 cursor.execute('select ideas from user where username=%s',[username]) ideas = cursor.fetchone()['ideas'] ideas = ideas + ',' + str(ideaId) ideas = ideas.lstrip(',') cursor.execute('update user set ideas=%s where username=%s',[ideas,username]) # 统计创意tag次数 for tag in tags.split(' '): if tag == '': continue cursor.execute("select count from ideaTagStat where tag=%s and category=%s",[tag,category]) record = cursor.fetchone() if record == None: cursor.execute("insert into ideaTagStat(tag,category,count) values(%s,%s,1)",[tag,category]) else: count = int(record['count']) + 1 cursor.execute("update ideaTagStat set count=%s where tag=%s and category=%s",[count,tag,category]) closedb(db,cursor) return json.dumps({"ideaId": ideaId}) # 用户尚未登录 else: session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def home(): if not session.get('username') == None: updateToken(session.get('username')) (db,cursor) = connectdb() # 用户已登陆 cursor.execute('select * from user where username=%s', [session.get('username')]) user = cursor.fetchone() # 获取所关注的其他用户名单 followUserStr = user['followUsers'] # 获取热门标签以供编辑 hotTags = {} cursor.execute("select tag from userTagStat where gender=1 order by count desc limit 10") hotTags['male'] = cursor.fetchall() cursor.execute("select tag from userTagStat where gender=0 order by count desc limit 10") hotTags['female'] = cursor.fetchall() # 获取用户的创意 ideas = user['ideas'] ideasCount = 0 if not ideas == '': cursor.execute('select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (ideas)) ideas = cursor.fetchall() ideasCount = len(ideas) else: ideas = None # # 获取用户待删除的创意 # trashs = user['ideas'] # if not trashs == '': # cursor.execute('select id,title,feature from idea where id in (%s) and locked=1' % (trashs)) # trashs = cursor.fetchall() # else: # trashs = None # 获取用户喜欢的创意 followIdeas = user['followIdeas'] followIdeasCount = 0 if not followIdeas == '': cursor.execute('select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (followIdeas)) followIdeas = cursor.fetchall() followIdeasCount = len(followIdeas) else: followIdeas = None # 获取用户关注的其他用户 followUsers = user['followUsers'] followUsersCount = 0 if not followUsers == '': followUsers = followUsers.split(',') temp = '' for item in followUsers: temp = temp + '"' + item + '",' followUsers = temp[:-1] cursor.execute('select username,nickname,portrait,fans from user where username in (%s)' % (followUsers)) followUsers = cursor.fetchall() for item in followUsers: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp followUsersCount = len(followUsers) else: followUsers = None # 获取用户的粉丝 fans = user['fans'] fansCount = 0 if not fans == '': fans = fans.split(',') temp = '' for item in fans: temp = temp + '"' + item + '",' fans = temp[:-1] cursor.execute('select username,nickname,portrait,fans from user where username in (%s)' % (fans)) fans = cursor.fetchall() for item in fans: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp fansCount = len(fans) else: fans = None closedb(db,cursor) return render_template('user/home.html', user=user, ideas=ideas, ideasCount=ideasCount, followIdeas=followIdeas, followIdeasCount=followIdeasCount, followUsers=followUsers, followUsersCount=followUsersCount, fans=fans, fansCount=fansCount, followUserStr=followUserStr, hotTags=hotTags) else: # 访问个人主页前需登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def home(): if not session.get('username') == None: updateToken(session.get('username')) (db, cursor) = connectdb() # 用户已登陆 cursor.execute('select * from user where username=%s', [session.get('username')]) user = cursor.fetchone() # 获取所关注的其他用户名单 followUserStr = user['followUsers'] # 获取热门标签以供编辑 hotTags = {} cursor.execute( "select tag from userTagStat where gender=1 order by count desc limit 10" ) hotTags['male'] = cursor.fetchall() cursor.execute( "select tag from userTagStat where gender=0 order by count desc limit 10" ) hotTags['female'] = cursor.fetchall() # 获取用户的创意 ideas = user['ideas'] ideasCount = 0 if not ideas == '': cursor.execute( 'select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (ideas)) ideas = cursor.fetchall() ideasCount = len(ideas) else: ideas = None # # 获取用户待删除的创意 # trashs = user['ideas'] # if not trashs == '': # cursor.execute('select id,title,feature from idea where id in (%s) and locked=1' % (trashs)) # trashs = cursor.fetchall() # else: # trashs = None # 获取用户喜欢的创意 followIdeas = user['followIdeas'] followIdeasCount = 0 if not followIdeas == '': cursor.execute( 'select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (followIdeas)) followIdeas = cursor.fetchall() followIdeasCount = len(followIdeas) else: followIdeas = None # 获取用户关注的其他用户 followUsers = user['followUsers'] followUsersCount = 0 if not followUsers == '': followUsers = followUsers.split(',') temp = '' for item in followUsers: temp = temp + '"' + item + '",' followUsers = temp[:-1] cursor.execute( 'select username,nickname,portrait,fans from user where username in (%s)' % (followUsers)) followUsers = cursor.fetchall() for item in followUsers: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp followUsersCount = len(followUsers) else: followUsers = None # 获取用户的粉丝 fans = user['fans'] fansCount = 0 if not fans == '': fans = fans.split(',') temp = '' for item in fans: temp = temp + '"' + item + '",' fans = temp[:-1] cursor.execute( 'select username,nickname,portrait,fans from user where username in (%s)' % (fans)) fans = cursor.fetchall() for item in fans: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp fansCount = len(fans) else: fans = None closedb(db, cursor) return render_template('user/home.html', user=user, ideas=ideas, ideasCount=ideasCount, followIdeas=followIdeas, followIdeasCount=followIdeasCount, followUsers=followUsers, followUsersCount=followUsersCount, fans=fans, fansCount=fansCount, followUserStr=followUserStr, hotTags=hotTags) else: # 访问个人主页前需登录 session['url'] = WECOPREFIX + request.path return redirect(url_for('login'))
def search_keyword(): (db,cursor) = connectdb() target = request.args.get('target') keyword = request.args.get('keyword') key = keyword pageId = request.args.get('pageId') numPerPage = 10 pageId = int(pageId) # 记录本次搜索 keyword = keyword.split(' ') if session.get('username') == None: username = '' else: username = session.get('username') # 存储搜索结果 result = [] if target == 'idea': # 搜索的是创意 for item in keyword: cursor.execute("insert into search(username,target,keyword,timestamp) values(%s,%s,%s,%s)",[username,target,item,str(int(time.time()))]) cursor.execute("select * from idea where published=1 and locked=0 and (title like '%%%s%%' or tags like '%%%s%%' or category like '%%%s%%')" % (item,item,item)) ideas = cursor.fetchall() for i in ideas: temp = int(time.time()) - int(i['timestamp']) if temp < 60: temp = str(temp) + 's' elif temp < 3600: temp = str(temp/60) + 'm' elif temp < 3600 * 24: temp = str(temp/3600) + 'h' else: temp = str(temp/(3600*24)) + 'd' i['timestamp'] = temp result.append(i) result = sorted(result, key=lambda x:(x['praise'], x['timestamp']), reverse=True) elif target == 'user': # 搜索的是用户 for item in keyword: cursor.execute("insert into search(username,target,keyword,timestamp) values(%s,%s,%s,%s)",[username,target,item,str(int(time.time()))]) cursor.execute("select username,nickname,portrait,tags,description,fans,lastActive from user where username!='None' and (nickname like '%%%s%%' or tags like '%%%s%%' or description like '%%%s%%')" % (item,item,item)) users = cursor.fetchall() for i in users: if i['fans'] == '': i['fans'] = 0 else: i['fans'] = len(i['fans'].split(',')) result.append(i) result = sorted(result, key=lambda x:(x['lastActive']), reverse=True) # 计算分页信息,截取结果 count = len(result) result = result[pageId*numPerPage:pageId*numPerPage+numPerPage] start = int(pageId) - 3 end = int(pageId) + 3 total = int(math.ceil(float(count) / numPerPage)) - 1 if start < 0: start = 0 if end > total: end = total pages = [] for i in xrange(start, end + 1): pages.append(i) # 关键词搜索无返回结果时查看当前热门搜索 cursor.execute("select keyword, count(*) as count from search where timestamp > %s and keyword!='' and target='idea' group by keyword order by count(*) desc limit 10",[int(time.time())-3600*24*7]) hot = cursor.fetchall() closedb(db,cursor) return render_template('search/search_keyword.html', target=target, keyword=key, count=count, start=start, end=end, current=int(pageId), pages=pages, total=total, result=result, hot=hot)
def user(username): if session.get('username') == username: # 访问的就是本人,返回个人主页 return redirect(url_for('home')) else: if not session.get('username') == None: updateToken(session.get('username')) (db,cursor) = connectdb() # 访问其他用户 # cursor.execute('select username,email,nickname,portrait,tags,description,gender,wechat,ideas,followIdeas,fans,followUsers,lastActive from user where username=%s',[username]) cursor.execute('select username,nickname,portrait,tags,description,gender,wechat,hobby,location,ideas,followIdeas,fans,followUsers,lastActive from user where username=%s',[username]) user = cursor.fetchone() # 获取其他用户的创意 ideas = user['ideas'] ideasCount = 0 if not ideas == '': cursor.execute('select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (str(ideas))) ideas = cursor.fetchall() ideasCount = len(ideas) else: ideas = None # 获取其他用户喜欢的创意 followIdeas = user['followIdeas'] followIdeasCount = 0 if not followIdeas == '': cursor.execute('select id,title,feature from idea where id in (%s) and published=1 and locked=0' % (str(followIdeas))) followIdeas = cursor.fetchall() followIdeasCount = len(followIdeas) else: followIdeas = None # 获取其他用户的关注 followUsers = user['followUsers'] followUsersCount = 0 if not followUsers == '': followUsers = followUsers.split(',') temp = '' for item in followUsers: temp = temp + '"' + item + '",' followUsers = temp[:-1] cursor.execute('select username,nickname,portrait,fans from user where username in (%s)' % (followUsers)) followUsers = cursor.fetchall() for item in followUsers: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp followUsersCount = len(followUsers) else: followUsers = None # 获取其他用户的粉丝 fans = user['fans'] fansCount = 0 if not fans == '': fans = fans.split(',') temp = '' for item in fans: temp = temp + '"' + item + '",' fans = temp[:-1] cursor.execute('select username,nickname,portrait,fans from user where username in (%s)' % (fans)) fans = cursor.fetchall() for item in fans: temp = item['fans'] if temp == '': temp = 0 else: temp = len(temp.split(',')) item['fans'] = temp fansCount = len(fans) else: fans = None # 获取当前用户的关注列表 followUserStr = '' me = session.get('username') if not me == None: cursor.execute('select followUsers from user where username=%s',[me]) followUserStr = cursor.fetchone()['followUsers'] closedb(db,cursor) return render_template('user/user.html',user=user, ideas=ideas, ideasCount=ideasCount, followIdeas=followIdeas, followIdeasCount=followIdeasCount, followUsers=followUsers, followUsersCount=followUsersCount, fans=fans, fansCount=fansCount, followUserStr=followUserStr)