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

news/2024/11/13 20:31:50/文章来源:https://www.cnblogs.com/xuxiaobo/p/18392600

代码:

import web
import os.path
import MySQLdb
import json
import hashlib
import random
import math
import os
from datetime import datetimeclass 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)urls = ('/', 'indexHandler','/user/register', 'RegisterHandler','/user/login', 'LoginHandler','/user/logout', 'LogoutHandler','/user/getuserinfo', 'GetuserinfoHandler','/post/list', 'PostlistHandler','/post/detail', 'PostdetailHandler','/post/add', 'PostaddHandler','/post/edit', 'PosteditHandler','/post/delete', 'PostdeleteHandler','/reply/list', 'ReplylistHandler','/reply/detail', 'ReplydetailHandler','/reply/add', 'ReplyaddHandler','/reply/edit', 'ReplyeditHandler','/reply/delete', 'ReplydeleteHandler'
)class BaseHandler:conn = Nonecursor = NonesecretKey = 'saacac3423@21212'pagesize = 20def __init__(self):self.conn = MySQLdb.Connection('127.0.0.1', 'root', '123456', 'my_bbs')self.cursor = self.conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)def __del__(self):self.cursor.close()self.conn.close()def get_argument(self, name, default = ''):i = web.input()if name in i:if name == "id":return i.idelif name == "sessionId":return i.sessionIdelif name == "page":return i.pageelif name == "keyword":return i.keywordelif name == "username":return i.usernameelif name == "password":return i.passwordelif name == "nickname":return i.nicknameelif name == "title":return i.titleelif name == "content":return i.contentelif name == "contentId":return i.contentIdelse:return defaultdef getloginuserinfo(self, sessionId):try:sessionIdHead = self.get_secure_cookie("sessionId")except:sessionIdHead = ''if sessionIdHead is not None and sessionIdHead != '':sessionId = sessionIdHeadsql = "select id,username,nickname,addTime,sessionId from user where sessionId='%s'" % sessionIdself.cursor.execute(sql)data = self.cursor.fetchone()if data is None:data = {'id' : 0, 'username' : '', 'nickname' : '', 'addTime' : '', 'sessionId' : ''}return datadef response(self, 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)web.header('Content-Type', 'text/plain; charset=utf-8')web.header('Server', 'webpy-Framework')return resultdef error(self, code, msg):return self.response(code, msg, None)def success(self, data = {}):return self.response(0, '', data)class indexHandler(BaseHandler):def GET(self):web.header('Content-Type', 'text/plain; charset=utf-8')web.header('Server', 'webpy-Framework')return "此站接口使用python.webpy实现,<a href='api.html' target='_blank'>接口列表</a>"class RegisterHandler(BaseHandler):def GET(self):username = self.get_argument("username", "")password = self.get_argument("password", "")nickname = self.get_argument("nickname", "")sql = "select id,username,nickname,addTime from user where username='%s'" % usernameself.cursor.execute(sql)data = self.cursor.fetchone()if data != None:return self.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)self.cursor.execute(sql)self.conn.commit()insertId = self.cursor.lastrowidreturn self.success(insertId)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '注册失败')class LoginHandler(BaseHandler):def GET(self):username = self.get_argument("username", "")password = self.get_argument("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)self.cursor.execute(sql)data = self.cursor.fetchone()if data == None:return self.error(1, '用户名或者密码错误')tmpSessionId = self.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'])self.cursor.execute(sql)self.conn.commit()data['sessionId'] = tmpSessionIdreturn self.success(data)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '保存会话id失败')class LogoutHandler(BaseHandler):def GET(self):sessionId = self.get_argument("sessionId", "")data = super().getloginuserinfo(sessionId)if data == None:return self.success(None)if data['sessionId'] == '':return self.success(data)try:sql = "update user set sessionId='' where sessionId='%s'" % sessionIdself.cursor.execute(sql)self.conn.commit()data['sessionId'] = ''return self.success(data)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '删除会话id失败')class GetuserinfoHandler(BaseHandler):def GET(self):sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)return self.success(userinfo)class PostlistHandler(BaseHandler):def GET(self):page = self.get_argument("page", "1")keyword = self.get_argument("keyword", "")if page == "":page = 1page = 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) * self.pagesizesql1 = "select count(1) as count from content where %s" % addsqlself.cursor.execute(sql1)countdata = self.cursor.fetchone()totalpage = math.ceil(countdata['count'] / float(self.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, self.pagesize)self.cursor.execute(sql2)data = self.cursor.fetchall()return self.success({'totalpage' : totalpage, 'data' : data})class PostdetailHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")sql = "select id,title,content,userId,userNickename,replyNum,updateTime from content where isDel=0 and id=%s" % idself.cursor.execute(sql)data = self.cursor.fetchone()return self.success(data)class PostaddHandler(BaseHandler):def GET(self):title = self.get_argument("title", "")content = self.get_argument("content", "")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.error(1, '请先登录')try:sql = "insert into content(title, content, userId, userNickename) value('%s', '%s', %s, '%s')" % (title, content, userId, userNickename)self.cursor.execute(sql)self.conn.commit()insertId = self.cursor.lastrowidreturn self.success(insertId)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '发帖失败')class PosteditHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")title = self.get_argument("title", "")content = self.get_argument("content", "")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.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)self.cursor.execute(sql)self.conn.commit()return self.success(None)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '编辑帖子失败')class PostdeleteHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.error(1, '请先登录')try:sql = "update content set isDel=1 where id=%s and userId=%s" % (id, userId)self.cursor.execute(sql)self.conn.commit()return self.success(None)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '删除帖子失败')class ReplylistHandler(BaseHandler):def GET(self):page = self.get_argument("page", "1")contentId = self.get_argument("contentId", "0")if page == "":page = 1page = int(page)if page <= 0:page = 1start = (page - 1) * self.pagesizesql1 = "select count(1) as count from reply where isDel=0 and contentId=%s" % contentIdself.cursor.execute(sql1)countdata = self.cursor.fetchone()totalpage = math.ceil(countdata['count'] / float(self.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, self.pagesize)self.cursor.execute(sql2)data = self.cursor.fetchall()return self.success({'totalpage' : totalpage, 'data' : data})class ReplydetailHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")sql = "select id,content,replyUserId,replyUserNickename,addTime from reply where isDel=0 and id=%s" % idself.cursor.execute(sql)data = self.cursor.fetchone()return self.success(data)class ReplyaddHandler(BaseHandler):def GET(self):contentId = self.get_argument("contentId", "0")content = self.get_argument("content", "")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.error(1, '请先登录')try:sql2 = "update content set replyNum=replyNum+1 where id=%s" % contentIdself.cursor.execute(sql2)sql1 = "insert into reply(contentId, content, replyUserId, replyUserNickename) value(%s, '%s', %s, '%s')" % (contentId, content, userId, userNickename)self.cursor.execute(sql1)self.conn.commit()insertId = self.cursor.lastrowidreturn self.success(insertId)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '回复失败')class ReplyeditHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")content = self.get_argument("content", "")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.error(1, '请先登录')try:sql = "update reply set content='%s',replyUserId=%s,replyUserNickename='%s' where id=%s and replyUserId=%s" % (content, userId, userNickename, id, userId)self.cursor.execute(sql)self.conn.commit()return self.success(None)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '编辑回复失败')class ReplydeleteHandler(BaseHandler):def GET(self):id = self.get_argument("id", "0")sessionId = self.get_argument("sessionId", "")userinfo = super().getloginuserinfo(sessionId)userId = userinfo['id']userNickename = userinfo['nickname']if userId <= 0:return self.error(1, '请先登录')sql = "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where isDel=0 and id=%s" % idself.cursor.execute(sql)contentdata = self.cursor.fetchone()if contentdata is None:return self.error(1, '回复不存在')try:sql2 = "update content set replyNum=replyNum-1 where id=%s" % contentdata['contentId']self.cursor.execute(sql2)sql1 = "update reply set isDel=1 where id=%s and replyUserId=%s" % (id, userId)self.cursor.execute(sql1)self.conn.commit()return self.success(None)except MySQLdb.Error as e:self.conn.rollback()return self.error(1, '删除回复失败')if __name__ == "__main__":app = web.application(urls, globals())app.run()

 

输出:

D:\workspace\studys\study_pys\pc_app\dist>D:\software\Python310\python.exe D:\workspace\studys\study_bbs\start_web_webpy.py 1092
http://0.0.0.0:1092/

 

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

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

相关文章

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

代码: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):…

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

为确保你提交的代码身份被 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…