flask完成前後端分離實例

需求:通過頁面點擊完成簡單的投票系統功能。

相關文件:

  

 設計思路:

1、前端:提供可以投票的入口。查詢的入口。(前端不做數據處理,只做展示)

使用<a>  </a> 完成超鏈接的接收數據

設置超鏈接的按鈕:提供投票和查詢功能

2、後端:數據存儲:可以通過txt文件做簡單的數據存儲。提供新增數據的介面,查詢的介面。

數據存儲為字典格式,放在txt文件中。 

voteF.txt:{‘1號’: 104, ‘2號’: 44}

在app.py中寫3個介面:

  • 請求介面可返回html頁面
  • 請求投票介面可以更新數據到txt文件中
  • 請求查詢介面可以返回最新的txt文件數據

3、具體頁面實現截圖:

請求鏈接://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="//127.0.0.1:5000/vote/1號/">為1號投票</a>
    <a href="//127.0.0.1:5000/vote/2號/">為2號投票</a><br>
<a href="//127.0.0.1:5000/static/voteF.txt" οnclick="location.reload()">查看當前票數 <object><meta http-equiv="refresh" content="1" ></object></a>
  </body>

  

 

丸子要加油呀

 by:丸子

 

Tags: