本文章涉及到Flask框架和HTML内容,相关知识可查看链接
HTML-form表单和提交_html form 提交_小梁今天敲代码了吗的博客-CSDN博客https://blog.csdn.net/weixin_43780415/article/details/130110722
前端引入和html标签_小梁今天敲代码了吗的博客-CSDN博客https://blog.csdn.net/weixin_43780415/article/details/130090994
HTML超链接和简单登陆界面_小梁今天敲代码了吗的博客-CSDN博客https://blog.csdn.net/weixin_43780415/article/details/130097939上一次我们知道了Python如何连接MySQL,现在我们通过Flask框架,将网页上收到的内容,存进数据库中
将网页收集数据存储至MySQL中:
(Python代码)
from flask import Flask,render_template,request
import pymysql
app = Flask(__name__)
@app.route("/add/user",methods=['GET','POST'])
def add_user():
if request.method == "GET":
return render_template("add_user.html")
username = request.form.get("user")
password = request.form.get("pwd")
mobile = request.form.get("mobile")
#1.连接MySQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="123456",charset="utf8",db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#2.执行SQL
sql="insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql,[username,password,mobile])
conn.commit()
#3.关闭连接
cursor.close()
conn.close()
return "添加成功"
if __name__ == '__main__':
app.run()
(HTML代码)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/add/user">
<input type="text" name="user" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号">
<input type="submit" value="提 交">
</form>
</body>
</html>
在此界面输入内容,点击提交后,添加入MySQL中
将MySQL数据展现到网页上:
from flask import Flask,render_template,request
import pymysql
app = Flask(__name__)
@app.route("/show/user")
def show_user():
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="123456", charset="utf8", db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标
# 2.发送指令
sql = "select * from admin"
cursor.execute(sql)
data_list = cursor.fetchall()# :将返回所有结果,返回二维元组,如((‘id’,‘title’),(‘id’,‘title’)),
# for row_dict in data_list:
# print(row_dict)
# 3.关闭
cursor.close()
conn.close()
print(data_list)
#1.找到index.html文件,读取所有的内容
#2.找到内容中“特殊占位符”,将数据替换
#3.将替换完成的字符串返回给用户的浏览器
return render_template("show_user.html",data_list=data_list)
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>手机号</th>
</tr>
</thead>
<tbody>
{% for item in data_list %}<!--把数据库中每一项数据挨个呈现-->
<tr>
<td>{{item.id}}</td>
<td>{{item.username}}</td>
<td>{{item.password}}</td>
<td>{{item.mobile}}</td>
</tr>
{% endfor%}
</tbody>
</table>
</body>
</html>
我们发现MySQL中的admin表已经可以在网页上呈现了