码迷,mamicode.com
首页 > 数据库 > 详细

购物网站+sqlachmy

时间:2017-10-13 14:13:09      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:def   bank   l数据库   错误   装饰器   mysql数据库   height   参考   rgs   

一、流程图:

技术分享

 

二、目录结构:

技术分享
C:\USERS\DAISY\PYCHARMPROJECTS\S12\MARKET
│  __init__.py
│  __init__.pyc
│
├─backend
│  │  __init__.py
│  │  __init__.pyc
│  │
│  ├─database_goods
│  │      dbgoods_con.py
│  │      dbgoods_con.pyc
│  │      goods_data.py
│  │      goods_data.pyc
│  │      modles.py
│  │      modles.pyc
│  │      __init__.py
│  │      __init__.pyc
│  │
│  ├─database_user
│  │      db_con.py
│  │      db_con.pyc
│  │      modle.py
│  │      modle.pyc
│  │      user_database.py
│  │      user_database.pyc
│  │      __init__.py
│  │      __init__.pyc
│  │
│  ├─logic
│  │      handle.py
│  │      handle.pyc
│  │      home.py
│  │      home.pyc
│  │      login.py
│  │      login.pyc
│  │      SHOPPING.py
│  │      SHOPPING.pyc
│  │      shopping_class.py
│  │      sockt.py
│  │      sockt.pyc
│  │      __init__.py
│  │      __init__.pyc
│  │
│  └─seller
│      │  __init__.py
│      │
│      ├─seller_db
│      │      __init__.py
│      │
│      └─seller_goods_db
│              __init__.py
│
├─config
│      seller_setting.py
│      seller_setting.pyc
│      settings.py
│      settings.pyc
│      __init__.py
│      __init__.pyc
│
└─frontend
        user_acc.py
        user_acc.pyc
        __init__.py
        __init__.pyc
View Code

三、代码展示:

  1、backend

    1)database_goods,指定购物的数据库,以及购物网站中的物品清单:    

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/9/25 9:28
# @Author  : xuxuedong
# @Site    : 
# @File    : dbgoods_con.py
# @Software: PyCharm
import os, sys
from sqlalchemy import create_engine,Table
from  sqlalchemy.orm import sessionmaker

from market.config import settings
BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# print(BASE_DIR)
engine = create_engine(settings.DB_CONN,encoding=utf-8,echo =True)  #指定Mysql数据库引擎

