def cookie2user(cookie_str): """ Parse cookie and load user if cookie is valid. :param cookie_str: :return: """ if not cookie_str: return None try: L = cookie_str.split('-') # 正确的格式:"用户id" - "过期时间" - SHA1 if len(L) != 3: return None uid, expires, sha1 = L if int(expires) < time.time(): # 已过期 return None user = yield from Users.find(uid) if user is None: # 数据库中不存在此用户 return None s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY) if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest(): # 密码不一致 logging.info('invalid sha1') return None user.passwd = '******' return user except Exception as e: logging.exception(e) return None
def route_profile(request): headers = { 'Content-Type': 'text/html', } username = current_user(request) header = response_with_headers(headers) user = Users.find(username) body = template('profile.html', id=user.id, username=user.name, note=user.note) r = header + '\r\n' + body return r.encode(encoding='utf-8')
def route_weibo_index(request): headers = { 'Content-Type': 'text/html', } header = response_with_headers(headers) user_id = request.query.get('user_id', -1) user_id = int(user_id) user = Users.find(user_id) if user is None: return error(request) # 找到 user 发布的所有 weibo weibos = Weibo.find_all(user_id=user_id) log('weibos', weibos) current_username = current_user(request) u = Users.find_by(username=current_username) if u is None: return redirect('/login') def weibo_tag(weibo): comment_list = Comment.find_all(weibo_id=weibo.id) comments = '<br>'.join([c.content for c in comment_list]) w = { "id": weibo.id, "user_id": u.id, "content": weibo.content, "username": user.username, "time": weibo.created_time, "comments": comments, } log('comments debug', comment_list) return """ <p>{content} from {username}@{time} <a href="/weibo/delete?id={id}">删除</a> <a href="/weibo/edit?id={id}">修改</a> <button class="gua-show-comment" data-id="{id}">评论</button> <div> {comments} </div> <div id="id-div-comment-{id}" class="gua-comment-form gua-hide"> <form action="/weibo/comment/add" method="post"> <input name="user_id" value="{user_id}" type="hidden"> <input name="weibo_id" value="{id}" type="hidden"> <textarea name="content"></textarea> <button type="submit">添加评论</button> </form> </div> </p> """.format(**w) weibos = '\n'.join([weibo_tag(w) for w in weibos]) body = template('weibo_index.html', weibos=weibos) r = header + '\r\n' + body return r.encode(encoding='utf-8')