一次从网上商店购买许多产品 [英] Buying many products at once from a webshop

查看:275
本文介绍了一次从网上商店购买许多产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过我的支付系统(api.payson.se)编程只有一种产品可以非常简单,但同时购买多种产品的各种数量的产品给我带来了麻烦,因为它没有实施,我也没有有一个好主意如何去做。现在我有一个解决方案,我只是放在一起工作,但建模和控制流是非常快速和肮脏的,我想知道这是否可以接受或应该需要重写。系统现在可以进入商店(步骤1)并输入我想要购买的产品的金额。

总金额为瑞典货币,并已向我的数据存储区下单,状态为未付,并包含订购的产品和数据存储中每个产品的金额:

用户可以然后取消购买或继续付款并通过支付系统实际支付api.payson.se:

因此,我需要做的就是收听Payson的回复并更新获得付款的订单的状态。但我的解决方案看起来不太干净,我想知道是否可以继续使用这样的代码,数据模型是两个字符串列表,一个是数量,另一个是使用哪个产品(Item ID),因为这是我可以解决的最简单的方法但它不能直接访问,只能从列表中获得。是否有更好的数据模型可以使用?



执行处理的代码有点杂乱,可以使用更好的数据模型和更好的算法,而不仅仅是字符串和列表:

  class ShopHandler(NewBaseHandler):

@user_required
def get(self) :
user = \
auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
]))
self.render_jinja('shop。 htm',items = Item.recent(),user = user)
return''

@user_required
def post(self,command):
user = \
auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
)))
logging.info('shophandler http post item id'+ self .request.get('item'))

items = [self.request.get('items [1]'),self.request.get('items [2]'),self .request.get( '项目[3]'),SEL f.request.get( '项[4]'),self.request.get( '项[5]'),self.request.get( '项目[6]'),self.request.get('项目'self.request.get('items [8]')]

amount = [self.request.get('amount [1]'),self.request.get ( '数量[2]'),self.request.get( '数量[3]'),self.request.get( '数量[4]'),self.request.get( '数量[5]') ,self.request.get('amount [6]'),self.request.get('amount [7]'),self.request.get('amount [8]')]
total = 0
total = int(self.request.get('amount [1]'))* long(Item.get_by_id(long(self.request.get('items [1]')))。price_fraction() )self.request.get('amount [1]')else total
total = total + int(self.request.get('amount [2]'))* long(Item.get_by_id(long self.request.get('items [2]')))。price_fraction())if self.request.get('amount [2]')else total
total = total + int(self.request。 get('amount [3]'))* long(Item.get_by_id(long(self.request。 get('items [3]')))。price_fraction())if self.request.get('amount [3]')else total
total = total + int(self.request.get('amount [item.get_by_id(long(self.request.get('items [4]')))。price_fraction())if self.request.get('amount [4]')else总计
total = total + int(self.request.get('amount [5]'))* long(Item.get_by_id(long(self.request.get('items [5]')))。 price.fraction())if self.request.get('amount [5]')else total
total = total + int(self.request.get('amount [6]'))* long(Item.get_by_id (self.request.get('items [6]')))。price_fraction())if self.request.get('amount [6]')else total
total = total + int(self .request.get('amount [7]'))* long(Item.get_by_id(long(self.request.get('items [7]')))。price_fraction())if self.request.get(' (self.request.get('amount [8]'))* long(Item.get_by_id(long(self.request.get('items [ 8] ')))。price_fraction())if self.request.get('amount [8]')else total
logging.info('total:'+ str(total))
trimmed = str (总数)+',00'
order = model.Order(status ='UNPAID')
order.items =商品
order.amounts =金额
order.put( )
logging.info('订单被写入')
ExtraCost = 0
GuaranteeOffered = 2
OkUrl ='http://'self.request.host + r' / paysonreceive /'
Key ='3110fb33-6122-4032-b25a-329b430de6b6'
text ='niklasro@gmail.com'+':'+ str(trimmed)+':'+ str( ExtraCost)\
+':'+ OkUrl +':'+ str(GuaranteeOffered)+ Key
m = hashlib.md5()

BuyerEmail = user.email
AgentID = 11366
self.render_jinja('order.htm',order = order,user = user,total = total,Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest(),Buy erEmail = user.email,Description ='Bnano Webshop',trimmed = trimmed,OkUrl = OkUrl,BuyerFirstName = user.firstname,BuyerLastName = user.lastname)

我的订单模型不是所有的字段都是使用的,是

  class Order(db.Model):
'''一个事务'''
item = db.ReferenceProperty(Item)
items = db.StringListProperty()
amount = db .StringListProperty()
owner = db.UserProperty()
purchaser = db.UserProperty()
created = db.DateTimeProperty(auto_now_add = True)
status = db.StringProperty选项=('NEW','CREATED','ERROR','CANCELED','RETURNED','COMPLETED','UNPAID','PAID'))
status_detail = db.StringProperty()
reference = db.StringProperty()
secret = db.StringProperty()#验证return_url
debug_request = db.TextProperty()
debug_response = db.TextProperty()
paykey = db.StringProperty()
shipping = db.TextProperty()

产品的模型也就是一个项目

  class物品(db.Model):
'''物品出售'''
owner = db。 UserProperty()#optional
created = db.DateTimeProperty(auto_now_add = True)
title = db.StringProperty(required = True)
price = db.InteProProperty()#cents / fractions,use price_decimal以美元/整数形式获得价格
image = db.BlobProperty()
enabled = db.BooleanProperty(default = True)
silver = db.IntegerProperty()#number of silver

def price_dollars(self):
return self.price / 100.0

def price_fraction(self):
return self.price / 100.0

def price_silver(self):#银币数量值得
返回self.silver / 1000.000

def price_decimal(self):
返回十进制.decimal(str(self.price / 100.0))

def price_display(self):
返回str(self.price_fraction())。replace('。',',')

@staticmethod
def recent():
return Item.all() .filter(enabled =,True).order(' - created')。fetch(10)



<我认为你现在有一个想法是怎么回事,这种对用户的作用,但代码看起来不太好。你认为我可以保留这样的代码并继续保留这个解决方案吗?还是我必须重写才能使它更加合适?这家商店只有8种产品,而且这种解决方案很难添加一个新的商品出售,因为那时我必须重新编写不完美的脚本。



可以你评论或回答,我很乐意得到关于这个快速而肮脏的解决方案的反馈。



谢谢



更新



我做了一个重写以允许添加新产品,以下内容似乎比以前更好:

  class ShopHandler(NewBaseHandler):

@user_required
def get(self):
user = \\ \\
auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
]))
self.render_jinja('shop.htm',items = Item.recent (),user = user)
return''

