def index(): cache.set("test", 1) page = request.args.get('page', 1, type=int) # 设定page参数默认值为1,类型为整型 per_page = request.args.get('per_page', 4, type=int) # 分页实现 # 方法1:offset为偏移量,limit限制返回的记录数 # questions = Question.query.order_by(Question.create_time.desc()).offset(per_page*(page-1)).limit(per_page) # 方法2:使用paginate,这样可通过paginate.pages获取总页数而不需要自己再另外计算 paginate = Question.query.order_by(Question.create_time.desc()).paginate( page, per_page, error_out=False) # questions = paginate.items # 获取当前页数据 print("总页数:{}".format(paginate.pages)) # 总页数 return render_template('index.html', paginate=paginate, per_page=per_page)
def make_vcode(): str_list = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] chars = ''.join(random.choices(str_list, k=4)) print(chars) cache.set('vcode', chars, timeout=300) image = ImageCaptcha().generate_image(chars) image.save('vcode.jpg') with open('vcode.jpg', 'rb') as f: ls_f = base64.b64encode(f.read()).decode() return ls_f
def vcode(num): img = Img.new("RGB", (100, 50), (200, 200, 200)) draw = ImageDraw.Draw(img, "RGB") font_path = "App/static/fonts/ADOBEARABIC-BOLD.OTF" font = ImageFont.truetype(font=font_path, size=30) vcode = random_code() cache.set(request.remote_addr + "vcode", vcode, 60 * 60) # 设置该ip的验证码缓存 for i in range(len(vcode)): xy = (10 + i * 20, random.randint(-10, 20)) draw.text(xy, vcode[i], font=font, fill=random_color()) buff = io.BytesIO() img.save(buff, "png") # 画布装维png格式的图片,保存到buff缓冲区中 response = make_response(buff.getvalue()) response.headers["Content-Type"] = "image/png" return response
def post(self): # 获取前端提交的参数 args = parser.parse_args() username = args.get("username") password = args.get("password") email = args.get("email") # 注册(添加用户数据) user = User() user.username = username user.password = generate_password_hash(password) # print(user.password) # print(len(user.password)) user.email = email user.user_token = str(uuid.uuid4()) # token, 唯一标识 try: db.session.add(user) db.session.commit() # 发生邮件激活用户 # 创建邮件 msg = Message(subject="淘票票用户激活", sender="*****@*****.**", recipients=[email]) # 邮件内容 # msg.html = "<b>hello 淘票票</b>" msg.html = render_template( 'user_active.html', username=username, active_url="http://10.20.158.28:5000/useractive/?token=%s" % user.user_token) # 发送邮件 mail.send(msg) # 使用缓存cache # 给每个用户单独使用缓存,在5分钟内激活才有效 cache.set(user.user_token, user.id, timeout=300) except Exception as e: return {"returnCode": "-1", "msg": str(e)} return {"returnCode": "0", "msg": "success", "returnValue": user}
def send_code(): telephone = request.args.get('telephone') resp = send_verify_code(telephone) result = resp.json() print(result) # 判断是否发送成功 # 成功则放到缓存中,并发送了则返回200给前端 if result.get('code') == 200: obj = result.get('obj') # 获取验证码 cache.set(telephone, obj) # 将手机号及对应的验证码存储到缓存中 data = { "msg": "ok", "status": 200 } return jsonify(data) # 不成功则返回400给前端 data = { "msg": "fail", "status": 400 } return jsonify(data)
def post(self): #注册 #获取客户端提交过来的东西 parse = parser.parse_args() username = parse.get('username') password = parse.get('password') email = parse.get('email') user = UserModel() user.name = username user.passwd = generate_password_hash(password) user.email = email #注册时设置token的值(唯一标识一个用户) user.token = str(uuid.uuid4()) try: db.session.add(user) db.session.commit() #临时存储5分钟,在5分钟之内激活有效(临时存储user.token,user.id) cache.set(user.token, user.id, timeout=300) #给指定的邮箱发送邮件 msg = Message(subject='用户激活', sender='*****@*****.**', recipients=[email]) #邮箱内容 msg.html = render_template( 'email_active.html', username=username, active_url='http://127.0.0.1:5000/urr/?u_token=%s' % user.token) #发送 mail.send(msg) except Exception as e: return {'returnCode': '-1', 'msg': e} return {'returnCode': '0', 'msg': 'success', 'returnValue': user}
def addcomment(): ip = request.base_url ip = ip + 'addcomm' data = datetime.datetime.now() if not cache.get(ip): cache.set(ip, data, timeout=60 * 5) else: return jsonify({'code': 0}) if request.method == 'GET': artval = request.args.get('artval') art_id = request.args.get('art_id') com = add_com( artval, 0, art_id, ) com = { 'id': com.id, 'info': com.info, 'name': com.name, 'date': com.date, } return jsonify({'com': com, 'code': 1}) if request.method == 'POST': artval = request.form.get('artval') fa_id = request.form.get('userid') art_id = request.form.get('art_id') print(fa_id, artval, art_id) toname = Comments.query.get(fa_id).name com = add_com(artval, fa_id, art_id, toname) com = { 'id': com.id, 'info': com.info, 'name': com.name, 'toname': com.toname, 'fa_id': fa_id, 'date': com.date, } return jsonify({'com': com, 'code': 1})
def info(id): if request.method == 'GET': print(datetime.datetime.now()) if id == 0: art = Article.query.paginate(1, 1, False) else: num = Article.query.filter(Article.id <= id, Article.ispublic == True).all() page = len(num) art = Article.query art = art.filter(Article.ispublic == True) art = art.paginate(page, 1, False) ip = request.base_url data = datetime.datetime.now() artid = Article.query.get(art.items[0].id) if not cache.get(ip): cache.set(ip, data, timeout=60 * 60) artid.read_num += 1 db.session.commit() cate_name = Category.query.get(artid.categoryid).name data = artnav() comms = comment(artid.id) return render_template('blog/info.html', data=data, art=art, cate_name=cate_name, comms=comms) elif request.method == "POST": ip = request.base_url ip = ip + 'praise' data = datetime.datetime.now() artid = Article.query.get(id) if not cache.get(ip): cache.set(ip, data, timeout=60 * 60 * 24) artid.praise_num += 1 db.session.commit() print(artid.praise_num) return jsonify({'pra_num': artid.praise_num})
def info(id, per_page=1): # 文章部分 page = Article.query.filter(Article.id.__le__(id)).count() article = Article.query.paginate(page, per_page, error_out=False) captcha = captchas() user_ip = request.remote_addr cache_ip = cache.get(user_ip) cache_aid = cache.get(int(id)) if not cache_ip and not cache_aid: article.items[0].readersum += 1 cache.set(user_ip, user_ip, timeout=10) cache.set(cache_aid, cache_aid, timeout=10) db.session.commit() data = { "article": article, 'captcha': captcha, } data.update(get_column()) data.update(get_type()) return render_template('blog/info.html', **data)
def info(id=1): try: id = int(id) except: id = 1 if request.method == "GET": user = User.query.get(1) types = Articletype.query.all() # 文章类型 paihang = Article.query.filter().order_by(desc("readnum")).limit( 8) # 所有文章按点击排行,也就是阅读量排行 biaoqian = Articlelabel.query.filter().limit(8) # 标签只取8个 article = Article.query.get(id) article.readnum += 1 comts = Comment.query.filter(Comment.articleid == id) comments = [] for i in comts: comments.append({ "name": i.name, "msg": i.msg, "time": i.time, }) list = [] lanmu = "" if article.type: # 如果文章类型存在 lanmu = Articletype.query.get(article.type).title # 则写道lanmu中 al = Alabel.query.filter(Alabel.articleid == article.id) # 在三方表中查找标签集 for j in al: # 遍历查找到的标签集 lab = Articlelabel.query.get(j.labelid) # 把标签集里的标签id放入 if lab: # 如果标签存在 list.append(lab.labelname) data = { "user": user, "types": types, "paihang": paihang, "biaoqian": biaoqian, "comments": comments, "article": { "articleid": article.id, "lanmu": lanmu, "labels": list, "article": article, }, } db.session.commit() return render_template('blog/info.html', **data) elif request.method == "POST": zanid = request.form.get("zan") username = request.form.get("username") key = request.form.get("key") saytext = request.form.get("saytext") if key: if not (key.lower() == (cache.get(request.remote_addr + "vcode")).lower()): return "验证码错误" elif key == "": return "验证码错误" if username and key and saytext: if key.lower() == (cache.get(request.remote_addr + "vcode")).lower(): comment = Comment() comment.articleid = id comment.name = username comment.msg = saytext comment.time = datetime.datetime.now() db.session.add(comment) db.session.commit() return redirect("/info/%s" % id) else: return "验证码错误" try: if zanid: zanid = int(zanid) except: zanid = None if zanid and not (username or key or saytext): if not cache.get(request.remote_addr + "zan"): cache.set(request.remote_addr + "zan", []) ca = cache.get(request.remote_addr + "zan") if id not in ca: article = Article.query.get(zanid) article.zan += 1 db.session.commit() ca.append(id) cache.set(request.remote_addr + "zan", ca, timeout=60 * 60 * 24) # 设置一个ip一天只能赞一篇文章一次 else: return "一天只能赞一次哦" return "ok"
def info(id): ''' 文章详细内容 :return: ''' if request.method == "GET": article = Article.query.get(id) # print(article.visit) if article.visit: article.visit += 1 else: article.visit = 1 db.session.commit() # 获取上一篇和下一篇的内容 if id != 1: prvart = Article.query.filter(Article.id.__lt__(id)).first() else: prvart = None nextart = Article.query.filter(Article.id.__gt__(id)).first() # 查询所有的文章 arts = Article.query.all() # 查看自己分类 types = AriticleType.query.all() commands = Commend.query.filter( Commend.articleid == article.id).order_by(desc("time")) tags = article.tag.split("、") typeclass = [] tmp = article.ariticletype flags = 1 while flags: typeclass.append(tmp.name) if tmp.father_type: print(tmp.father_type) tmp = AriticleType.query.get(tmp.father_type) else: flags = 0 print(typeclass) data = { "prvart": prvart, "nextart": nextart, "article": article, "typeclass": typeclass, "tags": tags, "arts": arts, "commands": list(commands), "types": types, } return render_template("blog/info.html", **data) elif request.method == "PUT": ''' 修改点赞量。 ''' if cache.get(request.remote_addr) != id: try: id = request.form.get("id") cache.set(request.remote_addr, id, 5) art = Article.query.get(id) art.num += 1 db.session.commit() return jsonify({"code": 1, "art_num": art.num}) except: return jsonify({"code": 0}) else: cache.set(request.remote_addr, id, 5) return jsonify({"code": 2}) elif request.method == "POST": try: id = request.cookies.get("user") or "1" nameip = request.remote_addr artid = request.form.get("artid") name = request.form.get("name") or nameip info = request.form.get("info") user = User() user.name = name user.icon = "http://img4.imgtn.bdimg.com/it/u=2641899507,2178808967&fm=26&gp=0.jpg" user.time = datetime.datetime.now() db.session.add(user) db.session.commit() commend = Commend() # 反向插入id必须找到对方的值。 commend.comment_user = user commend.articleid = artid commend.info = info commend.time = datetime.datetime.now() db.session.add(commend) db.session.commit() return jsonify({"code": 1}) except: return jsonify({"code": 0})