hzyuhz 2020-05-04
需求:通过页面点击完成简单的投票系统功能。
相关文件:

设计思路:
1、前端:提供可以投票的入口。查询的入口。(前端不做数据处理,只做展示)
使用<a> </a> 完成超链接的接收数据
设置超链接的按钮:提供投票和查询功能
2、后端:数据存储:可以通过txt文件做简单的数据存储。提供新增数据的接口,查询的接口。
数据存储为字典格式,放在txt文件中。
voteF.txt:{‘1号‘: 104, ‘2号‘: 44}
在app.py中写3个接口:
3、具体页面实现截图:
请求链接:http://127.0.0.1:5000/test



备注:投票的是同个接口,只是参数不同。

4、相关代码
voteF.txt
{‘1号‘: 108, ‘2号‘: 44}app.py
from flask import Flask, render_template, jsonify, request, redirect, url_for
import os
app = Flask(__name__)
app.config.update(DEBUG=False)
@app.route(‘/test‘, methods=[‘GET‘])
def test():
# print(namme)
return render_template(‘output.html‘)
@app.route(‘/vote/<string:name>/‘,methods=[‘GET‘, ‘POST‘])
def vote(name):
F = open("D:\\XXX\\static\\voteF.txt","r+",encoding="utf-8")
votelist = F.read()
print(votelist)
F.close()
tmp = eval(votelist)#读取的str转换为字典
print(tmp)
for key,value in tmp.items():
if name == key://如果名字会等于key
tmp.get(key,value)
# print(key,value)
tmp[key] = value + 1//将key的value+1
F = open("D:\\XXX\\static\\voteF.txt", "w+",encoding="utf-8")
F.write(str(tmp))//写入文件中
F.close()
# return render_template(‘output.html‘)
print("投票成功")
return "为{}投票成功".format(name)
@app.route(‘/voteF.txt‘)
def query():
# F = open("voteFF.txt", "r+")
# lines = F.read()
# return render_template(‘output.html‘, lines = lines)
return redirect(url_for(‘static‘,filename=‘voteF.txt‘))
html
<body style="color:black">
<a href="http://127.0.0.1:5000/vote/1号/">为1号投票</a>
<a href="http://127.0.0.1:5000/vote/2号/">为2号投票</a><br>
<a href="http://127.0.0.1:5000/static/voteF.txt" οnclick="location.reload()">查看当前票数 <object><meta http-equiv="refresh" content="1" ></object></a>
</body>丸子要加油呀
by:丸子