瀏覽代碼

buy api revised

CJYen 3 年之前
父節點
當前提交
39bb6033e2
共有 1 個文件被更改,包括 39 次插入11 次删除
  1. 39 11
      main.py

+ 39 - 11
main.py

@@ -282,7 +282,7 @@ async def receive(userModel : models.TransactionNft):
 def shop():
     # 為了顯示正確的nft網頁和數量,直接顯示nft表出來
     # db connect
-    db = dataset.connect('mysql://root:pAssw0rd@localhost:3306/arkcard?charset=utf8mb4')
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
     nfts = {}
     i = 0
     for row in db['nft']:
@@ -295,22 +295,50 @@ def shop():
 async def buy(userModel : models.BuyNft):
     # db connect
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/arkcard?charset=utf8mb4')
-    table2 = db['nft']
+    table1 = db['users']
+    table2 = db['ownership']
+    table3 = db['nft']
+    table4 = db['transactions']
+    shops = "shop"
+    hash = "hash"
 
     # input
-    nftid = userModel.nftid
-    userid = userModel.userid
+    the_list = userModel.dic
+    address = userModel.address
+    # 例:
+    # {
+    #   "address": "d04",
+    #   "dic": {"1":"2","2":"3"}
+    # }
+
+    result1 = table1.find_one(address=address)
 
-    if not table2.find_one(id=nftid):
+    # 找不到該使用者就回報錯誤
+    if not result1:
         db.close()
-        print("error: nft not found")
-        return "該NFT商品不存在!如果有疑問,請洽網站的服務信箱!"
+        return "該用戶不存在!如果有疑問,請洽網站的服務信箱!"
     else:
-        user_obj = table2.find_one(id=nftid)
-        user_obj['userid'] = userid
-        table2.update(dict(user_obj), ['id'])
+        for nftid, amount in the_list.items():
+            # 先user找到該使用者的userid留著備用
+            userid = result1['userid']
+
+            # 更新到ownership
+            owner_data = [dict(userid=userid, address=address, nftid=nftid, amount=int(amount))]
+            table2.insert_many(owner_data)
+
+            # 更新nft數量
+            result3 = table3.find_one(nftid=nftid)
+            nft_total = result3['amount']
+            total = int(nft_total) - int(amount)
+            nft_data = dict(nftid=nftid, amount=int(total))
+            table3.update(nft_data, ['nftid'])
+
+            # 最後再來處理transactions
+            now = dt.datetime.now()
+            trans_data = dict(to_token=address, time=now, amount=int(amount), userid=userid, from_token=shops, hash=hash)
+            table4.insert(trans_data)
         db.close()
-    return "您已購買成功!"
+        return "您已購買成功!"
 
 @app.post("/event")
 async def nftdrops(userModel : models.NftDrops):