def post(self, *args, **kwargs): rep = BaseResponse() form = account.LoginForm() if form.valid(self): if form._value_dict['code'].lower() != self.session["CheckCode"].lower(): rep.message = {'code': '验证码错误'} self.write(json.dumps(rep.__dict__)) return conn = ORM.session() obj = conn.query(ORM.UserInfo).filter( or_( and_(ORM.UserInfo.email == form._value_dict['user'], ORM.UserInfo.password == form._value_dict['pwd']), and_(ORM.UserInfo.username == form._value_dict['user'], ORM.UserInfo.password == form._value_dict['pwd']) )).first() conn.close() if not obj: rep.message = {'user': '******'} self.write(json.dumps(rep.__dict__)) return self.session['is_login'] = True self.session['user_info'] = obj.__dict__ rep.status = True else: rep.message = form._error_dict self.write(json.dumps(rep.__dict__))
def get(self, page=1): conn = ORM.session() all_count = conn.query(ORM.News).count() obj = Pagination(page, all_count) # 从基于redis的session钟取得数据时,返回格式是bytes # 因此会在__getitem__方法中,将其转换为str类型再返回 # 但在这里,如果用户预先没有登陆,那么下面一句返回的就是None,转换类型的话会出错 # 因此在转换为字符串时,需要判断其是否为None类型 # 另外还要注意self.session['user_info']虽然在存储时,存储的是字典 # 但从session取过来后是str类型的 if self.session['is_login']: current_user_id = self.session['user_info']['nid'] else: current_user_id = 0 result = conn.query( ORM.News.nid, ORM.News.title, ORM.News.url, ORM.News.content, ORM.News.ctime, ORM.UserInfo.username, ORM.NewsType.caption, ORM.News.favor_count, ORM.News.comment_count, ORM.Favor.nid.label('has_favor')).join( ORM.NewsType, isouter=True).join(ORM.UserInfo, isouter=True).join( ORM.Favor, and_(ORM.Favor.user_info_id == current_user_id, ORM.News.nid == ORM.Favor.news_id), isouter=True)[obj.start:10] conn.close() str_page = obj.string_pager('/index/') self.render('home/index.html', str_page=str_page, news_list=result)
def get(self, *args, **kwargs): # comment_list需要按照时间从小到大排列 nid = self.get_argument('nid', 0) conn = ORM.session() comment_list = conn.query( ORM.Comment.nid, ORM.Comment.content, ORM.Comment.reply_id, ORM.UserInfo.username, ORM.Comment.ctime, ORM.Comment.up, ORM.Comment.down, ORM.Comment.news_id).join( ORM.UserInfo, isouter=True).filter(ORM.Comment.news_id == nid).all() conn.close() """ comment_list = [ (1, '111',None), (2, '222',None), (3, '33',None), (9, '999',5), (4, '444',2), (5, '555',1), (6, '666',4), (7, '777',2), (8, '888',4), ] """ comment_tree = commons.build_tree(comment_list) self.render('include/comment.html', comment_tree=comment_tree)
def get(self, page=1): current_time = time.time() conn = ORM.session() all_count = conn.query(ORM.News).count() obj = Pagination(page, all_count) current_user_id = self.session['user_info']['nid'] if self.session[ 'is_login'] else 0 result = conn.query( ORM.News.nid, ORM.News.title, ORM.News.url, ORM.News.content, ORM.News.ctime, ORM.UserInfo.username, ORM.NewsType.caption, ORM.News.favor_count, ORM.News.comment_count, ORM.Favor.nid.label('has_favor')).join( ORM.NewsType, isouter=True).join(ORM.UserInfo, isouter=True).join( ORM.Favor, and_(ORM.Favor.user_info_id == current_user_id, ORM.News.nid == ORM.Favor.news_id), isouter=True)[obj.start:10] conn.close() str_page = obj.string_pager('/index/') self.render('home/index.html', str_page=str_page, news_list=result, current_time=current_time)
def post(self, *args, **kwargs): rep = BaseResponse() news_id = self.get_argument('news_id', None) if not news_id: rep.summary = "新闻ID不能为空." else: user_info_id = self.session['user_info']['nid'] conn = ORM.session() has_favor = conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).count() if has_favor: conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).delete() conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count - 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorMinus else: conn.add( ORM.Favor(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now())) conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count + 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorPlus conn.commit() conn.close() rep.status = True self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = account.RegisterForm() if form.valid(self): current_date = datetime.datetime.now() # timedelta(): used to express difference between two datetime values limit_day = current_date - datetime.timedelta(minutes=1) conn = ORM.session() # SendMsg表的邮箱、验证码、创建时间 is_valid_code = conn.query(ORM.SendMsg).filter( ORM.SendMsg.email == form._value_dict['email'], ORM.SendMsg.code == form._value_dict['email_code'], ORM.SendMsg.ctime > limit_day).count() if not is_valid_code: rep.message['email_code'] = '邮箱验证码不正确或过期' self.write(json.dumps(rep.__dict__)) return has_exists_email = conn.query(ORM.UserInfo).filter( ORM.UserInfo.email == form._value_dict['email']).count() if has_exists_email: rep.message['email'] = '邮箱已经存在' self.write(json.dumps(rep.__dict__)) return has_exists_username = conn.query(ORM.UserInfo).filter( ORM.UserInfo.username == form._value_dict['username']).count() if has_exists_username: rep.message['email'] = '用户名已经存在' self.write(json.dumps(rep.__dict__)) return form._value_dict['ctime'] = current_date form._value_dict.pop('email_code') obj = ORM.UserInfo(**form._value_dict) conn.add(obj) conn.flush() conn.refresh(obj) user_info_dict = { 'nid': obj.nid, 'email': obj.email, 'username': obj.username } conn.query(ORM.SendMsg).filter_by( email=form._value_dict['email']).delete() conn.commit() conn.close() self.session['is_login'] = True self.session['user_info'] = user_info_dict rep.status = True else: rep.message = form._error_dict self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = account.SendMsgForm() if form.valid(self): email = form._value_dict['email'] conn = ORM.session() has_exists_email = conn.query(ORM.UserInfo).filter( ORM.UserInfo.email == form._value_dict['email']).count() if has_exists_email: rep.summary = "此邮箱已经被注册" self.write(json.dumps(rep.__dict__)) return current_date = datetime.datetime.now() code = commons.random_code() count = conn.query( ORM.SendMsg).filter_by(**form._value_dict).count() if not count: insert = ORM.SendMsg(code=code, email=email, ctime=current_date) conn.add(insert) conn.commit() rep.status = True else: limit_day = current_date - datetime.timedelta(hours=1) times = conn.query(ORM.SendMsg).filter( ORM.SendMsg.email == email, ORM.SendMsg.ctime > limit_day, ORM.SendMsg.times >= 10, ).count() if times: rep.summary = "'已经超过今日最大次数(1小时后重试)'" else: unfreeze = conn.query(ORM.SendMsg).filter( ORM.SendMsg.email == email, ORM.SendMsg.ctime < limit_day).count() if unfreeze: conn.query(ORM.SendMsg).filter_by(email=email).update( {"times": 0}) conn.query(ORM.SendMsg).filter_by(email=email).update( { "times": ORM.SendMsg.times + 1, "code": code, "ctime": current_date }, synchronize_session="evaluate") conn.commit() rep.status = True conn.close() else: rep.summary = form._error_dict['email'] self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = account.SendMsgForm() # 判断输入是否合法 if form.valid(self): email = form._value_dict['email'] conn = ORM.session() # 判断该邮箱是否已注册 has_exists_email = conn.query(ORM.UserInfo).filter(ORM.UserInfo.email == email).count() if has_exists_email: rep.summary = '该邮箱已被注册' self.write(json.dumps(rep.__dict__)) return current_datetime = datetime.datetime.now() code = commons.random_code() # 判断该邮箱之前是否发送过验证码 has_send_count = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email).count if not has_send_count: message.email([email, ], code) insert_obj = ORM.SendMsg(email = email, code = code, ctime = current_datetime) conn.add(insert_obj) conn.commit() rep.status = True else: # 发送过则判断是否过于频繁 limit_hour = current_datetime - datetime.timedelta(hours=1) times = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email, ORM.SendMsg.ctime > limit_hour, ORM.SendMsg.times >= 10,).count() if times: rep.summary = "已经超过今日最大次数(1小时后重试)" else: # 判断是否超过间隔时间,是则清零 unforzen = conn.query(ORM.SendMsg).filter(ORM.SendMsg.email == email, ORM.SendMsg.ctime < limit_hour).count() if unforzen: # filter_by 里面是键值对; filter 里面是条件 conn.query(ORM.SendMsg).filter_by(email = email).update({"times": 0}) message.email([email,], code) conn.query(ORM.SendMsg).filter_by(email = email).update({"times": ORM.SendMsg.times + 1, "code": code, "ctime": current_datetime}) conn.commit() rep.status = True conn.close() else: rep.summary = form._error_dict['email'] self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): # 定义给前端的返回值对象 rep = BaseResponse() # 声明登陆表单,每个表单内包含了预先定义的验证域 form = account.LoginForm() # 表单的valid()方法会遍历表单内所有的验证域,都满足的话才会返回True if form.valid(self): # 判断验证码 print(form._value_dict['code']) print(self.session["CheckCode"]) print(self.session["CheckCode"]) if form._value_dict['code'].lower( ) != self.session["CheckCode"].lower(): rep.message = {'code': '验证码错误'} self.write(json.dumps(rep.__dict__)) return # 验证成功,与数据库建立连接 conn = ORM.session() # 邮箱/密码或用户名/密码匹配任意一对即可 obj = conn.query(ORM.UserInfo).filter( or_( # 邮箱/密码 and_(ORM.UserInfo.email == form._value_dict['user'], ORM.UserInfo.password == form._value_dict['pwd']), # 用户名/密码 and_(ORM.UserInfo.username == form._value_dict['user'], ORM.UserInfo.password == form._value_dict['pwd'] ))).first() # 断开与数据库的连接 conn.close() # 如果在数据库中没有找到用户信息 if not obj: rep.message = {'user': '******'} self.write(json.dumps(rep.__dict__)) return # 数据库中有匹配的信息,则将用户登陆状态及用户信息存入session,并写给前端状态码 # 这里ORM连接的__dict__属性返回的字典中有个键是'_sa_instance_state' # 其值是一个sqlalchemy对象 # 我们自定义session时,__setitem__方法会进行要设置值是否是字典的判断 # 如果是字典的话,会对value使用dumps方法,而json并不知道如何转换sqlalchemy对象 # 这个错误排查了有一会儿才确定怎么回事 # 话说我为什么要把obj.__dict__写入session?里面有敏感信息 # 而且也没什么用 self.session['is_login'] = True self.session['user_info'] = obj.__dict__ rep.status = True else: rep.message = form._error_dict self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = CommentForm() if form.valid(self): form._value_dict['ctime'] = datetime.datetime.now() conn = ORM.session() obj = ORM.Comment(user_info_id=self.session['user_info']['nid'], news_id=form._value_dict['news_id'], reply_id=form._value_dict['reply_id'], content=form._value_dict['content'], up=0, down=0, ctime=datetime.datetime.now()) conn.add(obj) # 获取nid conn.flush() conn.refresh(obj) rep.data = { 'user_info_id': self.session['user_info']['nid'], 'username': self.session['user_info']['username'], 'nid': obj.nid, 'news_id': obj.news_id, 'ctime': obj.ctime.strftime("%Y-%m-%d %H:%M:%S"), 'reply_id': obj.reply_id, 'content': obj.content, } # 将评论数+1 conn.query(ORM.News).filter( ORM.News.nid == form._value_dict['news_id']).update( {"comment_count": ORM.News.comment_count + 1}, synchronize_session="evaluate") conn.commit() conn.close() rep.status = True else: rep.message = form._error_dict print(rep.__dict__) self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() form = IndexForm() if form.valid(self): # title,content,href,news_type,user_info_id input_dict = copy.deepcopy(form._value_dict) input_dict['ctime'] = datetime.datetime.now() input_dict['user_info_id'] = self.session['user_info']['nid'] conn = ORM.session() conn.add(ORM.News(**input_dict)) conn.commit() conn.close() rep.status = True else: rep.message = form._error_dict self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): rep = BaseResponse() # 前端对应index.html中的DoFavor方法中的ajax请求 news_id = self.get_argument('news_id', None) if not news_id: rep.summary = "新闻ID不能为空." else: # 从session中获取用户信息 user_info_id = self.session['user_info']['nid'] conn = ORM.session() # 在Favor表中查询是否有该用户的点赞记录 has_favor = conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).count() if has_favor: # 用户已点过赞,则此时用户的点击操作代表消除自己的点赞 # 因此先从数据库中删除点赞该用户的点赞记录 # 分别从Favor和News表中同时删除,保持数据一致 conn.query(ORM.Favor).filter( ORM.Favor.user_info_id == user_info_id, ORM.Favor.news_id == news_id).delete() conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count - 1}, synchronize_session="evaluate") # 要给前端发送的code信息,以便前端做出相应的效果改变 rep.code = StatusCodeEnum.FavorMinus else: # 否则用户执行点赞操作,数据库内记录+1 conn.add( ORM.Favor(user_info_id=user_info_id, news_id=news_id, ctime=datetime.datetime.now())) conn.query(ORM.News).filter(ORM.News.nid == news_id).update( {"favor_count": ORM.News.favor_count + 1}, synchronize_session="evaluate") rep.code = StatusCodeEnum.FavorPlus conn.commit() conn.close() rep.status = True # 将返回信息写入前端 self.write(json.dumps(rep.__dict__))
def post(self, *args, **kwargs): ret = {'status': True, "data": "", "error": ""} email = self.get_argument('email', None) print(email) if email: code = commons.random_code() # 获取随机验证码 print(code) message.email([email, ], code) # 发送验证码到邮箱 conn = chouti_orm.session() # 获取数据库session对象 print('1') obj = chouti_orm.SendCode(email=email, code=code, stime=datetime.datetime.now()) # 写入数据库 print('2') conn.add(obj) conn.commit() else: ret['status'] = False ret['error'] = "邮箱格式错误" self.write(json.dumps(ret))