利用Python将数据库内的表单公开展现
这里提出这个需求是因为团队内的协作,和数据统计后的展现需要,需要将数据库中收集到的表单,提供出来,方便展现,用一个简单的方法。
我是用 LimeSurvey 项目收集的表单,需要数据公开,方法基于Python实现
首先创建一个路径,我们全部在这个路径中实现。
mkdir sqlinfo cd sqlinfo
编写py脚本:
from flask import Flask, render_template
from flask_basicauth import BasicAuth
import pymysql
app = Flask(__name__)
# Flask-BasicAuth 配置
app.config['BASIC_AUTH_USERNAME'] = 'your_username' # 配置身份验证
app.config['BASIC_AUTH_PASSWORD'] = 'your_password'
basic_auth = BasicAuth(app)
# MySQL 连接配置
db_config = {
'host': 'localhost',
'user': 'user',
'password': 'password',
'database': 'database',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor,
}
@app.route('/')
@basic_auth.required # 添加此以要求基本身份验证
def index():
# 在此编写你的 SQL 查询
sql_query = """
-- 你的 SQL 查询内容
"""
result = execute_sql_query(sql_query)
return render_template('index.html', result=result)
def execute_sql_query(sql):
connection = pymysql.connect(**db_config)
try:
with connection.cursor() as cursor:
cursor.execute(sql)
result = cursor.fetchall()
finally:
connection.close()
return result
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0') # 允许互联网访问创建文件夹:
mkdir templates/
编写一个前端页面放在templates路径下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- templates/index.html -->
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<title>冲锋号社区 - 个人信息收集表</title>
</head>
<body>
<div>
<h1>冲锋号社区 - 个人信息收集表</h1>
<table>
<!-- 表头 -->
<thead>
<tr>
<th>调查ID</th>
<th>提交日期</th>
... <!-- 其他的表头 -->
</tr>
</thead>
<!-- 表格数据 -->
<tbody>
{% for row in result %}
<tr>
<td>{{ row['调查ID'] }}</td>
<td>{{ row['提交日期'] }}</td>
... <!-- 其他的表头 -->
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>创建文件夹:
mkdir static/
编写一个css页面放在static路径下:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
width: 80%;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
tbody tr:hover {
background-color: #f5f5f5;
}启动python即可,以http访问5000端口。
发表评论