Implementation of Motivation Technology Route Planning of Python-based Sports Billing Management System

Implementation of Motivation Technology Route Planning of Python-based Sports Billing Management System

motivation

My friends have recently become obsessed with badminton. They organized a small group and set up a public sports card for the opening. Considering that not every activity is full participation, a billing system is needed to calculate the cost of each person. After discussing and deciding to adopt the "pre-charge-deduction" method, a system is required for billing and deduction.

Technical route planning

Module name

Language

Remarks

Management core

Python

Use JSON to store information

Web backend

Python

Flask framework

Web front end

HTML

Jinja frame rendering

achieve

Core module-user status management

This part is the core of the entire billing system and is used to manage the balance of each user. Use a class to represent the user, the required attributes are

  • Status list (username, ID, usage times, balance)

The required methods are:

  • Create user (create new JSON file)
  • Read user status (from existing JSON file)
  • Deduction (the number of uses increases by 1, the balance decreases)
  • Recharge (increased balance)
  • Save state (write existing state into JSON file)

code show as below

# -*- coding: utf-8 -*-
import json
import os


class UserHanlde(object):
    """docstring for UserHanlde"""

    def __init__(self, UserID, UserName=""):
        super(UserHanlde, self).__init__()
        if self.UserExsist(UserID):
            self.UserInfo = self.LoadUserInfo(UserID)
        else:
            self.UserInfo = self.CreateNewUser(UserName, UserID)

Constructor, if the user ID exists, read the status, otherwise create

    def UserExsist(self, UserID):
        return os.path.exists("./Users/%s.json"% UserID)

Determine whether the JSON file of the ID exists

    def CreateNewUser(self, UserName, UserID):
        UserInfo = {
            "name": UserName,
            "id": UserID,
            "num": 0,
            "balance": 50
        }
        with open("./Users/%s.json"% UserID, "w") as jsonfile:
            json.dump(UserInfo, jsonfile, ensure_ascii=False, indent=4)
        return UserInfo

Create a new user, set the initial balance to 50 and save the JSON file

    def LoadUserInfo(self, UserID):
        with open("./Users/%s.json"% UserID, "r") as jsonfile:
            return json.load(jsonfile)

Load user status from JSON file

    def PlayOneTime(self, Pay):
        self.UserInfo["num"] += 1
        self.UserInfo["balance"] = self.UserInfo["balance"]-Pay

Deduction, deduct the specified fee and increase the number of deductions by +1

    def Recharge(self, Pay):
        self.UserInfo["balance"] += Pay

Recharge, the fee plus the specified value

    def DeleteUser(self):
        os.remove("./Users/%s.json"% self.UserInfo["id"])

Delete user, delete the specified JSON file

    def SaveInfo(self):
        with open("./Users/%s.json"% self.UserInfo["id"], "w") as jsonfile:
            json.dump(self.UserInfo, jsonfile, ensure_ascii=False, indent=4)

Save the state, write the current state to the corresponding JSON file

Web backend

The web backend is constructed using Python's Flask framework, the code is as follows

from flask import Flask, render_template, request
from UserHanlde import UserHanlde
import os
app = Flask(__name__)


def GetUserIDList():
    return [x[:-5] for x in os.listdir("./Users") if ".json" in x]

def GetUserInfoList():
    UserInfoList = dict()
    for UserID in GetUserIDList():
        UserData = UserHanlde(UserID)
        UserInfoList[UserID] = UserData.UserInfo
    return UserInfoList

Encapsulation of common parts:

  • GetUserIDList(): Return a list of user IDs that already exist
  • GetUserInfoList():Return to the existing user status list
@app.route("/index")
def ViewInfo():
    return render_template("index.html", user_list=GetUserInfoList())


@app.route("/recharge")
def GetReChargeInfo():
    return render_template("recharge.html", user_list=GetUserInfoList())


@app.route("/recharge_handle", methods=["GET", "POST"])
def Recharge():
    UserID = request.values.get("id")
    UserRecharge = request.values.get("pay")
    if UserRecharge.isdigit() is True:
        UserHanlder = UserHanlde(UserID)
        UserHanlder.Recharge(int(UserRecharge))
        UserHanlder.SaveInfo()
        return render_template("back.html")
    else:
        return "fail"


@app.route("/register")
def GetRegisterInfo():
    return render_template("register.html")


@app.route("/register_handle", methods=["GET", "POST"])
def Register():
    UserID = request.values.get("id")
    UserName = request.values.get("name")
    UserHanlder = UserHanlde(UserID, UserName=UserName)
    return render_template("back.html")


