购物网站+sqlachmy

Posted Steward_Xu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了购物网站+sqlachmy相关的知识,希望对你有一定的参考价值。

一、流程图:

 

二、目录结构:

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:
                    以上是关于购物网站+sqlachmy的主要内容,如果未能解决你的问题,请参考以下文章

vs2003:快速片段工具

超级有用的9个PHP代码片段

html 将以编程方式附加外部脚本文件的javascript代码片段,并按顺序排列。用于响应式网站,其中ma

如何在 Reactjs 中添加丰富的代码片段?

Wordpress阻止访问wp admin€“wpsnipp.com网站你博客的Wordpress代码片段

几个可以直接拿来用的jQuery代码片段