文章评论区
背景是我的文章需要一个评论区,且已经建立好了mysql数据库
pymysql的准备
我写了一个用于插入的pymysql代码
先上代码
有些地方将会在后面说到
from pymysql import Connection
from config import host #拿取host
import gettime #请见后续时间获取
import where #请见后续根据ip爬取地点
def MI(table,name,ip,text):
city = where.getWhere(ip)
time=gettime.gettime()
mysqlInsertTable(table,"0",name,ip,text,f"{time}",f"{city}")
def MR(table):
comment=mysqlReadTable(table)
return comment
def mysqlInsertTable(table,row,name,text,str) :
con = None
try:
con = Connection(
host=host,
port=3306,
user='',
password='',
database="",
autocommit=True # 设置自动提交
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
# 获取游标对象
cursor = con.cursor()
# 使用游标对象,执行sql语句
sql = f"INSERT IGNORE INTO {table} (id, name, text,...) VALUES (%s, %s, %s,....)"
values = (row, name,text,.......)
cursor.execute(sql, values)
#PS:这里形式非常重要 以此形式写入数据库能防止数据库被侵入
print("id=", con.insert_id())
except Exception as e:
print("error", e)
finally:
if con:
con.close()
PS:这里形式非常重要 以此形式写入数据库能防止数据库被侵入
为了保证安全这里一定要注意
sql = f"INSERT IGNORE INTO {table} (id, name, text,...) VALUES (%s, %s, %s,....)"
values = (row, name,text,.......)
cursor.execute(sql, values)
其他就是常规操作
评论的读取以及展示
后端
每篇文章 我准备了一个table
当需要读取的时候 每篇文章读自己相应的table
下面是我测试阶段的数据库样板
id | name | text | 。。。 | |
---|---|---|---|---|
1 | 筑基期修士 | 你好 | 。。。 |
当展示的时候
我先用刚刚提到的代码中缺少的mysqlReadTable(table) 函数
去读取整个表
def mysqlReadTable(table) :
con = None
try:
con = Connection(
host=host,
port=3306,
user='titoweb',
password='Wochaoshuai666',
database="titoweb"
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
# 创建游标对象
cursor = con.cursor()
cursor.execute("select * from "+table)
# 获取查询所有结果
result = cursor.fetchall()
return result
# print(type(result), result)
# for row in result:
# print(row)
except Exception as e:
print("error", e)
finally:
if con:
con.close()
返回到flask框架后 我们读取最后一个id减轻处理前端负担
(注意pymysql直接给回的是元组 我们必须将其变为有序 否则处理棘手)
@app.route('/get_comments/<title>', methods=['GET'])
def get_comments(title):
q=list(mysql.MR(f"{title}"))
#有序化
num=q[-1][0]
#读取最后一位
return jsonify(data=q,num=num)
#json返回
前端
拿到手后只需要根据num来循环放置即可展示
<div id="comments">
<!-- 评论将在这里动态显示 -->
</div>
function fetchComments() {
fetch('/get_comments/qianru2')
.then(response => response.json())
.then(data => {
// 在页面上动态显示评论
const ar = data.data
// 获取二维数据
const n = data.num
console.log(ar)
const commentsDiv = document.getElementById('comments');
for (var i = 0; i < n; i++) {
const timeElement = document.createElement('div');
timeElement.textContent = ar[i][];
//根据自己数据库调整即可
commentsDiv.appendChild(timeElement);
}
});
}
window.onload = fetchComments;
// 在页面加载时请求评论数据
评论的写入
前端(正常操作我就不多说了)
<form id="data-form" action="/process_data" method="POST">
<label for="data">输入信息:</label>
<input type="text" id="data" name="data">
<button type="submit">提交</button>
<p id="error-message" style="color: red;"></p>
</form>
document.getElementById('data-form').addEventListener('submit', function(event) {
var dataInput = document.getElementById('data');
var errorMessage = document.getElementById('error-message');
if (dataInput.value.trim() === '') {
errorMessage.textContent = '输入框不能为空';
event.preventDefault(); // 阻止表单提交
} else {
errorMessage.textContent = ''; // 清空错误消息
}
});
到后端
@app.route('/process_data', methods=['POST'])
def process_data():
data = request.form['data']
if data.strip() == '':
return '输入框不能为空'
# 在这里你可以对数据进行处理
return f'接收到的信息为: {data}'
再到数据库
我们对上面的前后端代码改造
前端
我们增加一个信息位来让评论的人
写入自己的大名
后端:
@app.route('/ping/<title>', methods=['POST'])
def ping(title):
table = title
ip = request.remote_addr
#flask获取ip
name = request.form['name']
text = request.form['data']
if text.strip() == '' or name.strip() == '':
error_message = '''错误'''
return error_message
# 在这里你可以对数据进行处理
MI(table, name, ip, text)
#前面提到的MI插入函数
return render_template(f"/article/{title}.html")
#这里起到刷新作用
时间和位置的解析
前面我们做到了基础评论
现在我们给他上个时间和位置
时间:
import datetime
def gettime():
# 返回字符串 实例:2023-10-12 15:33:22
return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
位置:
位置我是对ip进行分析处理
我借用了网上的ip查询网址
通过爬取信息
来分析位置
import requests
import re
def getWhere(ip):
url = "".format(ip)
headers = {
}
#以上是爬取url 和反爬的用户模拟
# 获取响应
response = requests.get(url=url, headers=headers)
response.encoding = ""
#编码信息
text = response.text
info =
#对得到的text处理成字典返回主程序
#因个人情况而变
return info
综合以上 你就能明白如何利用数据库去做你想做的事情