@app.route("/pay")
def GetPayName():
    return render_template("pay.html", user_list=GetUserInfoList())


@app.route("/pay_handle", methods=["GET", "POST"])
def Pay():
    UserIDList = request.values.getlist("vehicle")
    UserIDPay = request.values.get("pay")
    if UserIDPay.isdigit() is True:
        PayNum = int(UserIDPay)/len(UserIDList)
        for UserID in UserIDList:
            UserHanlder = UserHanlde(UserID)
            UserHanlder.PlayOneTime(PayNum)
            UserHanlder.SaveInfo()
        return render_template("back.html")
    else:
        return "fail"

Routing part

  • /index: Home page, including navigation and status display, all users' consumption times and balance will be displayed here
  • /rechargeAnd /recharge_handle: the top-up page, which /rechargeis the operation page, where the user fills in the form data, and then the form data is submitted to /recharge_handleprocess the top-up business
  • /registerAnd /register_handle: registration page, the same relationship with /rechargeand/recharge_handle
  • /payAnd /pay_handle: Deduction page, the same as /rechargeand /recharge_handlerelationship
app.run(host="0.0.0.0")

Run, monitor all IP, so you can access it on the LAN

Web front end

Web uses HTML code to provide GUI and Jinja framework to separate data and templates

  • index interface
<!DOCTYPE html>
<html>
<head>
    <title>index</title>
</head>
<body>
    <div>
        <h1>Badminton sports management system</h1>
    </div>
    <div>
        <table border="1">
            <thead>
                <tr>
                    <th>User</th>
                    <th>Number of times</th>
                    <th>Balance</th>
                </tr>
            </thead>
            <tbody>
                {% for user_id in user_list -%}
                <tr>
                    <td>{{user_list[user_id]["name"]}}</td>
                    <td>{{user_list[user_id]["num"]}}</td>
                    <td>{{user_list[user_id]["balance"]}}</td>
                </tr>
                {%- endfor %}
            </tbody>
        </table>
    </div>

User status display, use for loop to generate table

    <div>
        <a href="register">register</a>
        <a href="recharge">recharge</a>
        <a href="pay">pay</a>
    </div>
</body>
</html>

Hyperlink part for navigation

  • register interface
<!DOCTYPE html>
<html>
<head>
    <title>register</title>
</head>
<body>
    <h1>Badminton Sports Management System--Registration</h1>
    <div>
        <form action="register_handle" method="post" accept-charset="utf-8">
            name<input type="text" name="name">
            id<input type="text" name="id">
            <input type="submit" name="Submit">
        </form>
    </div>
    <a href="/index">back to index</a>
</body>
</html>

Use two text input box forms to enter the user name and user ID

  • recharge interface
<!DOCTYPE html>
<html>
<head>
    <title>recharge</title>
</head>
<body>
    <div>
        <h1>Badminton sports management system-recharge</h1>
    </div>
    <div>
        <form action="recharge_handle" method="post" accept-charset="utf-8">
            <select name="id">
                {% for userid in user_list -%}
                <option value="{{userid}}">{{user_list[userid]["name"]}}</option>
                {%- endfor %}
            </select>
            recharge¥<input type="text" name="pay">
            <input type="submit" name="Submit">
        </form>
    </div>
    <a href="/index">back to index</a>
</body>
</html>

Use the drop-down menu to provide a user name to choose from, and enter the recharge amount in text

  • pay interface
<!DOCTYPE html>
<html>
<head>
    <title>pay</title>
</head>
<body>
    <h1>Badminton sports management system-consumption</h1>
    <div>
        <form action="pay_handle" method="post" accept-charset="utf-8">
            <div>
                {%for userid in user_list%}
                <input type="checkbox" name="vehicle" value="{{userid}}">{{user_list[userid]["name"]}}<br>
                {% endfor %}
            </div>
            pay¥<input type="text" name="pay">
            <input type="submit" name="Submit">
        </form>
    </div>
    <a href="/index">back to index</a>
</body>
</html>

Use checkboxes to list all user-provided choices, text input total input amount, checkbox form data is used in the back-end to request.values.getlist("name")obtain a list

  • back interface
<!DOCTYPE html>
<html>
<head>
    <title>back</title>
</head>
<body>
    <a href="/index">back to index</a>
</body>
</html>

Used to return to the homepage when the user completes recharge/registration/consumption

Reference: https://cloud.tencent.com/developer/article/1110605 Implementation of Motivational Technical Route Planning for Sports Billing Management System Based on Python-Cloud + Community-Tencent Cloud