一个练习项目,好玩的bbs-python-flask

news/2024/11/13 20:44:46/文章来源:https://www.cnblogs.com/xuxiaobo/p/18392589

代码:

from flask import Flask, make_response, request
import os.path
import MySQLdb
import json
import hashlib
import random
import math
import os
from datetime import datetimeapp = Flask(__name__)class DateEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime):return obj.strftime("%Y-%m-%d %H:%M:%S")else:return json.JSONEncoder.default(self, obj)secretKey = 'saacac3423@21212'
pagesize = 20def getConn():conn = MySQLdb.Connection('127.0.0.1', 'root', '123456', 'my_bbs')cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)return (conn, cursor)def getloginuserinfo(sessionId):(conn, cursor) = getConn()try:sessionIdHead = request.cookies.get("sessionId")except:sessionIdHead = ''if sessionIdHead is not None and sessionIdHead != '':sessionId = sessionIdHeadsql = "select id,username,nickname,addTime,sessionId from user where sessionId='%s'" % sessionIdcursor.execute(sql)data = cursor.fetchone()if data is None:data = {'id' : 0, 'username' : '', 'nickname' : '', 'addTime' : '', 'sessionId' : ''}return datadef response(code, msg, data):if code != 0:result = {'code' : code, 'msg' : msg, 'data' : None}else:result = {'code' : 0, 'msg' : '', 'data' : data}result = json.dumps(result, cls = DateEncoder, ensure_ascii = False)response = make_response(result)response.headers['Server'] = 'flask-Web-Framework'return responsedef error(code, msg):return response(code, msg, None)def success( data = {}):return response(0, '', data)@app.route('/')
def index():(conn, cursor) = getConn()result = "此站接口使用python.flask实现,<a href='api.html' target='_blank'>接口列表</a>"response = make_response(result)response.headers['Server'] = 'flask-Web-Framework'return response@app.route('/user/register')
def register():(conn, cursor) = getConn()username = request.args.get("username", "")password = request.args.get("password", "")nickname = request.args.get("nickname", "")sql = "select id,username,nickname,addTime from user where username='%s'" % usernamecursor.execute(sql)data = cursor.fetchone()if data != None:return error(1, '用户名已经存在')try:passwordMd5 = hashlib.md5(password.encode(encoding='utf-8')).hexdigest()sql = "insert into user(username, password, nickname) value('%s', '%s', '%s')" % (username, passwordMd5, nickname)cursor.execute(sql)conn.commit()insertId = cursor.lastrowidreturn success(insertId)except MySQLdb.Error as e:conn.rollback()return error(1, '注册失败')@app.route('/user/login')
def login():(conn, cursor) = getConn()username = request.args.get("username", "")password = request.args.get("password", "")passwordMd5 = hashlib.md5(password.encode(encoding='utf-8')).hexdigest()sql = "select id,username,nickname,addTime from user where username='%s' and password='%s'" % (username, passwordMd5)cursor.execute(sql)data = cursor.fetchone()if data == None:return error(1, '用户名或者密码错误')tmpSessionId = secretKey + str(data['id']) + str(data['addTime'])tmpSessionId = hashlib.md5(tmpSessionId.encode(encoding='utf-8')).hexdigest()try:sql = "update user set sessionId='%s' where id=%s" % (tmpSessionId, data['id'])cursor.execute(sql)conn.commit()data['sessionId'] = tmpSessionIdreturn success(data)except MySQLdb.Error as e:conn.rollback()return error(1, '保存会话id失败')@app.route('/user/logout')        
def logout():(conn, cursor) = getConn()sessionId = request.args.get("sessionId", "")data = getloginuserinfo(sessionId)if data == None:return success(None)if data['sessionId'] == '':return success(data)try:sql = "update user set sessionId='' where sessionId='%s'" % sessionIdcursor.execute(sql)conn.commit()data['sessionId'] = ''return success(data)except MySQLdb.Error as e:conn.rollback()return error(1, '删除会话id失败')@app.route('/user/getuserinfo') 
def getuserinfo():(conn, cursor) = getConn()sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)return success(userinfo)@app.route('/post/list')
def postlist():(conn, cursor) = getConn()page = request.args.get("page", "1")keyword = request.args.get("keyword", "")page = int(page)if page <= 0:page = 1addsql = " isDel=0 "if keyword is not None and keyword != '':addsql = " isDel=0 and title like '%"+keyword+"%' "start = (page - 1) * pagesizesql1 = "select count(1) as count from content where %s" % addsqlcursor.execute(sql1)countdata = cursor.fetchone()totalpage = math.ceil(countdata['count'] / float(pagesize))data = []if totalpage > 0:sql2 = "select id,title,userId,userNickename,replyNum,updateTime from content where %s order by updateTime desc limit %s,%s" % (addsql, start, pagesize)cursor.execute(sql2)data = cursor.fetchall()return success({'totalpage' : totalpage, 'data' : data})@app.route('/post/detail')
def postdetail():(conn, cursor) = getConn()id = request.args.get("id", "0")sql = "select id,title,content,userId,userNickename,replyNum,updateTime from content where isDel=0 and id=%s" % idcursor.execute(sql)data = cursor.fetchone()return success(data)@app.route('/post/add')  
def postadd():(conn, cursor) = getConn()title = request.args.get("title", "")content = request.args.get("content", "")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')try:sql = "insert into content(title, content, userId, userNickename) value('%s', '%s', %s, '%s')" % (title, content, userId, userNickename)cursor.execute(sql)conn.commit()insertId = cursor.lastrowidreturn success(insertId)except MySQLdb.Error as e:conn.rollback()return error(1, '发帖失败')@app.route('/post/edit') 
def postedit():(conn, cursor) = getConn()id = request.args.get("id", "0")title = request.args.get("title", "")content = request.args.get("content", "")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')try:sql = "update content set title='%s',content='%s',userId=%s,userNickename='%s' where id=%s and userId=%s" % (title, content, userId, userNickename, id, userId)cursor.execute(sql)conn.commit()return success(None)except MySQLdb.Error as e:conn.rollback()return error(1, '编辑帖子失败')@app.route('/post/delete') 
def postdelete():(conn, cursor) = getConn()id = request.args.get("id", "0")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')try:sql = "update content set isDel=1 where id=%s and userId=%s" % (id, userId)cursor.execute(sql)conn.commit()return success(None)except MySQLdb.Error as e:conn.rollback()return error(1, '删除帖子失败')@app.route('/reply/list') 
def replylist():(conn, cursor) = getConn()page = request.args.get("page", "1")contentId = request.args.get("contentId", "0")page = int(page)if page <= 0:page = 1start = (page - 1) * pagesizesql1 = "select count(1) as count from reply where isDel=0 and contentId=%s" % contentIdcursor.execute(sql1)countdata = cursor.fetchone()totalpage = math.ceil(countdata['count'] / float(pagesize))data = []if totalpage > 0:sql2 = "select id,content,replyUserId,replyUserNickename,addTime from reply where isDel=0 and contentId=%s order by id asc limit %s,%s" % (contentId, start, pagesize)cursor.execute(sql2)data = cursor.fetchall()return success({'totalpage' : totalpage, 'data' : data})@app.route('/reply/detail') 
def replydetail():(conn, cursor) = getConn()id = request.args.get("id", "0")sql = "select id,content,replyUserId,replyUserNickename,addTime from reply where isDel=0 and id=%s" % idcursor.execute(sql)data = cursor.fetchone()return success(data)@app.route('/reply/add') 
def replyadd():(conn, cursor) = getConn()contentId = request.args.get("contentId", "0")content = request.args.get("content", "")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')try:sql2 = "update content set replyNum=replyNum+1 where id=%s" % contentIdcursor.execute(sql2)sql1 = "insert into reply(contentId, content, replyUserId, replyUserNickename) value(%s, '%s', %s, '%s')" % (contentId, content, userId, userNickename)cursor.execute(sql1)conn.commit()insertId = cursor.lastrowidreturn success(insertId)except MySQLdb.Error as e:conn.rollback()return error(1, '回复失败')@app.route('/reply/edit') 
def replyedit():(conn, cursor) = getConn()id = request.args.get("id", "0")content = request.args.get("content", "")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')try:sql = "update reply set content='%s',replyUserId=%s,replyUserNickename='%s' where id=%s and replyUserId=%s" % (content, userId, userNickename, id, userId)cursor.execute(sql)conn.commit()return success(None)except MySQLdb.Error as e:conn.rollback()return error(1, '编辑回复失败')@app.route('/reply/delete') 
def replydelete():(conn, cursor) = getConn()id = request.args.get("id", "0")sessionId = request.args.get("sessionId", "")userinfo = getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return error(1, '请先登录')sql = "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=%s" % idcursor.execute(sql)contentdata = cursor.fetchone()if contentdata is None:return error(1, '回复不存在')try:sql2 = "update content set replyNum=replyNum-1 where id=%s" % contentdata['contentId']cursor.execute(sql2)sql1 = "update reply set isDel=1 where id=%s and replyUserId=%s" % (id, userId)cursor.execute(sql1)conn.commit()return success(None)except MySQLdb.Error as e:conn.rollback()return error(1, '删除回复失败')if __name__ == "__main__":app.run(port=1089)

 

