Ben Sizer wrote:
But do you have an example of such a use case?
Here is a 69 lines implementation of the idea of applying extended
generators to manage Web forms (obviously this is only a proof of
concept and it contains many mistakes, but you have something to get
started).
Notice that I am not claiming that this is a good idea.
Michele Simionato
---
import datetime
import cherrypy as cp
# each user (but really should be each session) has her input loop
# one should disable the back button and implement an undo mechanism
def inputloop(user):
start_time = datetime.datetime.today()
cart = []
while True: # fill the shopping cart
item = yield locals()
if item == 'start':
continue
elif item == 'end':
break
elif item:
cart.append(item)
finish_time = datetime.datetime.today()
yield locals()
class User(object):
def __init__(self, name):
self.name = name
self.inputloop = inputloop(self)
self.inputloop.send(None) # start the user loop
users = dict(michele=User('michele'))
class Root(object):
@cp.expose
def login_welcome(self):
yield 'hello!'
yield '<form action="login_action">'
yield "what's your name? "
yield '<input type="text" name="name"/>'
yield '</form>'
@cp.expose
def login_action(self, name):
yield ('<a href="shopping_loop?name=%s&item=start">'
'You may start shopping</a><br/>') % name
@cp.expose
def shopping_loop(self, name, item):
if not name in users:
yield '%r is not a valid name; please retry' % name
return
user = users[name]
status = user.inputloop.send(item)
if item == 'start':
yield 'Today is %s<br/>' % status['start_time']
yield 'Please buy something!<br/>'
if item == 'end':
yield 'Thanks for shopping, %s<br/>' % user.name
yield 'You bought items %s<br/>' % status['cart']
yield 'Today is %s' % status['finish_time']
return
yield '<form action="">'
yield 'The content of your cart is %s<br/>' % status['cart']
yield 'Please enter the item you want to buy: '
yield '<input type="text" name="item"/><br/>'
yield '<input type="hidden" name="name" value="%s"/>' % name
yield '(enter end to finish)'
yield '</form>'
index = login_welcome
if __name__ == '__main__':
cp.root = Root()
cp.server.start()