楚阿旗

博客园 首页 新随笔 联系 订阅 管理

 

 

 1 # Import libraries
 2 from flask import Flask, redirect, request, render_template, url_for
 3 # Instantiate Flask functionality
 4 app = Flask(__name__)
 5 # Sample data
 6 transactions = [
 7     {'id': 1, 'date': '2023-06-01', 'amount': 100},
 8     {'id': 2, 'date': '2023-06-02', 'amount': -200},
 9     {'id': 3, 'date': '2023-06-03', 'amount': 300}
10 ]
11 # Read operation
12 @app.route("/")
13 def get_tansactions():
14     return render_template("transactions.html",transactions=transactions)
15 
16 # Create operation
17 @app.route("/add",methods=["GET","POST"])
18 def add_transaction():
19     if request.method == 'POST':
20         # Create a new transaction object using form field values
21         transaction = {
22             'id': len(transactions) + 1,
23             'date': request.form['date'],
24             'amount': float(request.form['amount'])
25         }
26         # Append the new transaction to the list
27         transactions.append(transaction)
28 
29         # Redirect to the transactions list page
30         return redirect(url_for("get_transactions"))
31     
32     # Render the form template to display the add transaction form
33     return render_template("form.html")
34 
35 # Update operation
36 @app.route("/edit/<int:transaction_id>",methods=['POST','GET'])
37 def edit_transaction(transaction_id):
38     if request.method == 'POST':
39         date = request.form['date']
40         amount = float(request.form['amount'])
41 
42         # Find the transaction with the matching ID and update its values
43         for transaction in transactions:
44             if transaction['id'] == transaction_id:
45                 transaction['date'] = date
46                 transaction['amount'] = amount
47                 break
48 
49         # Redirect to the ransactions list page
50         return redirect(url_for("get_transactions"))
51 
52     # Find the transaction with the matching ID and render the edit form
53     for transaction in transactions:
54         if transaction['id'] == transaction_id:
55             return render_template("edit.html", transaction=transaction)
56 
57 # Delete operation
58 @app.route("/delete/<int:transaction_id>")
59 def delete_transaction(transaction_id):
60     # Find the transaction with the matching ID and remove it from the list
61     for transaction in transactions:
62         if transaction['id'] == transation_id:
63             transactions.remove(transaction)
64             break
65 
66     # Redirect to the transactions list page
67 
68     return redirect(url_for("get_transactions"))
69 # Run the Flask app
70  if __name__ == "__main__":
    app.run(debug=True)

 

posted on 2024-03-20 23:57  楚阿旗  阅读(33)  评论(0)    收藏  举报