Monday, February 26, 2024

Python 練習

 

Shopping Cart Module

Functional Requirements

You are to prototype business logic for an online shopping cart. Eventually, the user will enter information into an HTML form and hit "Submit". This will trigger Python logic processing the order. The results of the order will be converted to JSON for storage in a NoSQL database. 

For this current assignment, you can ignore the presentation layer (the HTML form). Instead, prototype the logic by letting the user (who will be a tester on your team), respond to command line prompts and enter data like "product id", "product name", "price", "customer id", etc. Use at least four data fields - more if you are feeling ambitious!

Likewise, ignore the part of the data layer that involves implementing the actual NoSQL database. For now, use .json files as your data storage mechanism. When you create the .json files, be sure to use some key field like order_number in the file name so you can retrieve each order from your file system. To finish the project, write a some code to search for orders by order number, read the JSON from the selected file, and present complete information from the order on the Python command line. 

ユーザー入力DataをJSON 形式で保存・追加:

import os
import json
input_id = input("Enter order #: ")
input_product_no = input("Enter product #: ")
input_productname = input("Enter product name: ")
input_price = input("Enter price: ")
with open('store_jsonfile.json',
    mode="r",
    encoding="utf-8") as file:
    orders = json.load(file)
    #print(orders)
    orders[input_id] = {"product_sku": input_product_no, "productname": input_productname, "price": input_price}
    #print(orders)
with open('store_jsonfile.json',
    mode="w",
    encoding="utf-8") as file:
    json.dump(orders, file, indent=4)

検索して表示:

import os
import json
input_id = input("Enter order #: ")
with open('store_jsonfile.json', mode="r", encoding="utf-8") as file:
    orders = json.load(file)
    
    order = orders[input_id]
    print("Order #: ", input_id)
    print("Product SKU: ", order['product_sku']) 
    print("Product Name: ", order['productname'])
    print("Price: ", order['price'])


参考:https://youtu.be/pq5aRRf8acI

No comments:

Post a Comment