@user_required
def post(self,command):
user = \
auth_models。 User.get_by_id(长(self.auth .get_user_by_session()['user_id'
)))
logging.info('in shophandler http post')

total = 0
order = model.Order (status ='UNPAID')

for self.request.POST中的项目:
amount = self.request.POST [item]
logging.info('item:' + str(item))
purchase = Item.get_by_id(long(item))
order.items.append(purchase.key())
order.amounts.append(int ))
order.put()
price = purchase.price_fraction()
logging.info('amount:'+ str(amount))
logging.info('product价格:'+ str(price))
total = total + price * int(金额)

logging.info('total:'+ str(total))
order .total = str(total)
order.put()
trimmed = str(total).replace('。',',')+'0'
ExtraCost = 0
保证金teeOffered = 2
OkUrl ='http://'+ self.request.host + r'/ paysonreceive /'
Key ='6230fb54-7842-3456-b43a-349b340de3b8'
text ='niklasro@gmail.com'+':'+ str(trimmed)+':'\
+ str(ExtraCost)+':'+ OkUrl +':'\
+ str (GuaranteeOffered)+ Key
m = hashlib.md5()
BuyerEmail = user.email#if user.email else user.auth_id [0]
AgentID = 11366
self.render_jinja (
'order.htm',
order = order,
user = user,
total = total,
Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest( ),
BuyerEmail = user.email,
Description ='Bnano Webshop',
trimmed = trimmed,
OkUrl = OkUrl,
BuyerFirstName = user.firstname,
BuyerLastName = user.lastname,


解决方案

男人,这是一个非常奇怪的代码。如果您想要在店中添加新商品,则必须重写店铺的脚本。
首先从接口中取消你的项目链接,你必须发送POST请求到控制器中,并且你的项目id和数量,我不知道如何工作gae请求对象,但它必须是这样的:
从你的订单页面使用字典的真正需要{item_id:qnt}的字典进行POST请求。
在控制器中,您可以获取所有对象,如:

 为item,qnt为request.POST:
{对每件物品做一些事情,例如你可以总计的总和}


请勿直接将控制器与您的接口连接。如果你想制作真正灵活的应用程序,你必须编写更多的抽象代码。

It's quite simple to program just one product to get sold via my payment system (api.payson.se) but buying many products at the same time in various amounts posed trouble for me since it was not implemented and I didn't have a good idea how to do it. Now I have a solution that I just put together which works but the modelling and control flow is kind of very quick and dirty and I wonder whether this is even acceptable or should need a rewrite. The system now behaves so that I can enter the shop (step 1) and enter the amounts for the products I want to buy

Then if I press Buy ("Köp") my Python calculates the sum correctly and this works whatever combination of amounts and products I have saying which the total is and this page could also list the specification but that is not implemented yet: The total sum is Swedish currency is correct and it has written an order to my datastore with status "unpaid" and containing which products are ordered and what amount for every product in the datastore: The user can then either cancel the purchase or go on and actually pay through the payment system api.payson.se: So all I need to do is listen to the response from Payson and update the status of the orders that get paid. But my solution does not look very clean and I wonder if I can go on with code like that, the data model is two stringlists, one with the amounts and one with which product (Item ID) since that was the easiest way I could solve it but it is then not directly accessible and only from the lists. Is there a better data model I can use?

The code that does the handling is slightly messy and could use a better data model and a better algorithm than just strings and lists:

class ShopHandler(NewBaseHandler):

    @user_required
    def get(self):
        user = \
            auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
                ]))
        self.render_jinja('shop.htm', items=Item.recent(), user=user)
        return ''

    @user_required
    def post(self, command):
        user = \
            auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
                ]))
        logging.info('in shophandler http post item id'+self.request.get('item'))

        items = [ self.request.get('items[1]'),self.request.get('items[2]'),self.request.get('items[3]'),self.request.get('items[4]'),self.request.get('items[5]'),self.request.get('items[6]'),self.request.get('items[7]'),self.request.get('items[8]')   ]   

        amounts = [ self.request.get('amounts[1]'),self.request.get('amounts[2]'),self.request.get('amounts[3]'),self.request.get('amounts[4]'),self.request.get('amounts[5]'),self.request.get('amounts[6]'),self.request.get('amounts[7]'),self.request.get('amounts[8]')  ]
        total = 0
        total = int(self.request.get('amounts[1]'))* long(Item.get_by_id(long(self.request.get('items[1]'))).price_fraction()) if self.request.get('amounts[1]') else total
        total = total + int(self.request.get('amounts[2]'))* long(Item.get_by_id(long(self.request.get('items[2]'))).price_fraction()) if self.request.get('amounts[2]') else total
        total = total + int(self.request.get('amounts[3]'))* long(Item.get_by_id(long(self.request.get('items[3]'))).price_fraction()) if self.request.get('amounts[3]') else total
        total = total + int(self.request.get('amounts[4]'))* long(Item.get_by_id(long(self.request.get('items[4]'))).price_fraction()) if self.request.get('amounts[4]') else total
        total = total + int(self.request.get('amounts[5]'))* long(Item.get_by_id(long(self.request.get('items[5]'))).price_fraction()) if self.request.get('amounts[5]') else total
        total = total + int(self.request.get('amounts[6]'))* long(Item.get_by_id(long(self.request.get('items[6]'))).price_fraction()) if self.request.get('amounts[6]') else total
        total = total + int(self.request.get('amounts[7]'))* long(Item.get_by_id(long(self.request.get('items[7]'))).price_fraction()) if self.request.get('amounts[7]') else total
        total = total + int(self.request.get('amounts[8]'))* long(Item.get_by_id(long(self.request.get('items[8]'))).price_fraction()) if self.request.get('amounts[8]') else total
        logging.info('total:'+str(total))
        trimmed = str(total)+',00'
        order = model.Order(status='UNPAID')
        order.items = items
        order.amounts = amounts
        order.put()
        logging.info('order was written')
        ExtraCost = 0
        GuaranteeOffered = 2
        OkUrl = 'http://' + self.request.host + r'/paysonreceive/'
        Key = '3110fb33-6122-4032-b25a-329b430de6b6'
        text = 'niklasro@gmail.com' + ':' + str(trimmed) + ':' + str(ExtraCost) \
            + ':' + OkUrl + ':' + str(GuaranteeOffered) + Key
        m = hashlib.md5()

        BuyerEmail = user.email
        AgentID = 11366
        self.render_jinja('order.htm', order=order, user=user, total=total, Generated_MD5_Hash_Value = hashlib.md5(text).hexdigest(), BuyerEmail=user.email, Description='Bnano Webshop', trimmed=trimmed, OkUrl=OkUrl, BuyerFirstName=user.firstname, BuyerLastName=user.lastname)

