网站购物,使用pickle

主程序,     

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import pickle
import os
import sys
import time
import pickle
dirname = os.path.dirname(os.path.dirname(__file__))
sys.path.append(dirname)

carshop = []
pricelist = []

shop = {
        'car':20000,
        'iphone':6000,
        'apple':20,
        'orange':15,
        'banana':10
}


def caradd():
    while True:
        for index,key in enumerate(shop.keys()):
            print index,'\t',key,'\t\t',shop[key]
        num = int(raw_input('请选在购买的商品ID,添加到购物车: '))

        if shop.keys()[num]:
            carshop.append([shop.items()[num],time.strftime("%Y-%m-%d %X", time.localtime())])
            print carshop
        else:
            print '请选择商品编号,或者您购买的商品不存在'

        name = raw_input('是否继续购物(y/n): ')
        if name == 'y':
            continue
        else:
            print '系统将返回到首页'
            return True

def showcar():
    for index1,key in enumerate(carshop,1):
            pricelist.append(key[0][1])
            print index1,key[0][0]

def price_sum():
    res1 = reduce(lambda x,y:x+y,pricelist)
    return  res1

while True:
    print '''-------欢迎访问本商城------
        1  进行购物
        2  查看购物车
    '''
    choose = int(raw_input('请按照提示信息进行输入: '))
    if choose == 1:
        result = caradd()
        if result  == 'True':
            break
    elif choose == 2:
        if carshop:
            showcar()
            price = price_sum()
            print '您一共够买了',price
        else:
            print '你还没有购物,购物车为空'

        commitcar = raw_input('时候马上结算(y/n): ')
        if commitcar == 'y':
            username = int(raw_input('请输入信用卡账号: '))
            passwd = int(raw_input('请输入信用卡密码: '))

            with open('user_pass','r') as f:
                data = pickle.load(f)
            for k,v in data.items():
                print k,v
                if k == username and passwd == v[0]:
                    print '将从信用卡中扣除商品金额'
                    salary = v[1]
                    if price > salary:
                        print '信用卡额度不足,无法购买商品'
                        break
                    else:
                        salary_new  = salary - price
                        print salary_new
                        v[1] = salary_new
                        with open('user_pass','w') as f:
                            pickle.dump(data,f)
                        print '支付成功,系统退出'
                        sys.exit()
                else:
                    print '----------------------->'
        else:
            continue
使用pickle生成user_pass文件


#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import pickle

dic_pick = {
    123:[123,10000]
}
f  = open('user_pass','w')

pickle.dump(dic_pick,f)
f.close()



###############################
#!/usr/bin/env python
#_*_ coding:utf-8 _*_

import pickle

f = open('user_pass','r')
data = pickle.load(f)
print data

 

posted @ 2016-03-05 23:36  fengjian1585  阅读(201)  评论(0编辑  收藏  举报