def compra(assento, espetaculo, cartao): assento = assento.split('<')[1] assento = assento.split('>')[0] espetaculo = espetaculo.split('<')[1] espetaculo = espetaculo.split('>')[0] cartao = cartao.split('<')[1] cartao = cartao.split('>')[0] host = HOST_TS port = PORT_TS tsname = espetaculo ts = NetWorkSpace(tsname, host, port) try: seat = ts.fetchTry(assento) ts.deleteVar(seat) if (seat == None): exit(0) #Envio para fila de mensagens connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='pendentes') channel.basic_publish(exchange='', routing_key='pendentes', body=cartao + '-' + seat) print(" [x] Mensagem recebida'") connection.close() aprovado = fila(assento) if aprovado == 1: retorno = '<link rel="stylesheet" type="text/css" media="screen" href="../static/index.css" />' retorno += "<h1>Compra aprovada! Obrigado por comprar conosco :D</h1>" retorno += '<br><br><button class="show"><a href="/">Home</a></button>' return retorno elif aprovado == 0: ts.store(seat, assento) retorno = '<link rel="stylesheet" type="text/css" media="screen" href="../static/index.css" />' retorno += "<h1>Compra reprovada :( Tente com outra forma de pagamento.</h1>" retorno += '<br><br><button class="show"><a href="/">Home</a></button>' return retorno else: retorno = '<link rel="stylesheet" type="text/css" media="screen" href="../static/index.css" />' retorno += "<h1>Falha na compra</h1>" retorno += '<br><br><button class="show"><a href="/">Home</a></button>' return retorno except: raise return "Except: Falha na compra."
class Provider: def __init__(self, ws_name='Estoque', time_sleep=1, batch_size=10): self.time_sleep = time_sleep self.batch_size = batch_size #self.rmi=RMIManager() self.workspace = NetWorkSpace(ws_name, cfg.ts_machine_ip, cfg.ts_machine_port, persistent=True) #Método para gerar lotes de um produto # product_amount (int): quantidade requisitada do produto. def generateBatch(self, product_amount): n_batchs = int(ceil((product_amount * 1.0) / self.batch_size)) delivery = 0 for i in range(n_batchs): sleep(self.time_sleep) delivery += self.batch_size return delivery #Método que fornece uma quantidade do produto no espaço de tuplas # product_name (string): nome do produto; # product_amount (int): quantidade requisitada do produto def supply(self, product_name, product_amount): print 'Processando requisição para (' + str(product_name) + ',' + str( product_amount) + ')' sleep(self.time_sleep) delivery = self.generateBatch(product_amount) self.workspace.store(product_name, delivery) print 'Requisição entregue'
class Chat(threading.Thread): def __init__(self, user, varName, wsName, **opt): threading.Thread.__init__(self, name="Chat") self._user, self._varName, self._wsName = user, varName, wsName self._ws = NetWorkSpace(wsName, persistent=True, **opt) self._ws.declare(varName, FIFO) self._queue = Queue.Queue() recvWs = NetWorkSpace(wsName, **opt) self._ifind = recvWs.ifind(varName) self.setDaemon(True) self.start() def sendMessage(self, ent): msg = ent.get().strip() if len(msg) > 0: self._ws.store(self._varName, "%s: %s" % (self._user, msg)) ent.delete(0, END) def checkForNewMessages(self, txt): txt.config(state=NORMAL) while not self._queue.empty(): txt.insert(END, self._queue.get() + "\n") txt.see(END) txt.config(state=DISABLED) txt.after(1000, self.checkForNewMessages, txt) def run(self): for val in self._ifind: self._queue.put(val)
class Sentinel(threading.Thread): def __init__(self, nwsHost, nwsPort, nwsName, gotShutdown): threading.Thread.__init__(self, name='Sentinel:' + nwsName) self.nwsHost = nwsHost self.nwsPort = nwsPort self.nwsName = nwsName self.gotShutdown = gotShutdown self.ws = NetWorkSpace(self.nwsName, self.nwsHost, self.nwsPort, useUse=True, create=False) def __str__(self): return "%s@%s:%d" % (self.nwsName, self.nwsHost, self.nwsPort) def run(self): try: try: self.ws.find('Sleigh ride over') self.ws.store('bye', 'Sleigh ride over') except Exception, e: try: self.ws.store('bye', str(sys.exc_info()[1])) except: pass finally: try: self.gotShutdown(self) except: pass try: self.ws.server.close() except: pass
class TSManager: def __init__(self): self.ws = NetWorkSpace('Estoque', cfg.ts_machine_ip, cfg.ts_machine_port, persistent=True) def put(self, item_name, quantity): self.ws.store(item_name, quantity) def get(self, item_name): available = self.ws.fetchTry(item_name) return available def checkStock(self, content): new_order = content for item in new_order["items"]: left = item["need"] - item["have"] while item["need"] > item["have"]: in_stock = self.get(item["name"]) if in_stock == None: break got = min(in_stock, left) item["have"] += got in_stock -= got if in_stock > 0: self.put(item["name"], in_stock) return new_order
def babelfish(host, port): ws = NetWorkSpace('Python babelfish', host, port) while 1: try: v = ws.fetch('food') t = str(v) if len(t) > MAXLEN: t = t[:MAXLEN] + '[WARNING: output truncated]' elif not t: t = repr(v) except NwsUnpicklingException, e: t = 'Unpickling error: ' + str(e.exception) ws.store('doof', t)
class Chat: def __init__(self, user, varName, wsName, **opt): self._user, self._varName, self._wsName = user, varName, wsName self._ws = NetWorkSpace(wsName, persistent=True, **opt) self._ws.declare(varName, FIFO) self._ifindTry = self._ws.ifindTry(varName) def sendMessage(self, ent): msg = ent.get().strip() if len(msg) > 0: self._ws.store(self._varName, "%s: %s" % (self._user, msg)) ent.delete(0, END) def checkForNewMessages(self, txt): txt.config(state=NORMAL) self._ifindTry.restart() for msg in self._ifindTry: txt.insert(END, msg + '\n') txt.see(END) txt.config(state=DISABLED) txt.after(1000, self.checkForNewMessages, txt)
except ImportError, e: print >> sys.stderr, "unable to import the nws.client python module" print >> sys.stderr, "make sure you have nwsclient installed on this machine" sys.exit(1) try: ws = NetWorkSpace('snake pit') except ImportError, e: print >> sys.stderr, "make sure you're running the NWS server on this machine" print >> sys.stderr, str(e) sys.exit(1) print 'connected, listing contents of netWorkSpace (should be nothing there).' print ws.listVars() ws.store('x', 1) print 'should now see x.' print ws.listVars() print 'find (but don\'t consume) x.' print ws.find('x') print 'check that it is still there.' print ws.listVars() print 'associate another value with x.' ws.store('x', 2) print ws.listVars() print 'consume values for x, should see them in order saved.' print ws.fetch('x') print ws.fetch('x')
#!/usr/bin/env python import sys, socket host = "localhost" port = 8765 wsname = "hello" try: from nws.client import NetWorkSpace nws = NetWorkSpace(wsname, host, port) count = int(raw_input("Number of times to loop? ")) print "hello: iterations:", count nws.store("hello example", count) for i in range(count): nws.store("hello", i) j = nws.fetch("hello") nws.fetch("hello example") print "Success" except KeyboardInterrupt: print "hello exiting" except ImportError: print "Unable to import the nwsClient module" print "You may need to set or correct your PYTHONPATH" except socket.error: print "NWS server not running on %s, port %d" % (host, port) except:
#start tuple space - twistd -y /etc/nws.tac #deleteVar() - deleta #find() - return a value #store() - insere no espaco #fetch() - retira do espaco #fetchTry() - retira nao bloqueante port = 8765 host = sys.argv[1] shows = ["Red Hot Chili Peppers", "ACDC", "Linkin Park", "Iron Maiden"] for tsname in shows: data = NetWorkSpace("database", host, port, persistent=True) data.declare(tsname, 'fifo') data.store(tsname, tsname) ts = NetWorkSpace(tsname, host, port, persistent=True) alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] try: for i in alpha[:10]: for j in range(10): ts.declare("%s%d" % (i, j), 'fifo') ts.store("%s%d" % (i, j), "%s%d" % (i, j)) print("Creation successful!") except: print ("Creation failed.") print ("new_show.py <show_name> <host> <show_size>")
#!/usr/bin/env python from nwss.local import NwsLocalServer from nws.client import NetWorkSpace from nws.sleigh import Sleigh from math import sqrt # start the local nws server srv = NwsLocalServer(daemon=False) srv.wait_until_started() # try an nws example ws = NetWorkSpace('foo', serverPort=srv.port) print ws for i in range(10): ws.store('x', 'Value %d' % i) print list(ws.ifetchTry('x')) # try a sleigh example s = Sleigh(nwsPort=srv.port) print s for i in xrange(10): print s.eachElem(sqrt, range(10)) # shutdown the local nws server print 'shutting it down' srv.shutdown() assert not srv.isAlive() try:
host = "localhost" port = 8765 wsname = "ping-pong" if len(sys.argv) == 2: wsname = sys.argv[1] elif len(sys.argv) != 1: print >> sys.stderr, "Usage: %s [<wsname>]" % sys.argv[0] sys.exit(1) try: from nws.client import NetWorkSpace nws = NetWorkSpace(wsname, host, port) nws.store("game", 0) print "Ping-pong server '%s' starting" % wsname while 1: request = nws.fetch("ping") pong = request["replyto"] request["time"] = time.asctime() print "Got a ping from", pong nws.store(pong, request) except KeyboardInterrupt: print "Ping-pong server '%s' exiting" % wsname except ImportError: print "Unable to import the nwsClient module" print "You may need to set or correct your PYTHONPATH" except socket.error:
loops = int(sys.argv[1]) except: print >> sys.stderr, "Usage: %s [<loops> [<wsname>]]" % sys.argv[0] sys.exit(1) if len(sys.argv) == 3: wsname = sys.argv[2] elif len(sys.argv) != 1: print >> sys.stderr, "Usage: %s [<loops> [<wsname>]]" % sys.argv[0] sys.exit(1) try: from nws.client import NetWorkSpace nws = NetWorkSpace(wsname, host, port, useUse=True) game = nws.fetch("game") nws.store("game", game + 1) pong = "pong_%d" % game request = {'replyto': pong} print "Starting a ping-pong game", game for i in xrange(loops): request['i'] = i nws.store("ping", request) reply = nws.fetch(pong) print reply if i != reply['i']: print "Error: expected %d, received %d" % (i, reply['i']) nws.deleteVar(pong) except KeyboardInterrupt: