Advertisement
Guest User

Untitled

a guest
May 29th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.72 KB | None | 0 0
  1. # -*- coding: UTF-8 -*-
  2. # Import de configuração do django para wsgi
  3. try:
  4.     from django.conf  import settings
  5.     settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,TEMPLATE_DIRS=('/tmp', '/tmp'))
  6. except:
  7.     pass
  8. from django.core.handlers.wsgi import WSGIRequest
  9.  
  10. #Python Imports
  11. import psycopg2
  12. import cgi,cgitb    
  13. # classe testew
  14. class testew:
  15.     """ teste ! """
  16.     def __init__(self, action, ):
  17.     """ Constructor da classe testew """
  18.     if(not action): action = 'listar'
  19.     self.action = action
  20.     if(self.action in ('listar','editar','processarcadastrar','processareditar') ):
  21.         conn = psycopg2.connect("dbname=db_produto user=postgres password=532146")
  22.         self.Cursor = conn.cursor()
  23.     #
  24.  
  25.     def listar(self, ):
  26.         """ listar """
  27.         self.Cursor.execute("select * from tbl_produto")
  28.         produtos = ''
  29.         cabecalho = '<html><head></head><body><div align="center"><h1>Lista de Produtos</h1><table bgcolor="burlywood">'
  30.         rodape = '</table><a href="index.py?acao=cadastrar"><button type="submit" value="Cadastrar" method="get">Cadastrar Novo Produto</a></button><p></div></body></html>'
  31.         for tab in self.Cursor:
  32.             edit = '<a href="index.py?acao=editar&id_produto=%s" method="get"><button type="submit" value="Editar">Editar</button></a>' % (tab[0])
  33.             tab = ('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (tab[1],tab[2],tab[3],tab[4],edit))
  34.             produtos += tab
  35.         id_produto = tab[0]
  36.         pagina = cabecalho + produtos + rodape
  37.         return pagina
  38.  
  39.  
  40.     def editar(self, id_produto):
  41.         """ editar """
  42.         self.Cursor.execute('select * from tbl_produto where cod_produto=%s;' % (id_produto))
  43.         tab = ''
  44.         cabecalho = '<html><head></head><body><div align="center"><h1>Edição de Produto</h1><div align="center"><h1>Dados sobre o produto</h1><form method="POST" name="edit" action="index.py?acao=processareditar&id_produto=%s"><fieldset><legend><b>Dados do Produto</b></legend>' % (id_produto)
  45.         rodape = '<button type="submit">*** Grava ***</button></form></div></body></html>'
  46.         for tab1 in self.Cursor:
  47.             tab += '<label><input type="hidden" name="id_produto" value="%s"></input></label>' % (tab1[0])
  48.             tab += '<br/><label>Nome: <br/><input type="text" name="nome" value="%s"></input></label><br/>' % (tab1[1])
  49.             tab +='<label>Preço:<br/><input type="float" name="preco" value=%s></input></label><br/>' % (tab1[2])
  50.             tab +='<label>Quantidade:<br/><input type="int" name="quantidade" value=%s></input></label><br/>' % (tab1[3])
  51.             tab += '<label>Fabricante <br/><input type="text" name="fabricante" value="%s"></input></label><br/> ' % (tab1[4])
  52.        
  53.         pagina = cabecalho + tab + rodape
  54.         return pagina
  55.    
  56.     # Processar editar
  57.    
  58.     def processareditar(self,nome,preco,quantidade,fabricante,id_produto):
  59.         """ a"""
  60.        
  61.         sql = ("BEGIN TRANSACTION; UPDATE tbl_produto SET nome='%s', preco=%s, quantidade=%s, fabricante='%s' WHERE cod_produto=%s ;COMMIT;" % (nome,preco,quantidade,fabricante,id_produto))
  62.         self.Cursor.execute(sql)                                                                                                                  
  63.         pagina = """<html><head>
  64.        <title>Confirmação de Edição de Registro</title>
  65.        </head><body>
  66.        <div align="center"><h1>Dados cadastrados com sucesso</h1>
  67.        <a href="index.py"><button value="Voltar">Voltar</button></a>
  68.        </div></body></html>"""
  69.         return pagina
  70.     #
  71.    
  72.    
  73.     def cadastrar(self, ):
  74.         """ cadastrar """
  75.         cadastro = """ <html><head></head><body>
  76.        <h1>Cadastro de Produtos</h1>
  77.        <form method="POST" name="form" action="index.py?acao=processarcadastrar">
  78.        <fieldset>
  79.        <legend><b>Dados do Produto</b></legend>
  80.        <br/><label>Nome: <br/>
  81.        <input type="text" name="nome"/>
  82.        </label><br/>
  83.        <label>Preço:<br/><input type="float" name="preco"/>
  84.        </label><br/>
  85.        <label>Quantidade:<br/><input type="int" name="quantidade"/>
  86.        </label><br/>
  87.        <label>Fabricante <br/><input type="text" name="fabricante"/>
  88.        </label><br/>
  89.        <button type="submit" value="Cadastrar">Cadastrar</button><input type="reset" value="Limpar"/>
  90.        </fieldset>
  91.        </form>
  92.        </body>
  93.        </html>
  94.        """
  95.         return cadastro
  96.     #
  97.  
  98.     def processarcadastrar(self,nome,preco,quantidade,fabricante):
  99.         """ aaa """
  100.         sql = "BEGIN TRANSACTION; insert into tbl_produto(nome,preco,quantidade,fabricante)values('%s', %s, %s, '%s');COMMIT;" %(nome,preco,quantidade,fabricante)
  101.         self.Cursor.execute(sql)
  102.         pagina = """<html><head>
  103.        <title>Confirmação de cadastro</title>
  104.        </head><body>
  105.        <div align="center"><h1>Dados cadastrados com sucesso</h1>
  106.        <form action="index.py?acao=listar"><button value="Página Inicial" type="submit">Página Inicial</button></form>
  107.        </div></body></html>"""
  108.         return pagina
  109.    
  110.    
  111.    
  112.     #
  113.  
  114. def application(environ, start_response):
  115.     """
  116.    teste aplication WSGI
  117.    """
  118.     #Request
  119.     request = WSGIRequest(environ).GET
  120.     id_produto = str(request.get('id_produto', ''))
  121.     acao = str(request.get('acao', ''))
  122.     output = "id_produto: *%s*" %(id_produto)
  123.     obj = testew(acao)
  124.  
  125.     #Tratando o executar
  126.     # import pdb;pdb.set_trace()
  127.     if(acao == 'editar'):
  128.         output = str(obj.editar(id_produto))
  129.        
  130.     elif(acao == 'cadastrar'):
  131.         output = str(obj.cadastrar())
  132.        
  133.     elif(acao == 'processarcadastrar'):
  134.         request = WSGIRequest(environ).POST
  135.         nome = str(request.get('nome',''))
  136.         preco = str(request.get('preco',''))
  137.         quantidade = str(request.get('quantidade','') )
  138.         fabricante = str(request.get('fabricante','') )  
  139.         output = str(obj.processarcadastrar(nome,preco,quantidade,fabricante))        
  140.        
  141.     elif(acao == 'processareditar'):
  142.         request = WSGIRequest(environ).POST        
  143.         nome = str(request.get('nome',''))
  144.         preco = str(request.get('preco',''))
  145.         quantidade = str(request.get('quantidade','') )
  146.         fabricante = str(request.get('fabricante','') )
  147.         id_produto = str(request.get('id_produto',''))
  148.         output = str(obj.processareditar(nome,preco,quantidade,fabricante,id_produto))
  149.        
  150.     else:
  151.         output = str(obj.listar())
  152.     ##
  153.  
  154.     #Return
  155.     status = '200 OK'
  156.     response_headers = [('Content-type', 'text/html'),
  157.                         ('Content-Length', str(len(output)))]
  158.     start_response(status, response_headers)
  159.     return [output]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement