Browse Source

测试通过等待实现自动取消订单以及查询

master
杨舜 1 year ago
parent
commit
3081cb69a6
48 changed files with 47 additions and 1117 deletions
  1. BIN
      .coverage
  2. BIN
      be/__pycache__/serve.cpython-38.pyc
  3. BIN
      be/model/__pycache__/buyer.cpython-38.pyc
  4. BIN
      be/model/__pycache__/db_conn.cpython-38.pyc
  5. BIN
      be/model/__pycache__/postgreSQLORM.cpython-38.pyc
  6. BIN
      be/model/__pycache__/seller.cpython-38.pyc
  7. +11
    -11
      be/model/buyer.py
  8. +1
    -1
      be/model/db_conn.py
  9. +25
    -25
      be/model/postgreSQLORM.py
  10. +3
    -3
      be/model/seller.py
  11. +6
    -4
      be/serve.py
  12. BIN
      be/view/__pycache__/testconn.cpython-38.pyc
  13. +1
    -1
      be/view/testconn.py
  14. +0
    -0
      modified/be/__init__.py
  15. BIN
      modified/be/__pycache__/__init__.cpython-38.pyc
  16. BIN
      modified/be/__pycache__/app.cpython-38.pyc
  17. BIN
      modified/be/__pycache__/creatTB.cpython-38.pyc
  18. BIN
      modified/be/__pycache__/postgreSQLORM.cpython-38.pyc
  19. BIN
      modified/be/__pycache__/serve.cpython-38.pyc
  20. BIN
      modified/be/__pycache__/testconn.cpython-38.pyc
  21. +0
    -4
      modified/be/app.py
  22. +0
    -0
      modified/be/model/__init__.py
  23. BIN
      modified/be/model/__pycache__/__init__.cpython-38.pyc
  24. BIN
      modified/be/model/__pycache__/buyer.cpython-38.pyc
  25. BIN
      modified/be/model/__pycache__/creatTB.cpython-38.pyc
  26. BIN
      modified/be/model/__pycache__/db_conn.cpython-38.pyc
  27. BIN
      modified/be/model/__pycache__/error.cpython-38.pyc
  28. BIN
      modified/be/model/__pycache__/postgreSQLORM.cpython-38.pyc
  29. BIN
      modified/be/model/__pycache__/seller.cpython-38.pyc
  30. BIN
      modified/be/model/__pycache__/user.cpython-38.pyc
  31. +0
    -292
      modified/be/model/buyer.py
  32. +0
    -5
      modified/be/model/creatTB.py
  33. +0
    -35
      modified/be/model/db_conn.py
  34. +0
    -66
      modified/be/model/error.py
  35. +0
    -126
      modified/be/model/postgreSQLORM.py
  36. +0
    -104
      modified/be/model/seller.py
  37. +0
    -202
      modified/be/model/user.py
  38. +0
    -49
      modified/be/serve.py
  39. +0
    -0
      modified/be/view/__init__.py
  40. BIN
      modified/be/view/__pycache__/__init__.cpython-38.pyc
  41. BIN
      modified/be/view/__pycache__/auth.cpython-38.pyc
  42. BIN
      modified/be/view/__pycache__/buyer.cpython-38.pyc
  43. BIN
      modified/be/view/__pycache__/seller.cpython-38.pyc
  44. BIN
      modified/be/view/__pycache__/testconn.cpython-38.pyc
  45. +0
    -53
      modified/be/view/auth.py
  46. +0
    -64
      modified/be/view/buyer.py
  47. +0
    -51
      modified/be/view/seller.py
  48. +0
    -21
      modified/be/view/testconn.py

BIN
.coverage View File


BIN
be/__pycache__/serve.cpython-38.pyc View File


BIN
be/model/__pycache__/buyer.cpython-38.pyc View File


BIN
be/model/__pycache__/db_conn.cpython-38.pyc View File


BIN
be/model/__pycache__/postgreSQLORM.cpython-38.pyc View File


BIN
be/model/__pycache__/seller.cpython-38.pyc View File


+ 11
- 11
be/model/buyer.py View File

@ -72,7 +72,7 @@ class Buyer(db_conn.DBConn):
# (uid, book_id, count, price))
# print("touch1")
creat_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) ## 订单创建时间
new_order_entity = New_Order(order_id=uid,fk_store_id=store_id,fk_user_id=user_id,creat_time=creat_time,status=0)
new_order_entity = New_Order(order_id=uid,store_id=store_id,user_id=user_id,creat_time=creat_time,status=0)
self.session.add(new_order_entity)
# self.conn.execute(
# "INSERT INTO new_order(order_id, store_id, user_id) "
@ -104,8 +104,8 @@ class Buyer(db_conn.DBConn):
# buyer_id = row[1]
# store_id = row[2]
order_id = row.order_id
buyer_id = row.fk_user_id
store_id = row.fk_store_id
buyer_id = row.user_id
store_id = row.store_id
if buyer_id != user_id:
return error.error_authorization_fail()
@ -121,14 +121,14 @@ class Buyer(db_conn.DBConn):
if password != pwd:
return error.error_authorization_fail()
row = session.query(postgreSQLORM.User_Store).filter(postgreSQLORM.User_Store.fk_store_id==store_id).first()
row = session.query(postgreSQLORM.User_Store).filter(postgreSQLORM.User_Store.store_id==store_id).first()
# cursor = conn.execute("SELECT store_id, user_id FROM user_store WHERE store_id = ?;", (store_id,))
# row = cursor.fetchone()
if row is None:
return error.error_non_exist_store_id(store_id)
# seller_id = row[1]
seller_id = row.fk_user_id
seller_id = row.user_id
if not self.user_id_exist(seller_id):
return error.error_non_exist_user_id(seller_id)
@ -225,13 +225,13 @@ class Buyer(db_conn.DBConn):
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).first()
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.user_id==user_id)).first()
if row is None:
return error.error_invalid_order_id(order_id)
if row.status != 2:
return error.error_invalid_order_id(order_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).update({'status':3})
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.user_id==user_id)).update({'status':3})
if row == 0:
return error.error_invalid_order_id(order_id)
@ -251,13 +251,13 @@ class Buyer(db_conn.DBConn):
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).first()
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.user_id==user_id)).first()
if row is None:
return error.error_invalid_order_id(order_id)
if row.status != 0:
return error.error_invalid_order_id(order_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).update({'status':-1})
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.user_id==user_id)).update({'status':-1})
if row == 0:
return error.error_invalid_order_id(order_id)
@ -276,10 +276,10 @@ class Buyer(db_conn.DBConn):
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(New_Order.fk_user_id==user_id).first()
row = session.query(New_Order).filter(New_Order.user_id==user_id).first()
if row is None:
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(New_Order.fk_user_id==user_id).order_by(New_Order.creat_time.desc()).all()
row = session.query(New_Order).filter(New_Order.user_id==user_id).order_by(New_Order.creat_time.desc()).all()
order_ids = []
for i in row:
order_ids.append(i.order_id)