SessionCls = sessionmaker(bind=engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
session = SessionCls()
dbgoods_con.py

    以下中为模拟的数据库中物品信息,当然可参考models.py存入数据库中。

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/5/21 11:13
# @Author  : xuxuedong
# @Site    :
# @File    : goods_data.py
# @Software: PyCharm
import os, sys

‘‘‘
模拟数据库,可以用sqlachmy单独建立在seller中创建库
‘‘‘
DATABASE_MAN = [
    {"name": "男士寸衣", "price": 100},
    {"name": "男士长裤", "price": 200},
    {"name": "男士皮鞋", "price": 190},
    {"name": "男士皮带", "price": 100},
    {"name": "男士外衣", "price": 300},
]

DATABASE_WOMAN = [
    {"name": "女士寸衣", "price": 300},
    {"name": "女士内衣", "price": 103},
    {"name": "女士鞋", "price": 200},
    {"name": "女士长裙", "price": 198},
]

DATABASE_CHILD = [
    {"name": "迪士尼", "price": 300},
    {"name": "玩具飞机", "price": 103},
    {"name": "玩具汽车", "price": 200},
    {"name": "童装", "price": 198},
]
goods_data.py

    以下为已经购买存入数据库中的物品数据库表创建代码实现    

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/9/25 9:38
# @Author  : xuxuedong
# @Site    : 
# @File    : modles.py
# @Software: PyCharm
import os, sys,sqlalchemy
from sqlalchemy import create_engine,Table, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey,UniqueConstraint,UnicodeText,DateTime
from sqlalchemy.orm import relationship
from sqlalchemy import or_,and_
from sqlalchemy import func
from sqlalchemy_utils import ChoiceType,PasswordType
from  sqlalchemy.orm import sessionmaker
from market.backend.database_goods import dbgoods_con

BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# engine = create_engine("mysql+pymysql://root:123@localhost/shooping",encoding=‘utf-8‘, echo=True)
Base = declarative_base()
User2goods= Table(user_to_goods,Base.metadata,
    Column(binduser_id,ForeignKey(goods.id),primary_key=True)
)

class GOODS(Base):
    __tablename__ = "goods"
    id = Column(Integer,primary_key=True)
    userid = Column(String(64),unique=True,nullable=False)
    goods = Column(String(64),unique=True,nullable=False)
    numble = Column(String(128),unique=True,nullable=False)
    price = Column( String(64),unique=True,nullable=False)
    def __repr__(self):
        return "<GOODS(id = ‘%s‘,userid = ‘%s‘,goods = ‘%s‘,numble = ‘%s‘)>" % (self.id,self.userid,self.goods,self.numble)

# class USER(Base):
#     __tablename__ = "user"
#     id = Column(Integer,primary_key=True)
#     user = Column(String(64),unique=True,nullable=False)
#     password = Column(String(64),unique=True,nullable=False)
#     # user_id = relationship (GOODS)
#     def __repr__(self):
#         return "<USER(id=‘%s‘,username=‘%s‘)>" % (self.id,self.user,self.password)


‘‘‘
##创建表
metadata = MetaData()
USER = Table(‘USER‘, metadata,
            Column(‘id‘, Integer, primary_key=True),
            Column(‘user‘, String(64)),
            Column(‘password‘, String(64))
        )
metadata.create_all(engine)
conn = engine.connect()
‘‘‘
‘‘‘
#创建表
metadata = MetaData()
USER = Table(‘goods‘, metadata,
            Column(‘id‘, Integer, primary_key=True),
            Column(‘userid‘,String(64)),
            Column(‘goods‘, String(64)),
            Column(‘numble‘, String(128))
        )
metadata.create_all(engine)
conn = engine.connect()
‘‘‘

if __name__ == __main__:
    dbgoods_con.SessionCls = sessionmaker(bind=dbgoods_con.engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
    session = dbgoods_con.SessionCls()
    # SessionCls =  sessionmaker(bind=engine)
    # session = SessionCls()
    # H1 = USER( user =‘admin1‘,password = ‘admin12‘)
    # H2 = USER( user =‘admin2‘,password = ‘admin22‘)
    # # h2 = User(hostname =‘ubuntu2‘,ip_addr = ‘192.168.1.101‘,port = 10001)
    # session.add_all([H1,H2])     #这是增加数据
    # session.commit()
‘‘‘ 查询出数据库信息
    for name, password in  session.query(USER.user,USER.password):
        print ("用户名:%s的密码:%s"%(name,password))

‘‘‘
modles.py

    2)database_user,位用户信息数据库,存放用户名及密码,用于登录验证,注册成功,用户信息写入数据库:

    db_con用于连接数据库

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/9/22 15:37
# @Author  : xuxuedong
# @Site    : 
# @File    : db_con.py
# @Software: PyCharm
import os, sys
from sqlalchemy import create_engine,Table
from  sqlalchemy.orm import sessionmaker

from market.config import settings,seller_setting
BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# print(BASE_DIR)
engine = create_engine(settings.DB_CONN,encoding=utf-8)


SessionCls = sessionmaker(bind=engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
session = SessionCls()
db_con.py

    modle.py用于创建用户表

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/9/22 15:21
# @Author  : xuxuedong
# @Site    : 
# @File    : modle.py
# @Software: PyCharm
import os, sys,sqlalchemy
from sqlalchemy import create_engine,Table, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey,UniqueConstraint,UnicodeText,DateTime
from sqlalchemy.orm import relationship
from sqlalchemy import or_,and_
from sqlalchemy import func
from sqlalchemy_utils import ChoiceType,PasswordType
from  sqlalchemy.orm import sessionmaker
from market.backend.database_user import db_con


BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# print(BASE_DIR)
engine = create_engine("mysql+pymysql://root:123@localhost/shooping",encoding=utf-8, echo=True)

Base = declarative_base() #生成一个SqlORM 基类Base = declarative_base()


User2goods= Table(user_to_goods,Base.metadata,
    Column(binduser_id,ForeignKey(goods.id),primary_key=True)
)

class GOODS(Base):
    __tablename__ = "goods"
    id = Column(Integer,primary_key=True)
    userid = Column(String(64),unique=True,nullable=False)
    goods = Column(String(64),unique=True,nullable=False)
    numble = Column(String(128),unique=True,nullable=False)
    price = Column( String(64),unique=True,nullable=False)
    # def __repr__(self):
    #     return "<GOODS(id = ‘%s‘,goods = ‘%s‘,numble = ‘%s‘)>" % (self.id,self.goods,self.numble)

class USER(Base):
    __tablename__ = "user"
    id = Column(Integer,primary_key=True)
    user = Column(String(64),unique=True,nullable=False)
    password = Column(String(64),unique=True,nullable=False)
    # user_id = relationship (GOODS)
    # def __repr__(self):
    #     return "<USER(id=‘%s‘,username=‘%s‘)>" % (self.id,self.username,self.password)


‘‘‘
#创建表
metadata = MetaData()
USER = Table(‘USER‘, metadata,
            Column(‘id‘, Integer, primary_key=True),
            Column(‘user‘, String(64)),
            Column(‘password‘, String(64))
        )
metadata.create_all(engine)
conn = engine.connect()
‘‘‘
‘‘‘
metadata = MetaData()
USER = Table(‘goods‘, metadata,
            Column(‘id‘, Integer, primary_key=True),
            Column(‘userid‘,String(64)),
            Column(‘goods‘, String(64)),
            Column(‘numble‘, String(128)),
            Column(‘price‘, String(64))
        )
metadata.create_all(engine)
conn = engine.connect()
‘‘‘

if __name__ == __main__:
    db_con.SessionCls = sessionmaker(bind=db_con.engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
    session = db_con.SessionCls()
    # # SessionCls =  sessionmaker(bind=engine)
    # # session = SessionCls()
    # # # H1 = USER( user =‘admin1‘,password = ‘admin12‘)
    # H2 = GOODS( userid = ‘admin‘,goods = ‘男士寸衣‘,numble=‘10‘,price=10000)
    # # # h2 = User(hostname =‘ubuntu2‘,ip_addr = ‘192.168.1.101‘,port = 10001)
    # obj = session.query(GOODS).filter(GOODS.goods==‘男士长裤‘).first() #查找数据库中的localhost第一个数据
    # print(obj)
    # for name, goods , numble, price in  session.query(GOODS.userid,GOODS.goods,GOODS.numble,GOODS.price):
    #     print ("用户名:%s购买的物品:%s 数量:%s 付款:%s"%(name,goods , numble, price))

#      #查询出数据库信息
#         obj = session.query(GOODS.userid,GOODS.goods,GOODS.numble,GOODS.price).filter(GOODS.userid=="admin").all()
#         # print(obj)
#         for  i in obj:
#             # print(i)
#             # print ("用户名:%s"%(i.userid))
#             print ("用户名:%s购买了物品:%s 数量:%s 付款:%s"%(i.userid,i.goods , i.numble, i.price))
#
#
#     # session.add_all([H2])     #这是增加数据
#     # session.commit()
#
# #查询出数据库信息
#     for name, password in  session.query(USER.user,USER.password):
#         print ("用户名:%s的密码:%s"%(name,password))
modle.py

    3)logic用于程序逻辑处理,含登录、验证、购物、以及银行sockt接口

    handle.py用于专区物品展示 

    技术分享
#!/usr/bin/env python
#coding=utf-8
# print sys.getdefaultencoding()

from market.backend.database_goods import goods_data

def man ():
    for i in goods_data.DATABASE_MAN :
        c = i["name"]
        d = i["price"]
        print("%s\t价格%s\t" % (c,d))
def woman():
    for i in goods_data.DATABASE_WOMAN :
        c = i["name"]
        d = i["price"]
        print("%s\t价格%s\t" % (c,d))
    # print("welcome to man pages!")
def chilrd():
    for i in goods_data.DATABASE_CHILD :
        c = i["name"]
        d = i["price"]
        print("%s\t价格%s\t" % (c,d))
handle.py

    home.py用于首页展示:    

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/6/2 16:46
# @Author  : xuxuedong
# @Site    : 
# @File    : home.py
# @Software: PyCharm
import os, sys

# def man ():
#     print("welcom to 男装专区.")
# def woman ():
#     print("welcom to 女装专区.")
# def chlid():
#     print("welcom to 儿童专区.")
def login():
    print(‘‘.center(82,*))
    print(*+ .center(80)+*)
    print(‘‘.ljust(1,*)+欢迎来到地猫购物平台.center(90, )+‘‘.ljust(1,*))
    print(*+ .center(80)+*)
    print(‘‘.center(82,*))
    print(|.ljust(5, )+1.用户登录.center(22, )+ .ljust(10, )+2.男装专区+‘‘.ljust(10, )+3.女装专区
          .center(31, )+|.ljust(5, ))
    print(|.ljust(5, )+4.儿童专区.center(22, )+ .ljust(10, )+5.用户注册+‘‘.ljust(7, )+6.付款
         .center(32, )+|.ljust(5, ))
    print(|.ljust(8, )+7.本次消费记录.center(22, )+ .ljust(9, )+8.历史消费+‘‘.ljust(7, )+ 9.退出
          .center(32, )+|.ljust(5, ))
       # print(‘1.用户登录‘+‘‘.ljust(1,‘‘)+‘2.男装专区‘)
home.py

    login.py用于登录验证、用户注册:

    技术分享
#!/usr/bin/env python
#coding=utf-8
# -*- coding: utf-8 -*-
# @Time    : 2017/6/5 15:34
# @Author  : xuxuedong
# @Site    : 
# @File    : login.py
# @Software: PyCharm
import os, sys
import json,shelve
from market.backend.database_user import user_database
from market.backend.database_user.db_con import session
from market.backend.database_user import modle

BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

user_status = False

‘‘‘
#此为不在数据库中取数据,需单独建立模拟数据库列表
def login(func):
    def inner(*args,**kwargs):
        global user_status
        count = 0
        if user_status == False:
            username = raw_input("请输入您的账号:")
            password = raw_input("请输入您的密码:")
            # for user in user_database.DATABASE_USER:
            if username in user_database.DATABASE_USER and password == user_database.DATABASE_USER[username]:
                print("welcome login....")
                user_status = True
            else:
                print("wrong username or password!")
        if user_status == True:
            return func(*args,**kwargs)  # 看这里看这里,只要验证通过了,就调用相应功能
    return inner #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
    # din = user_database.DATABASE_USER
‘‘‘
# userid = None



def login(func):
    ‘‘‘
    #认证模块装饰器,从mysql数据库中提取用户名密码,认证成功并且返回用户名密码,待购物时提取userid=用户名
    ‘‘‘
    # userid = None
    def inner(arg1,INPUT,userid):
        global user_status
        # userid = None
        count = 0
        if user_status == False:
            while count <3:
                username = raw_input("\033[32;1mUsername:\033[0m").strip()
                if len(username) ==0:continue
                password = raw_input("\033[32;1mPassword:\033[0m").strip()
                if len(password) ==0:continue
                user_obj = session.query(modle.USER).filter(modle.USER.user==username,
                                                                    modle.USER.password==password).first()
                if user_obj != None:
                    print("welcome login....")
                    userid = username
                    user_status = True
                    func(arg1,INPUT,userid)   ###可返回数据待购物时提取userid=用户名
                    # return userid == username
                    break
                else:
                    print("wrong username or password, you have %s more chances." %(3-count-1))
                    count +=1
            else:
                print("too many attempts.")
        if user_status == True:
            return func(arg1,INPUT,userid)  # 看这里看这里,只要验证通过了,就调用相应功能
    return inner #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数

def registe():
    ‘‘‘
    注册模块,注册时先查找mysql数据库中是否有这个用户,如果没有,输入两次相同用户名密码注册至myslq数据库
    :return:
    ‘‘‘
    global din
    status = False
    count = 0
    counts = 0
    while count <3:
        if user_status == True:
            print ("你已经登录不需要注册!!!")
            break
        if status ==True or counts == 2:
            break
        else:
            user_name = raw_input("请输入您要注册的账号的账号:")
            if len(user_name) ==0:
                print ("用户名不能为空!!!")
                continue
            host_obj = session.query(modle.USER).filter(modle.USER.user == user_name ).first()
            # print(host_obj)
            if host_obj != None:
                print("用户名:%s已经注册!请从新输入"%(user_name))
                count +=1
                continue
            else:
                print("用户名:%s可用"%(user_name))
                userpasword = raw_input("请输入您要注册的账号密码:")
                if len(userpasword) ==0:
                    print ("密码不能为空!!!")

                while counts < 3:
                    confirmpasswrod = raw_input("请再次输入您要注册的账号密码:")
                    if userpasword != confirmpasswrod:
                        print("两次输入密码不一致请从新输入!!")
                        counts +=1
                        # continue
                    else:
                        uname =  modle.USER(user = user_name ,password = userpasword )
                        session.add_all([uname,])   #连接数据库并注册用户只数据库
                        session.commit()
                        print("账号:%s 注册成功"%(user_name))
                        status = True
                        break


# print (userid)
login.py

    SHOPPING.py用于购物以及结算购物

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/6/2 17:47
# @Author  : xuxuedong
# @Site    : 
# @File    : SHOPPING.py
# @Software: PyCharm
import os, sys
from market.backend.logic import handle,home,login
from market.backend.database_goods import modles
from market.backend.database_goods.dbgoods_con import session

BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
shopping_cart = {}
totel = 0

@login.login  #购物之前需认证登录
def SHOP(arg1,INPUT,userid):
    global  shopping_cart,totel
    status1 = False
    while True:
        if INPUT == "2":
            handle.man()
        elif INPUT == "3":
            handle.woman()
        elif INPUT == "4":
            handle.chilrd()
        # else:
        #     print("输入错误")
        #     continue
        # print(userid)
        # print (type(numble_goods))
        # print(userid)
        shoops = raw_input("请输入商品名称(Q结账):")
        for item in arg1:
            if shoops.upper()  == "Q":
                return status1 == True
                break
            if shoops in item["name"]:
                numble_goods = raw_input("请输入购买数量:")
                int(numble_goods)
                # print(item["price"])
                name = item["name"]
                totel = int( item["price"]) * int(numble_goods)
                # if name in shopping_cart.items():
                #     shopping_cart[name]["num"] = numble_goods
                #     shopping_cart[name]["pice"] =  item["price"]
                #     print (shopping_cart.keys)
                shoop  =  modles.GOODS(userid = userid ,goods = shoops,numble=numble_goods,price=totel )
                session.add_all([shoop,])  #将购物信息写入数据库中
                session.commit()
                shopping_cart[name] ={"price":item["price"],"numble":numble_goods}
                print(shopping_cart)
            # elif shoops.upper()  == "Q":
             #     break
        #
        # totel1 = 0
        # for i, j in shopping_cart.items():
        #         # i[name]
        #         print(i)
        #         signle_sum =int(j["price"]) * int(j["numble"])
        #         print (type(signle_sum))
        #         int(signle_sum)
        #         totel1 = totel + signle_sum
        #         print("购买商品%s\t价格%s\t数量%s"%(i,j["price"],int(j["numble"])))
        # print(totel1)

        stop = raw_input("是否继续购物(Y/N):")
        totel1 = 0
        if stop.upper() == "Y":
            for i, j in shopping_cart.items():
                    signle_sum =int(j["price"]) * int(j["numble"])
                    print (type(signle_sum))
                    int(signle_sum)
                    totel1 = totel1 + signle_sum
                    print("购买商品%s\t价格%s\t数量%s"%(i,j["price"],int(j["numble"])))
            print("此次购物消费%s"%totel1)
                # print(shopping_cart)
            # print("总价%s"%totel)
                # print(shopping_cart)
            print("====================")

        if stop.upper() == "N":
            # return shopping_cart,totel
            # print("此次购物消费%s"%totel1)
            break

                # break
Totel1 = 0
Totel2 = 0
def shopping_car():
    ‘‘‘
    #结算时结算此次购物总价并打印此次购物清单购物
    :return:
    ‘‘‘

    global shopping_cart,totel,Totel1,Totel2
    for i, j in shopping_cart.items():
        signle_sum = int(j["price"]) * int(j["numble"])
        Totel2 = Totel2 + signle_sum
        Totel1 = Totel1 + signle_sum
        print("购买商品%s\t价格%s\t数量%s"%(i,j["price"],int(j["numble"])))
    print("总价%s"%Totel2)
        # print(shopping_cart)
    print("====================")
# def cash():
#     global shopping_cart,totel
#     for i, j in shopping_cart.items():
#         signle_sum = j["price"] * j["num"]
#         Totel2 = totel + signle_sum
#     print("总价%s"%Totel2)
#         # print(type(stop))
#         if stop.upper() == "Y":
#             return shopping_cart,totel
#         break
SHOPPING.py

    socket.py用于连接银行接口

    技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/6/14 12:59
# @Author  : xuxuedong
# @Site    : 
# @File    : sockt.py
# @Software: PyCharm
import socket
# from market.frontend import user_acc
# from market.backend.logic import SHOPPING
def API_Atm(args):
    HOST, PORT = "localhost", 9999
    # data = " hahah".join(sys.argv[1:])
    # Create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))
    sock.sendall(bytes(args))
    server_reply = sock.recv(1024)
    print("server said:%s"%str(server_reply))
    # while True:
    #     msg = raw_input(">>>>>").strip()
    #     sock.sendall(bytes(user_acc.bank_card))
    #     server_reply = sock.recv(1024)
    #     print("server said:%s"%str(server_reply))
    #     sock.sendall(bytes(user_acc.bank_card_passwd))
    #     server_reply = sock.recv(1024)
    #     print("server said:%s"%str(server_reply))
    #     sock.sendall(bytes(SHOPPING.totel))
    #     server_reply = sock.recv(1024)
    #     print("server said:%s"%str(server_reply))
    # try:
    #     # Connect to server and send data
    #     sock.connect((HOST,PORT))
    #     sock.sendall(bytes(data))
    #
    #     # Receive data from the server and shut down
    #     received = str(sock.recv(1024))
    # finally:
    sock.close()

# print("Sent:     {}".format(data))
# print("Received: {}".format(received))
socket.py

  2、config

    settings.py用于定义数据库连接:

    

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/5/20 23:17
# @Author  : xuxuedong
# @Site    : 
# @File    : settings.py
# @Software: PyCharm
import os, sys


BASE_DIR =os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)



DB_CONN ="mysql+mysqldb://root:123@localhost:3306/shooping"  #指定连接数据库

DB_CONN1 ="mysql+mysqldb://root:123@localhost:3306/goods"    #指定连接数据库

   3、frontend

   user_acc.py程序入口 

  技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/5/20 22:43
# @Author  : xuxuedong
# @Site    :
# @File    : user_acc.py
# @Software: PyCharm
# print sys.getdefaultencoding()
import os, sys

from market.backend.logic import handle,home,SHOPPING,login,sockt
from market.backend.database_goods import goods_data
BASE_DIR =os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

# home.man()
# home.woman()
# home.chlid()
# home.login()
userid1 = []
@login.login
def homelogin (arg1,INPUT,userid):
    # print(userid)
    userid1.append(userid)
    # print(userid1)
    # user_status = True
while True:
    # global shopping_cart
    # global totel
    home.login()
    CHOSE = raw_input("请选择你要访问的专区:")
    if CHOSE == "1":
        arg1 = None
        INPUT = None
        userid = None
        homelogin(arg1,INPUT,userid)
        print(userid1[0])

    elif CHOSE == "2":
        # homelogin()
        arg1 = goods_data.DATABASE_MAN
        INPUT ="2"
        userid = None
        homelogin(arg1,INPUT,userid)
        userid = userid1[0]
        SHOPPING.SHOP(arg1,INPUT,userid)
    elif CHOSE == "3":
        # homelogin()
        arg1 = goods_data.DATABASE_WOMAN
        INPUT="3"
        # handle.woman()
        userid = None
        homelogin(arg1,INPUT,userid)
        userid = userid1[0]
        SHOPPING.SHOP(arg1,INPUT,userid)
        print(userid)
    elif CHOSE == "4":
        # homelogin()
        # userid = login.userid
        # print (userid)
        arg1 = goods_data.DATABASE_CHILD
        INPUT="4"
        userid = None
        homelogin(arg1,INPUT,userid)
        userid = userid1[0]
        # handle.chilrd()
        SHOPPING.SHOP(arg1,INPUT,userid)
    elif CHOSE == "5":
        login.registe()
    elif CHOSE == "6":
        chash = raw_input("是否结算(Y/N):")
        if chash.upper() == "Y":
            user_flag=None
            passwd_flag=None
            # print("购物清单是:%s"%SHOPPING.shopping_cart)
            SHOPPING.shopping_car()
            a=SHOPPING.Totel2
            bank_card = raw_input("请输入你的银行卡号:")
            bank_card_passwd = raw_input("请输入你的银行卡密码:")
            sockt.API_Atm(bank_card)
            sockt.API_Atm(bank_card_passwd)
            sockt.API_Atm(SHOPPING.Totel2)
            print(a)
            break
    elif CHOSE == "7":
        SHOPPING.shopping_car()
        print(SHOPPING.Totel1)
    elif CHOSE == "8":
        pass
        #查询数据库中的用户所购物的信息即可。
    elif CHOSE == "9":
        break
if __name__ == "__main__":
    user_status = False
    T=0
    bank_card = None
    bank_card_passwd = None
user_acc.py

四、程序运行截图:

  登录:

技术分享

  先注册用户:选择5

 技术分享

  注册成功可选择登录,也可直接选择专区,直接选择专区会进行登录验证:

  选择男装专区2:提示输入用户名密码验证,成功后可进行购物:

技术分享

  购物:

技术分享

    查看本次消费记录:选择7

  技术分享

   如果想不结束,再次购物则不需要验证了:如选择4儿童专区

  技术分享

    再次购物在查看消费记录:

    技术分享

 

  

 

 

 

    

 

    

 

购物网站+sqlachmy

标签:def   bank   l数据库   错误   装饰器   mysql数据库   height   参考   rgs   

原文地址:http://www.cnblogs.com/Steward-Xu/p/7657164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!