My model for the order, where not all fields are used, is

class Order(db.Model):
  '''a transaction'''
  item = db.ReferenceProperty(Item)
  items = db.StringListProperty()
  amounts = db.StringListProperty()
  owner = db.UserProperty()
  purchaser = db.UserProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  status = db.StringProperty( choices=( 'NEW', 'CREATED', 'ERROR', 'CANCELLED', 'RETURNED', 'COMPLETED', 'UNPAID', 'PAID' ) )
  status_detail = db.StringProperty()
  reference = db.StringProperty()
  secret = db.StringProperty() # to verify return_url
  debug_request = db.TextProperty()
  debug_response = db.TextProperty()
  paykey = db.StringProperty()
  shipping = db.TextProperty()

And the model for a product ie an item is

class Item(db.Model):
  '''an item for sale'''
  owner = db.UserProperty() #optional
  created = db.DateTimeProperty(auto_now_add=True)
  title = db.StringProperty(required=True)
  price = db.IntegerProperty() # cents / fractions, use price_decimal to get price in dollar / wholes
  image = db.BlobProperty()
  enabled = db.BooleanProperty(default=True)
  silver = db.IntegerProperty() #number of silver

  def price_dollars( self ):
    return self.price / 100.0

  def price_fraction( self ):
    return self.price / 100.0

  def price_silver( self ): #number of silvers an item "is worth"
    return self.silver / 1000.000

  def price_decimal( self ):
    return decimal.Decimal( str( self.price / 100.0 ) )

  def price_display( self ):
    return str(self.price_fraction()).replace('.',',')

  @staticmethod
  def recent():
    return Item.all().filter( "enabled =", True ).order('-created').fetch(10)