+ 1
- 1
be/model/db_conn.py View File

@ -26,7 +26,7 @@ class DBConn:
return True
def store_id_exist(self, store_id):
row = self.session.query(User_Store).filter(User_Store.fk_store_id==store_id).first()
row = self.session.query(User_Store).filter(User_Store.store_id==store_id).first()
# cursor = self.conn.execute("SELECT store_id FROM user_store WHERE store_id = ?;", (store_id,))
# row = cursor.fetchone()
if row is None:

+ 25
- 25
be/model/postgreSQLORM.py View File

@ -33,10 +33,10 @@ class User(Base):
token = Column(TEXT, comment="缓存的令牌")
terminal = Column(TEXT, comment="终端代码")
class Store(Base):
__tablename__ = 'store'
store_id = Column(TEXT, primary_key=True,comment="主键")
stock_level = Column(Integer, comment = "货存")
# class Store(Base):
# __tablename__ = 'store'
# store_id = Column(TEXT, primary_key=True,comment="主键")
# stock_level = Column(Integer, comment = "货存")
class Store_Book(Base):
__tablename__ = 'store_book'
@ -52,38 +52,38 @@ class Store_Book(Base):
class User_Store(Base):
__tablename__ = 'user_store'
id = Column(Integer, primary_key=True, autoincrement=True, comment="主键")
# id = Column(Integer, primary_key=True, autoincrement=True, comment="主键")
fk_user_id = Column(
user_id = Column(
TEXT,
ForeignKey(
"user.user_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
# ForeignKey(
# "user.user_id",
# ondelete="CASCADE",
# onupdate="CASCADE",
# ),
nullable=False,
comment="user外键"
)
fk_store_id = Column(
store_id = Column(
TEXT,
ForeignKey(
"store.store_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
# ForeignKey(
# "store.store_id",
# ondelete="CASCADE",
# onupdate="CASCADE",
# ),
nullable=False,
comment="store外键"
)
# 多对多关系的中间表必须使用联合唯一约束,防止出现重复数据
__table_args__ = (
UniqueConstraint("fk_user_id", "fk_store_id";),
PrimaryKeyConstraint('store_id', 'user_id';),
)
class New_Order(Base):
__tablename__ = 'new_order'
order_id = Column(TEXT, primary_key = True, comment = '订单id')
fk_user_id = Column(
user_id = Column(
TEXT,
ForeignKey(
"user.user_id",
@ -93,13 +93,13 @@ class New_Order(Base):
nullable=False,
comment="user外键"
)
fk_store_id = Column(
store_id = Column(
TEXT,
ForeignKey(
"store.store_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
# ForeignKey(
# "store.store_id",
# ondelete="CASCADE",
# onupdate="CASCADE",
# ),
nullable=False,
comment="store外键"
)

+ 3
- 3
be/model/seller.py View File

@ -59,9 +59,9 @@ class Seller(db_conn.DBConn):
return error.error_non_exist_user_id(user_id)
if self.store_id_exist(store_id):
return error.error_exist_store_id(store_id)
new_store = postgreSQLORM.Store(store_id=store_id,stock_level=0)
new_user_store = postgreSQLORM.User_Store(fk_user_id=user_id,fk_store_id=store_id)
self.session.add(new_store)
# new_store = postgreSQLORM.Store(store_id=store_id,stock_level=0)
new_user_store = postgreSQLORM.User_Store(user_id=user_id,store_id=store_id)
# self.session.add(new_store)
# self.session.commit()
self.session.add(new_user_store)
# self.conn.execute("INSERT into user_store(store_id, user_id)"

+ 6
- 4
be/serve.py View File

@ -20,7 +20,7 @@ def shutdown_server():
func()
@bp_shutdown.route("/shutdown")
@bp_shutdown.route("/shutdown", methods=["POST","GET"])
def be_shutdown():
shutdown_server()
return "Server shutting down..."
@ -29,6 +29,8 @@ def be_run():
this_path = os.path.dirname(__file__)
parent_path = os.path.dirname(this_path)
log_file = os.path.join(parent_path, "app.log")
createTable()
logging.basicConfig(filename=log_file, level=logging.ERROR)
handler = logging.StreamHandler()
formatter = logging.Formatter(
@ -38,11 +40,11 @@ def be_run():
logging.getLogger().addHandler(handler)
app = Flask(__name__)
createTable()
app.register_blueprint(bp_shutdown)
app.register_blueprint(testconn.bp_testconn)
app.register_blueprint(auth.bp_auth)
app.register_blueprint(seller.bp_seller)
app.register_blueprint(buyer.bp_buyer)
app.run(port=5000)
app.run()

BIN
be/view/__pycache__/testconn.cpython-38.pyc View File


+ 1
- 1
be/view/testconn.py View File

@ -3,7 +3,7 @@ from flask import Flask, abort, request, jsonify
import json
from flask import jsonify
from be.model import postgreSQLORM
from be.model.postgreSQLORM import User,Store,Store_Book,User_Store,New_Order,New_Order_Detail
from be.model.postgreSQLORM import User,Store_Book,User_Store,New_Order,New_Order_Detail
bp_testconn = Blueprint("testconn",__name__,url_prefix="/testconn")

+ 0
- 0
modified/be/__init__.py View File


BIN
modified/be/__pycache__/__init__.cpython-38.pyc View File


BIN
modified/be/__pycache__/app.cpython-38.pyc View File


BIN
modified/be/__pycache__/creatTB.cpython-38.pyc View File


BIN
modified/be/__pycache__/postgreSQLORM.cpython-38.pyc View File


BIN
modified/be/__pycache__/serve.cpython-38.pyc View File


BIN
modified/be/__pycache__/testconn.cpython-38.pyc View File


+ 0
- 4
modified/be/app.py View File

@ -1,4 +0,0 @@
import serve
if __name__ == "__main__":
serve.be_run()

+ 0
- 0
modified/be/model/__init__.py View File


BIN
modified/be/model/__pycache__/__init__.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/buyer.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/creatTB.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/db_conn.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/error.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/postgreSQLORM.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/seller.cpython-38.pyc View File


BIN
modified/be/model/__pycache__/user.cpython-38.pyc View File


+ 0
- 292
modified/be/model/buyer.py View File

@ -1,292 +0,0 @@
import sqlite3 as sqlite
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import and_
from model import postgreSQLORM
from model.postgreSQLORM import Store_Book
from model.postgreSQLORM import New_Order_Detail
from model.postgreSQLORM import New_Order
from model.postgreSQLORM import User
import uuid
import json
import logging
import time
from model import db_conn
from model import error
class Buyer(db_conn.DBConn):
def __init__(self):
db_conn.DBConn.__init__(self)
def new_order(self, user_id: str, store_id: str, id_and_count: [(str, int)]) -> (int, str, str):
order_id = ""
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id) + (order_id, )
if not self.store_id_exist(store_id):
return error.error_non_exist_store_id(store_id) + (order_id, )
uid = "{}_{}_{}".format(user_id, store_id, str(uuid.uuid1()))
# print("touch0")
for book_id, count in id_and_count:
row = self.session.query(postgreSQLORM.Store_Book).filter(and_(postgreSQLORM.Store_Book.store_id==store_id,postgreSQLORM.Store_Book.book_id==book_id)).first()
# cursor = self.conn.execute(
# "SELECT book_id, stock_level, book_info FROM store "
# "WHERE store_id = ? AND book_id = ?;",
# (store_id, book_id))
# row = cursor.fetchone()
if row is None:
return error.error_non_exist_book_id(book_id) + (order_id, )
# stock_level = row[1]
# book_info = row[2]
stock_level = row.stock_level
book_info = row.book_info
book_info_json = json.loads(book_info)
price = book_info_json.get("price")
if stock_level < count:
return error.error_stock_level_low(book_id) + (order_id,)
# print("touch2")
row = self.session.query(Store_Book).filter(and_(Store_Book.store_id==store_id,Store_Book.book_id==book_id,Store_Book.stock_level>=count)).update({'stock_level':Store_Book.stock_level-count})
# cursor = self.conn.execute(
# "UPDATE store set stock_level = stock_level - ? "
# "WHERE store_id = ? and book_id = ? and stock_level >= ?; ",
# (count, store_id, book_id, count))
# if cursor.rowcount == 0:
# print("touch3")
if row == 0:
return error.error_stock_level_low(book_id) + (order_id, )
# print("touch4")
new_order_detail_entity = New_Order_Detail(order_id=uid,book_id=book_id,count=count,price=price)
# print("touch5")
row = self.session.add(new_order_detail_entity)
# self.session.commit()
# self.conn.execute(
# "INSERT INTO new_order_detail(order_id, book_id, count, price) "
# "VALUES(?, ?, ?, ?);",
# (uid, book_id, count, price))
# print("touch1")
creat_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) ## 订单创建时间
new_order_entity = New_Order(order_id=uid,fk_store_id=store_id,fk_user_id=user_id,creat_time=creat_time,status=0)
self.session.add(new_order_entity)
# self.conn.execute(
# "INSERT INTO new_order(order_id, store_id, user_id) "
# "VALUES(?, ?, ?);",
# (uid, store_id, user_id))
# self.conn.commit()
self.session.commit()
order_id = uid
except SQLAlchemyError as e:
logging.info("528, {}".format(str(e)))
return 528, "{}".format(str(e)), ""
except BaseException as e:
logging.info("530, {}".format(str(e)))
return 530, "{}".format(str(e)), ""
return 200, "ok", order_id
def payment(self, user_id: str, password: str, order_id: str) -> (int, str):
# conn = self.conn
session = self.session
try:
row = session.query(New_Order).filter(New_Order.order_id==order_id).first()
# cursor = conn.execute("SELECT order_id, user_id, store_id FROM new_order WHERE order_id = ?", (order_id,))
# row = cursor.fetchone()
if row is None:
return error.error_invalid_order_id(order_id)
# order_id = row[0]
# buyer_id = row[1]
# store_id = row[2]
order_id = row.order_id
buyer_id = row.fk_user_id
store_id = row.fk_store_id
if buyer_id != user_id:
return error.error_authorization_fail()
row = session.query(postgreSQLORM.User).filter(postgreSQLORM.User.user_id==buyer_id).first()
# cursor = conn.execute("SELECT balance, password FROM user WHERE user_id = ?;", (buyer_id,))
# row = cursor.fetchone()
if row is None:
return error.error_non_exist_user_id(buyer_id)
# balance = row[0]
balance = row.balance
pwd = row.password
if password != pwd:
return error.error_authorization_fail()
row = session.query(postgreSQLORM.User_Store).filter(postgreSQLORM.User_Store.fk_store_id==store_id).first()
# cursor = conn.execute("SELECT store_id, user_id FROM user_store WHERE store_id = ?;", (store_id,))
# row = cursor.fetchone()
if row is None:
return error.error_non_exist_store_id(store_id)
# seller_id = row[1]
seller_id = row.fk_user_id
if not self.user_id_exist(seller_id):
return error.error_non_exist_user_id(seller_id)
row = session.query(New_Order_Detail).filter(New_Order_Detail.order_id==order_id).all()
# cursor = conn.execute("SELECT book_id, count, price FROM new_order_detail WHERE order_id = ?;", (order_id,))
total_price = 0
# for row in cursor:
# count = row[1]
# price = row[2]
# total_price = total_price + price * count
for i in row:
count = i.count
price = i.price
total_price = total_price + price * count
if balance < total_price:
return error.error_not_sufficient_funds(order_id)
# print('touch0')
## 买家扣钱
row = session.query(User).filter(and_(User.balance>=total_price,User.user_id==buyer_id)).update({'balance':User.balance-total_price})
# cursor = conn.execute("UPDATE user set balance = balance - ?"
# "WHERE user_id = ? AND balance >= ?",
# (total_price, buyer_id, total_price))
# if cursor.rowcount == 0:
if row == 0:
return error.error_not_sufficient_funds(order_id)
# print('touch1')
## 卖家加钱
row = session.query(User).filter(User.user_id==seller_id).update({'balance':User.balance+total_price})
# cursor = conn.execute("UPDATE user set balance = balance + ?"
# "WHERE user_id = ?",
# (total_price, buyer_id))
# if cursor.rowcount == 0:
if row == 0:
return error.error_non_exist_user_id(buyer_id)
# print('touch2')
# row = session.query(New_Order).filter(New_Order.order_id==order_id).delete() 不在删除而是修改订单状态
row = session.query(New_Order).filter(New_Order.order_id==order_id).update({'status':1})
# cursor = conn.execute("DELETE FROM new_order WHERE order_id = ?", (order_id, ))
# if cursor.rowcount == 0:
if row == 0:
return error.error_invalid_order_id(order_id)
# row = session.query(New_Order_Detail).filter(New_Order_Detail.order_id==order_id).delete()
# cursor = conn.execute("DELETE FROM new_order_detail where order_id = ?", (order_id, ))
# if cursor.rowcount == 0:
if row == 0:
return error.error_invalid_order_id(order_id)
# conn.commit()
session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def add_funds(self, user_id, password, add_value) -> (int, str):
try:
row = self.session.query(postgreSQLORM.User).filter(postgreSQLORM.User.user_id==user_id).first()
# cursor = self.conn.execute("SELECT password from user where user_id=?", (user_id,))
# row = cursor.fetchone()
if row is None:
return error.error_authorization_fail()
pwd = row.password
if pwd != password:
return error.error_authorization_fail()
row = self.session.query(postgreSQLORM.User).filter_by(user_id=user_id).update({'balance':postgreSQLORM.User.balance+add_value,'user_id':user_id})
# cursor = self.conn.execute(
# "UPDATE user SET balance = balance + ? WHERE user_id = ?",
# (add_value, user_id))
if row == 0:
return error.error_non_exist_user_id(user_id)
self.session.commit()
# self.conn.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def take_over(self, user_id, order_id):
session = self.session
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).first()
if row is None:
return error.error_invalid_order_id(order_id)
if row.status != 2:
return error.error_invalid_order_id(order_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).update({'status':3})
if row == 0:
return error.error_invalid_order_id(order_id)
session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
# print('touch3')
return 530, "{}".format(str(e))
return 200, "ok"
def order_cancel(self, user_id, order_id):
session = self.session
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).first()
if row is None:
return error.error_invalid_order_id(order_id)
if row.status != 0:
return error.error_invalid_order_id(order_id)
row = session.query(New_Order).filter(and_(New_Order.order_id==order_id,New_Order.fk_user_id==user_id)).update({'status':-1})
if row == 0:
return error.error_invalid_order_id(order_id)
session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
# print('touch3')
return 530, "{}".format(str(e))
return 200, "ok"
def history_order(self, user_id):
session = self.session
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(New_Order.fk_user_id==user_id).first()
if row is None:
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(New_Order.fk_user_id==user_id).order_by(New_Order.creat_time.desc()).all()
order_ids = []
for i in row:
order_ids.append(i.order_id)
session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
# print('touch3')
return 530, "{}".format(str(e))
return 200, "ok", order_ids

+ 0
- 5
modified/be/model/creatTB.py View File

@ -1,5 +0,0 @@
from model.postgreSQLORM import Base,engine
def createTable():
# 创建所有继承于Base的类对应的表
Base.metadata.create_all(engine)

+ 0
- 35
modified/be/model/db_conn.py View File

@ -1,35 +0,0 @@
from model import postgreSQLORM
from model.postgreSQLORM import User, Store_Book, User_Store
class DBConn:
def __init__(self):
self.session = postgreSQLORM.session
return
# self.conn = store.get_db_conn()
def user_id_exist(self, user_id):
row = self.session.query(User).filter(User.user_id==user_id).first()
# cursor = self.conn.execute("SELECT user_id FROM user WHERE user_id = ?;", (user_id,))
# row = cursor.fetchone()
if row is None:
return False
else:
return True
def book_id_exist(self, store_id, book_id):
row = self.session.query(Store_Book).filter(Store_Book.book_id==book_id and Store_Book.store_id==store_id).first()
# cursor = self.conn.execute("SELECT book_id FROM store WHERE store_id = ? AND book_id = ?;", (store_id, book_id))
# row = cursor.fetchone()
if row is None:
return False
else:
return True
def store_id_exist(self, store_id):
row = self.session.query(User_Store).filter(User_Store.fk_store_id==store_id).first()
# cursor = self.conn.execute("SELECT store_id FROM user_store WHERE store_id = ?;", (store_id,))
# row = cursor.fetchone()
if row is None:
return False
else:
return True

+ 0
- 66
modified/be/model/error.py View File

@ -1,66 +0,0 @@
error_code = {
401: "authorization fail.",
511: "non exist user id {}",
512: "exist user id {}",
513: "non exist store id {}",
514: "exist store id {}",
515: "non exist book id {}",
516: "exist book id {}",
517: "stock level low, book id {}",
518: "invalid order id {}",
519: "not sufficient funds, order id {}",
520: "",
521: "",
522: "",
523: "",
524: "",
525: "",
526: "",
527: "",
528: "",
}
def error_non_exist_user_id(user_id):
return 511, error_code[511].format(user_id)
def error_exist_user_id(user_id):
return 512, error_code[512].format(user_id)
def error_non_exist_store_id(store_id):
return 513, error_code[513].format(store_id)
def error_exist_store_id(store_id):
return 514, error_code[514].format(store_id)
def error_non_exist_book_id(book_id):
return 515, error_code[515].format(book_id)
def error_exist_book_id(book_id):
return 516, error_code[516].format(book_id)
def error_stock_level_low(book_id):
return 517, error_code[517].format(book_id)
def error_invalid_order_id(order_id):
return 518, error_code[518].format(order_id)
def error_not_sufficient_funds(order_id):
return 519, error_code[518].format(order_id)
def error_authorization_fail():
return 401, error_code[401]
def error_and_message(code, message):
return code, message

+ 0
- 126
modified/be/model/postgreSQLORM.py View File

@ -1,126 +0,0 @@
from sqlalchemy import create_engine,MetaData
from sqlalchemy import Integer,String,ForeignKey,Column,TEXT
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import PrimaryKeyConstraint,UniqueConstraint
import sqlalchemy
import time
Base=declarative_base()
class con:
def connect():
'''Returns a connection and a metadata object'''
# We connect with the help of the PostgreSQL URL
url = 'postgresql://stu10205501415:Stu10205501415@dase-cdms-2022-pub.pg.rds.aliyuncs.com:5432/stu10205501415'
# The return value of create_engine() is our connection object
con = create_engine(url, client_encoding='utf8')
# We then bind the connection to MetaData()
meta = MetaData(bind=con)
return con, meta
class User(Base):
__tablename__ = 'user'
user_id = Column(TEXT, primary_key=True, comment="主键")
password = Column(TEXT, nullable=False, comment="密码")
balance = Column(Integer, nullable=False, comment="")
token = Column(TEXT, comment="缓存的令牌")
terminal = Column(TEXT, comment="终端代码")
class Store(Base):
__tablename__ = 'store'
store_id = Column(TEXT, primary_key=True,comment="主键")
stock_level = Column(Integer, comment = "货存")
class Store_Book(Base):
__tablename__ = 'store_book'
store_id = Column(TEXT, comment="主键")
book_id = Column(TEXT, comment="主键")
book_info = Column(TEXT, comment="书籍信息")
stock_level = Column(Integer, comment = "货存")
__table_args__ = (
PrimaryKeyConstraint('store_id', 'book_id'),
)
class User_Store(Base):
__tablename__ = 'user_store'
id = Column(Integer, primary_key=True, autoincrement=True, comment="主键")
fk_user_id = Column(
TEXT,
ForeignKey(
"user.user_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
nullable=False,
comment="user外键"
)
fk_store_id = Column(
TEXT,
ForeignKey(
"store.store_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
nullable=False,
comment="store外键"
)
# 多对多关系的中间表必须使用联合唯一约束,防止出现重复数据
__table_args__ = (
UniqueConstraint("fk_user_id", "fk_store_id"),
)
class New_Order(Base):
__tablename__ = 'new_order'
order_id = Column(TEXT, primary_key = True, comment = '订单id')
fk_user_id = Column(
TEXT,
ForeignKey(
"user.user_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
nullable=False,
comment="user外键"
)
fk_store_id = Column(
TEXT,
ForeignKey(
"store.store_id",
ondelete="CASCADE",
onupdate="CASCADE",
),
nullable=False,
comment="store外键"
)
creat_time = Column(TEXT, nullable=False,comment="订单创建时间")
status = Column(Integer,nullable=False,comment="订单状态")
class New_Order_Detail(Base):
__tablename__ = 'new_order_detail'
order_id = Column(TEXT, comment='订单id')
book_id = Column(TEXT, comment='订单书籍')
count = Column(Integer, comment='购买书籍数')
price = Column(Integer, comment='单价')
__table_args__ = (
PrimaryKeyConstraint('order_id','book_id'),
)
engine, meta = con.connect()
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

+ 0
- 104
modified/be/model/seller.py View File

@ -1,104 +0,0 @@
from sqlalchemy.exc import SQLAlchemyError
from model import error
from model import postgreSQLORM
from model.postgreSQLORM import New_Order
from model import db_conn
from sqlalchemy import and_
class Seller(db_conn.DBConn):
def __init__(self):
db_conn.DBConn.__init__(self)
def add_book(self, user_id: str, store_id: str, book_id: str, book_json_str: str, stock_level: int):
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
if not self.store_id_exist(store_id):
return error.error_non_exist_store_id(store_id)
if self.book_id_exist(store_id, book_id):
return error.error_exist_book_id(book_id)
# self.session.query(postgreSQLORM.Store_Book).
new_book = postgreSQLORM.Store_Book(store_id=store_id,book_id=book_id,book_info=book_json_str,stock_level=stock_level)
self.session.add(new_book)
# self.conn.execute("INSERT into store(store_id, book_id, book_info, stock_level)"
# "VALUES (?, ?, ?, ?)", (store_id, book_id, book_json_str, stock_level))
# self.conn.commit()
self.session.query(postgreSQLORM.Store).filter_by(store_id=store_id).update({'stock_level':postgreSQLORM.Store.stock_level+1})
self.session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def add_stock_level(self, user_id: str, store_id: str, book_id: str, add_stock_level: int):
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
if not self.store_id_exist(store_id):
return error.error_non_exist_store_id(store_id)
if not self.book_id_exist(store_id, book_id):
return error.error_non_exist_book_id(book_id)
self.session.query(postgreSQLORM.Store).filter_by(store_id=store_id).update({'stock_level':add_stock_level})
self.session.query(postgreSQLORM.Store_Book).filter_by(store_id=store_id,book_id=book_id).update({'stock_level':add_stock_level})
# self.conn.execute("UPDATE store SET stock_level = stock_level + ? "
# "WHERE store_id = ? AND book_id = ?", (add_stock_level, store_id, book_id))
# self.conn.commit()
self.session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def create_store(self, user_id: str, store_id: str) -> (int, str):
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
if self.store_id_exist(store_id):
return error.error_exist_store_id(store_id)
new_store = postgreSQLORM.Store(store_id=store_id,stock_level=0)
new_user_store = postgreSQLORM.User_Store(fk_user_id=user_id,fk_store_id=store_id)
self.session.add(new_store)
# self.session.commit()
self.session.add(new_user_store)
# self.conn.execute("INSERT into user_store(store_id, user_id)"
# "VALUES (?, ?)", (store_id, user_id))
# self.conn.commit()
self.session.commit()
# print('touch1')
except SQLAlchemyError as e:
# print('touch2')
return 528, "{}".format(str(e))
except BaseException as e:
# print('touch3')
return 530, "{}".format(str(e))
return 200, "ok"
def send_out(self, order_id:str, user_id:str):
session = self.session
try:
if not self.user_id_exist(user_id):
return error.error_non_exist_user_id(user_id)
row = session.query(New_Order).filter(New_Order.order_id==order_id).first()
if row is None:
return error.error_invalid_order_id(order_id)
if row.status != 1:
return error.error_invalid_order_id(order_id)
row = session.query(New_Order).filter(New_Order.order_id==order_id).update({'status':2})
if row == 0:
return error.error_invalid_order_id(order_id)
session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
# print('touch3')
return 530, "{}".format(str(e))
return 200, "ok"

+ 0
- 202
modified/be/model/user.py View File

@ -1,202 +0,0 @@
import jwt
import time
import logging
import sqlite3 as sqlite
from sqlalchemy.exc import SQLAlchemyError
from model import error
from model import postgreSQLORM
from model.postgreSQLORM import User
from model import db_conn
# encode a json string like:
# {
# "user_id": [user name],
# "terminal": [terminal code],
# "timestamp": [ts]} to a JWT
# }
def jwt_encode(user_id: str, terminal: str) -> str:
encoded = jwt.encode(
{"user_id": user_id, "terminal": terminal, "timestamp": time.time()},
key=user_id,
algorithm="HS256",
)
return encoded.encode("utf-8").decode("utf-8")
# decode a JWT to a json string like:
# {
# "user_id": [user name],
# "terminal": [terminal code],
# "timestamp": [ts]} to a JWT
# }
def jwt_decode(encoded_token, user_id: str) -> str:
decoded = jwt.decode(encoded_token, key=user_id, algorithms="HS256")
return decoded
class User(db_conn.DBConn):
token_lifetime: int = 3600 # 3600 second
def __init__(self):
db_conn.DBConn.__init__(self)
def __check_token(self, user_id, db_token, token) -> bool:
try:
if db_token != token:
# print('touch')
return False
jwt_text = jwt_decode(encoded_token=token, user_id=user_id)
ts = jwt_text["timestamp"]
if ts is not None:
now = time.time()
if self.token_lifetime > now - ts >= 0:
return True
except jwt.exceptions.InvalidSignatureError as e:
logging.error(str(e))
return False
def register(self, user_id: str, password: str):
## 判断用户是否注册过了
if self.user_id_exist(user_id=user_id):
return error.error_exist_user_id(user_id)
else:
# try:
terminal = "terminal_{}".format(str(time.time()))
token = jwt_encode(user_id, terminal)
## 为新注册的用户创建对象
new_user = postgreSQLORM.User(user_id=user_id,password=password,balance=0,token=token,terminal=terminal)
self.session.add(new_user)
self.session.commit()
# self.conn.execute(
# "INSERT into user(user_id, password, balance, token, terminal) "
# "VALUES (?, ?, ?, ?, ?);",
# (user_id, password, 0, token, terminal), )
# self.conn.commit()
# except sqlite.Error:
# return error.error_exist_user_id(user_id)
return 200, "ok"
def check_token(self, user_id: str, token: str) -> (int, str):
row = self.session.query(postgreSQLORM.User.token).filter(postgreSQLORM.User.user_id==user_id).first()
# cursor = self.conn.execute("SELECT token from user where user_id=?", (user_id,))
# row = cursor.fetchone()
# print(row)
if row is None:
# print('touch')
return error.error_authorization_fail()
db_token = row[0]
# print(db_token)
# print(token)
if not self.__check_token(user_id, db_token, token):
# print('touch')
return error.error_authorization_fail()
return 200, "ok"
def check_password(self, user_id: str, password: str) -> (int, str):
row = self.session.query(postgreSQLORM.User.password).filter(postgreSQLORM.User.user_id==user_id).first()
# cursor = self.conn.execute("SELECT password from user where user_id=?", (user_id,))
# row = cursor.fetchone()
if row is None:
return error.error_authorization_fail()
if password != row[0]:
return error.error_authorization_fail()
return 200, "ok"
def login(self, user_id: str, password: str, terminal: str) -> (int, str, str):
token = ""
try:
code, message = self.check_password(user_id, password)
if code != 200:
return code, message, ""
token = jwt_encode(user_id, terminal)
row = self.session.query(postgreSQLORM.User).filter_by(user_id=user_id).update({'token':token,'terminal':terminal})
# cursor = self.conn.execute(
# "UPDATE user set token= ? , terminal = ? where user_id = ?",
# (token, terminal, user_id), )
# if cursor.rowcount == 0:
if row == 0:
return error.error_authorization_fail() + ("", )
# self.conn.commit()
self.session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e)), ""
except BaseException as e:
return 530, "{}".format(str(e)), ""
return 200, "ok", token
def logout(self, user_id: str, token: str) -> bool:
try:
code, message = self.check_token(user_id, token)
if code != 200:
return code, message
terminal = "terminal_{}".format(str(time.time()))
dummy_token = jwt_encode(user_id, terminal)
row = self.session.query(postgreSQLORM.User).filter_by(user_id=user_id).update({'token':dummy_token,'terminal':terminal})
# cursor = self.conn.execute(
# "UPDATE user SET token = ?, terminal = ? WHERE user_id=?",
# (dummy_token, terminal, user_id), )
# if cursor.rowcount == 0:
# print(row)
if row == 0:
return error.error_authorization_fail()
# self.conn.commit()
self.session.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def unregister(self, user_id: str, password: str) -> (int, str):
try:
code, message = self.check_password(user_id, password)
if code != 200:
return code, message
row = self.session.query(postgreSQLORM.User).filter(postgreSQLORM.User.user_id==user_id).delete()
# cursor = self.conn.execute("DELETE from user where user_id=?", (user_id,))
# if cursor.rowcount == 1:
if row == 1:
self.session.commit()
# self.conn.commit()
else:
return error.error_authorization_fail()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"
def change_password(self, user_id: str, old_password: str, new_password: str) -> bool:
try:
code, message = self.check_password(user_id, old_password)
if code != 200:
return code, message
terminal = "terminal_{}".format(str(time.time()))
token = jwt_encode(user_id, terminal)
row = self.session.query(postgreSQLORM.User).filter_by(user_id=user_id).update({'password':new_password,'token':token,'terminal':terminal})
# cursor = self.conn.execute(
# "UPDATE user set password = ?, token= ? , terminal = ? where user_id = ?",
# (new_password, token, terminal, user_id), )
# if cursor.rowcount == 0:
if row == 0:
return error.error_authorization_fail()
self.session.commit()
# self.conn.commit()
except SQLAlchemyError as e:
return 528, "{}".format(str(e))
except BaseException as e:
return 530, "{}".format(str(e))
return 200, "ok"

+ 0
- 49
modified/be/serve.py View File

@ -1,49 +0,0 @@
import logging
import os
from flask import Flask
from flask import Blueprint
from flask import request
from view import testconn
from view import auth
from view import seller
from view import buyer
from model.creatTB import createTable
bp_shutdown = Blueprint("shutdown", __name__)
def shutdown_server():
func = request.environ.get("werkzeug.server.shutdown")
if func is None:
raise RuntimeError("Not running with the Werkzeug Server")
func()
@bp_shutdown.route("/shutdown")
def be_shutdown():
shutdown_server()
return "Server shutting down..."
def be_run():
this_path = os.path.dirname(__file__)
parent_path = os.path.dirname(this_path)
log_file = os.path.join(parent_path, "app.log")
logging.basicConfig(filename=log_file, level=logging.ERROR)
handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s"
)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
app = Flask(__name__)
createTable()
app.register_blueprint(bp_shutdown)
app.register_blueprint(testconn.bp_testconn)
app.register_blueprint(auth.bp_auth)
app.register_blueprint(seller.bp_seller)
app.register_blueprint(buyer.bp_buyer)
app.run()

+ 0
- 0
modified/be/view/__init__.py View File


BIN
modified/be/view/__pycache__/__init__.cpython-38.pyc View File


BIN
modified/be/view/__pycache__/auth.cpython-38.pyc View File


BIN
modified/be/view/__pycache__/buyer.cpython-38.pyc View File


BIN
modified/be/view/__pycache__/seller.cpython-38.pyc View File


BIN
modified/be/view/__pycache__/testconn.cpython-38.pyc View File


+ 0
- 53
modified/be/view/auth.py View File

@ -1,53 +0,0 @@
from flask import Blueprint
from flask import request
from flask import jsonify
from model import user
bp_auth = Blueprint("auth",__name__,url_prefix="/auth")
@bp_auth.route("/login", methods=["POST"])
def login():
user_id = request.json.get("user_id", "")
password = request.json.get("password", "")
terminal = request.json.get("terminal", "")
u = user.User()
code, message, token = u.login(user_id=user_id, password=password, terminal=terminal)
return jsonify({"message": message, "token": token}), code
@bp_auth.route("/logout", methods=["POST"])
def logout():
user_id: str = request.json.get("user_id")
token: str = request.headers.get("token")
print(token)
u = user.User()
code, message = u.logout(user_id=user_id, token=token)
return jsonify({"message": message}), code
@bp_auth.route("/register", methods=["POST"])
def register():
user_id = request.json.get("user_id", "")
password = request.json.get("password", "")
u = user.User()
code, message = u.register(user_id=user_id, password=password)
return jsonify({"message": message}), code
@bp_auth.route("/unregister", methods=["POST"])
def unregister():
user_id = request.json.get("user_id", "")
password = request.json.get("password", "")
u = user.User()
code, message = u.unregister(user_id=user_id, password=password)
return jsonify({"message": message}), code
@bp_auth.route("/password", methods=["POST"])
def change_password():
user_id = request.json.get("user_id", "")
old_password = request.json.get("oldPassword", "")
new_password = request.json.get("newPassword", "")
u = user.User()
code, message = u.change_password(user_id=user_id, old_password=old_password, new_password=new_password)
return jsonify({"message": message}), code

+ 0
- 64
modified/be/view/buyer.py View File

@ -1,64 +0,0 @@
from flask import Blueprint
from flask import request
from flask import jsonify
from model.buyer import Buyer
bp_buyer = Blueprint("buyer",__name__,url_prefix="/buyer")
@bp_buyer.route("/new_order", methods=["POST"])
def new_order():
user_id: str = request.json.get("user_id")
store_id: str = request.json.get("store_id")
books: [] = request.json.get("books")
id_and_count = []
for book in books:
book_id = book.get("id")
count = book.get("count")
id_and_count.append((book_id, count))
b = Buyer()
code, message, order_id = b.new_order(user_id, store_id, id_and_count)
return jsonify({"message": message, "order_id": order_id}), code
@bp_buyer.route("/payment", methods=["POST"])
def payment():
user_id: str = request.json.get("user_id")
order_id: str = request.json.get("order_id")
password: str = request.json.get("password")
b = Buyer()
code, message = b.payment(user_id, password, order_id)
return jsonify({"message": message}), code
@bp_buyer.route("/add_funds", methods=["POST"])
def add_funds():
user_id = request.json.get("user_id")
password = request.json.get("password")
add_value = request.json.get("add_value")
b = Buyer()
code, message = b.add_funds(user_id, password, add_value)
return jsonify({"message": message}), code
@bp_buyer.route("/take_over", methods=["POST"])
def take_over():
user_id = request.json.get("user_id")
order_id = request.json.get("order_id")
b = Buyer()
code, message = b.take_over(user_id, order_id)
return jsonify({"message": message}), code
@bp_buyer.route("/order_cancel", methods=["POST"])
def order_cancel():
user_id = request.json.get("user_id")
order_id = request.json.get("order_id")
b = Buyer()
code, message = b.order_cancel(user_id, order_id)
return jsonify({"message": message}), code
@bp_buyer.route("/history_order", methods=["POST"])
def history_order():
user_id = request.json.get("user_id")
b = Buyer()
code, message, order_ids = b.history_order(user_id)
return jsonify({"message": message,"order_id": order_ids}), code

+ 0
- 51
modified/be/view/seller.py View File

@ -1,51 +0,0 @@
from flask import Blueprint
from flask import request
from flask import jsonify
from model import seller
import json
bp_seller = Blueprint("seller",__name__,url_prefix="/seller")
@bp_seller.route("/create_store", methods=["POST"])
def seller_create_store():
user_id: str = request.json.get("user_id")
store_id: str = request.json.get("store_id")
s = seller.Seller()
code, message = s.create_store(user_id, store_id)
return jsonify({"message": message}), code
@bp_seller.route("/add_book", methods=["POST"])
def seller_add_book():
user_id: str = request.json.get("user_id")
store_id: str = request.json.get("store_id")
book_info: str = request.json.get("book_info")
stock_level: str = request.json.get("stock_level", 0)
s = seller.Seller()
code, message = s.add_book(user_id, store_id, book_info.get("id"), json.dumps(book_info), stock_level)
return jsonify({"message": message}), code
@bp_seller.route("/add_stock_level", methods=["POST"])
def add_stock_level():
user_id: str = request.json.get("user_id")
store_id: str = request.json.get("store_id")
book_id: str = request.json.get("book_id")
add_num: str = request.json.get("add_stock_level", 0)
s = seller.Seller()
code, message = s.add_stock_level(user_id, store_id, book_id, add_num)
return jsonify({"message": message}), code
@bp_seller.route("/send_out",methods=["POST"])
def send_out():
order_id: str = request.json.get("order_id")
user_id: str = request.json.get("user_id")
s = seller.Seller()
code, message = s.send_out(order_id,user_id)
return jsonify({"message": message}), code

+ 0
- 21
modified/be/view/testconn.py View File

@ -1,21 +0,0 @@
from flask import Blueprint
from flask import Flask, abort, request, jsonify
import json
from flask import jsonify
from model import postgreSQLORM
from model.postgreSQLORM import User,Store,Store_Book,User_Store,New_Order,New_Order_Detail
bp_testconn = Blueprint("testconn",__name__,url_prefix="/testconn")
@bp_testconn.route("/test",methods=['GET'])
def test():
user_id: str = request.args.get("user_id")
print(user_id)
try:
ss = postgreSQLORM.session.query(User).filter(User.user_id==user_id).all()
for i in ss:
print('user_id',i.user_id)
except:
print("error")
return "connect success"

Loading…
Cancel
Save