输出:

D:\workspace\studys\study_pys\pc_app\dist>D:\software\Python310\python.exe D:\workspace\studys\study_bbs\start_web_flask.py* Serving Flask app 'start_web_flask'* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.* Running on http://127.0.0.1:1089
Press CTRL+C to quit

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/791012.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

新电脑第一次拉取仓库代码

为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置git config --global user.name xxxxxxxx git config --global user.email xxxxxxxx初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置1 生成 RSA 密钥ssh-keygen -t rsa2 获取 RSA 公…

java~重写hashcode和equals

单字段和多字段重写hashcode 在 Java 中,重写 hashCode 方法的场景通常与对象的哈希值计算有关,特别是在使用哈希表(如 HashMap, HashSet 等)时。下面是你提供的两种 hashCode 实现的具体使用场景分析: 1. 第一种实现 @Override public boolean equals(Object o) {if (thi…

鱼眼相机成像模型和畸变模型

一文详解分析鱼眼相机投影成像模型和畸变模型 - feng..liu - 博客园 (cnblogs.com) 深入洞察OpenCV鱼眼模型之成像投影和畸变表估计系数相互转化 - 知乎 (zhihu.com)

第十二周-云计算运维作业

总结zabbix安装过程(选择课程演示版本)。1. 下载仓库 # wget https://repo.zabbix.com/zabbix/6.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_6.0-4+ubuntu22.04_all.deb # dpkg -i zabbix-release_6.0-4+ubuntu22.04_all.deb # apt update 2. 安装Zabbix server,W…

OpenCV开发笔记(八十):基于特征点匹配实现全景图片拼接

前言一个摄像头视野不大的时候,我们希望进行两个视野合并,这样让正视的视野增大,从而可以看到更广阔的标准视野。拼接的方法分为两条路,第一条路是Sticher类,第二条思路是特征点匹配。  本篇使用特征点匹配,进行两张图来视野合并拼接。 Demo100%的点匹配  换了一幅图…

中国最著名十大风水大师排名

风水大师,又称阴阳先生,因为它们常常在看风水时利用阴阳学说进行解释,于是便有了这样的称谓。风水大师从古至今非常之多,其中也不乏江湖骗子。本期风水大师就来说说中国知名的有真材实料的风水大师吧。 中国最著名十大风水大师排名 Top1裴翁 裴翁(又名裴伟胜),是世界地理名…

从实在智能最新发布的实在Agent 7.0,看RPA Agent的迭代升级

智能体进化发展了一年,现在的RPA Agent迭代到什么程度了? 从实在智能最新发布的实在Agent 7.0,看RPA Agent的迭代升级 抓取豆瓣信息、自己制作PPT,这款AI Agent真的实现了流程全自动化 AI Agent构建到执行全自动化,持续进化RPA Agent再次降低智能体应用门槛 实在智能重磅发…

丝滑解决Chatgpt频繁奔溃、断网掉线问题

这段时间使用Chatgpt的时候频繁出现`something wrong`等断网掉线问题,中间还频繁出现物品转向的人机验证(我那么具有迷惑性吗...),被烦的不行。后面了解到有一个**KeepChatgpt**的插件可以解决这些问题,于是把这个方法介绍给大家,希望大家也都可以丝滑gpt。事件缘由 这段…

周赛413场 个人总结

周赛413场 个人总结第1题 代码 """ 根据a的ascii码值是97 奇数 黑色的规律是: a1是 97 + 1 = 偶数 b2 是 98 + 2 =偶数 c1 是99 +1 = 偶数 d2 是100 + 2 = 偶数 ... 所以,偶数为黑色 === 白色的规律 a2 = 97 +2 = 奇数 b1 = 98 +1 = 奇数 .... 所以,奇数为…

【LaTex、markdown】常用语法写出漂亮的blog

@目录markdown加粗斜体设置标题级别设置目录删除线无序列表有序列表分割线代办引用高亮标记字体颜色代码块图片链接表格公式表达行中公式独行公式LaTex初步文章骨干换行与换页figure(基本是图片)表格公式公式字体颜色左右居中figure引用文献引用markdown 加粗 **加粗样式**格…

YOLOS:大道至简,直接使用预训练ViT进行实时目标检测 | NeurIPS 2021

论文探索了在中型ImageNet-1k数据集上预训练的普通ViT到更具挑战性的COCO目标检测基准的可迁移性,提出了基于Vision Transformer的You Only Look at One Sequence(YOLOS)目标检测模型。在具有挑战性的COCO目标检测基准上的实验结果表明,2D目标检测可以以纯sequence-to-sequen…

MetaLlama大模型

llama 大模型介绍我们介绍 LLaMA,这是一个基础语言模型的集合,参数范围从 7B 到 65B。我们在数万亿个Token上训练我们的模型,并表明可以专门使用公开可用的数据集来训练最先进的模型,而无需诉诸专有的和无法访问的数据集。特别是,LLaMA-13B 在大多数基准测试中都优于 GPT-…