I think you now have an idea what's going on and that this kind of works towards the user but the code is not looking good. Do you think I can leave the code like this and go on and keep this "solution" or must I do a rewrite to make it more proper? There are only 8 products in the store and with this solution it becomes difficult to add a new Item for sale since then I must reprogram the script which is not perfect.

Could you comment or answer, I'd be very glad to get some feedback about this quick and dirty solution to my use case.

Thank you

Update

I did a rewrite to allow for adding new products and the following seems better than the previous:

class ShopHandler(NewBaseHandler):

    @user_required
    def get(self):
        user = \
            auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
                ]))
        self.render_jinja('shop.htm', items=Item.recent(), user=user)
        return ''

    @user_required
    def post(self, command):
        user = \
            auth_models.User.get_by_id(long(self.auth.get_user_by_session()['user_id'
                ]))
        logging.info('in shophandler http post')

        total = 0
        order = model.Order(status='UNPAID')

        for item in self.request.POST:
            amount = self.request.POST[item]
            logging.info('item:'+str(item))
            purchase = Item.get_by_id(long(item))
            order.items.append(purchase.key())
            order.amounts.append(int(amount))
            order.put()
            price = purchase.price_fraction()
            logging.info('amount:'+str(amount))
            logging.info('product price:'+str(price))
            total = total + price*int(amount)

        logging.info('total:'+str(total))
        order.total = str(total)
        order.put()
        trimmed = str(total).replace('.',',') + '0'
        ExtraCost = 0
        GuaranteeOffered = 2
        OkUrl = 'http://' + self.request.host + r'/paysonreceive/'
        Key = '6230fb54-7842-3456-b43a-349b340de3b8'
        text = 'niklasro@gmail.com' + ':' + str(trimmed) + ':' \
            + str(ExtraCost) + ':' + OkUrl + ':' \
            + str(GuaranteeOffered) + Key
        m = hashlib.md5()
        BuyerEmail = user.email  # if user.email else user.auth_id[0]
        AgentID = 11366
        self.render_jinja(
            'order.htm',
            order=order,
            user=user,
            total=total,
            Generated_MD5_Hash_Value=hashlib.md5(text).hexdigest(),
            BuyerEmail=user.email,
            Description='Bnano Webshop',
            trimmed=trimmed,
            OkUrl=OkUrl,
            BuyerFirstName=user.firstname,
            BuyerLastName=user.lastname,
            )

解决方案

Man, this is a really strange code. If you will want to add new items in you shop you must rewrite you shop's script. At the first unlink your items from interface, you must send POST request to controller with your items ids and quantity, i don know how work gae request object, but it must be like that: from your order page make POST request with dict of items which really need {"item_id":"qnt"}. When in the controller you can fetch all objects like:

for item, qnt in request.POST:
    {do something with each item, for example where you can sum total}

and etc Don't link controllers with your interfaces directly. You must write more abstraction code, if you want make really flexible app.

这篇关于一次从网上商店购买许多产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