NameError : name 'pass_result' not defined line 25? - python

Index.html:
<html>
<head>
<title>Login Page</title>
<link type="text/css" rel="stylesheet" href="coach.css" />
</head>
<body>
<img src="images/logo-cel-transparent_0.png" width="74" height="64"><strong><img src="images/logo-cel-transparent_0.png" alt="Cel logo" width="74" height="64" align="right">
</strong>
<h1 align="center"><strong>Central Electronics Limited</strong></h1>
<p> </p>
<h2 align="center">Storage Management System</h2>
<p> </p>
<p align="center">Login To System</p>
<p align="center"> </p>
<form action="cgi-bin/validate.py" method="post">
<div align="center">Username :
<input type="text" name="username">
<br>
Password :
<input type="text" name="password">
<br>
<input type="submit" value="Submit">
</div>
</form>
<p align="center"> </p>
</body>
</html>
validate.py:
import cgi
import yate
import sqlite3
import sys
connection = sqlite3.connect('users.sqlite')
cursor = connection.cursor()
print('Content-type:text/html')
form=cgi.FieldStorage()
for each_form_item in form.keys():
if (each_form_item=='username'):
username=form[each_form_item].value
if (each_form_item=='password'):
password=form[each_form_item].value
result=cursor.execute('SELECT USERNAME from validate')
usernames=[row[0] for row in result.fetchall()]
print(usernames)
for each_username in usernames:
if (username==each_username):
pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,))
password1=[row[0] for row in pass_result.fetchall()]
for each_password in password1:
if (each_password==password):
with open("C:\Python34\ProjectShivam\webapp\cgi-bin\successvalidate.py") as f:
code = compile(f.read(), "successvalidate.py", 'exec')
exec(code)
else:
print('')
print('Login Failure')
successvalidate.py:
import yate
print(yate.start_response())
print(yate.para("Login Successful"))
print(yate.include_footer({"Click here to Go to Welcome Page":"/welcome.html"}))
simple_httpd.py(The server code):
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8080
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
I run the server(simple_httpd.py) using command prompt. The index page opens up. I enter the 1st set of username and password. It runs as expected and successvalidate.py opens up. But when i enter the 2nd set of username and password(i.e, the second row of table validate in users.sqlite)(validate table contains two set of usernames and passwords), it displays on cmd:
127.0.0.1 - - [18/Jun/2015 20:59:29] b'Traceback (most recent call last):\r\n F
ile "C:\\Python34\\ProjectShivam\\webapp\\cgi-bin\\validate.py", line 25, in <mo
dule>\r\n password1=[row[0] for row in pass_result.fetchall()]\r\nNameError:
name \'pass_result\' is not defined\r\n'
Also any other username does not result in the text 'Login Failure' being printed on the web browser but instead same error shows on server. What is wrong?

you are getting the error when this condition is not met:
if (username==each_username):
pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,))
set a default value to pass_result, e.g. pass_result = None and then handle it before using, e.g. if pass_result is not None:

Related

How get bootstrap in my html read through python socket

I have been try simple python socket, I have bootstrap.min.css in the same directory of registro.html, but it's not charge style from bootstrap, registro.html, bootstrap.min.css and soket_test.py are in same directory.
I have been do request from any browser.
socket_test.py
#!/usr/bin/env python
import socket
import json
import re
def getValorArreglo(parametros, clave):
for indice in parametros:
if indice.split('=')[0] == clave:
return indice.split('=')[1]
return None
'''def setSiguienteVista(action,parametros):
if action != None and action == '/formulario':'''
host = '127.0.0.1'
port = 8791
server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create a socket object
server_sock.bind((host , port)) # Bind to the port
server_sock.listen(5) # Now wait for client connection.
print ('Entering infinite loop; hit CTRL-C to exit')
while True:
# Establish connection with client.
client_sock, (client_host, client_port) = server_sock.accept()
print ('Got connection from', client_host, client_port)
request = b""
contador = 0
while not b"\r\n\r\n" in request:
request += client_sock.recv(1000) # should receive request from client. (GET ....)
client_sock.send(b'HTTP/1.0 200 OK\n')
client_sock.send(b'Content-Type: text /html\n')
client_sock.send(b'\n') # header and body should be separated by additional newline
# you can paste your 2 text field html here in the <body>
HtmlFile = open('registro.html','r')
registro = HtmlFile.read()
client_sock.send(registro)
client_sock.close()
registro.html
<!DOCTYPE html>
<html>
<head>
<title>Proyecto Sistemas Distribuidos</title>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<form method="post" action="formulario"class="form-group" >
<div class="form-row etiqueta_principal">
<label class="text-label-principal">REGISTRO DE BACHILLER ASPIRANTE</label>
</div>
<div class="form-row">
<div class="form-group col-md-3 item-div">
<label class="col-md-12 item-label" for="nombre1">Primer Nombre</label>
<input type="text" class="form-control" id="nombre1" name="nombre1" placeholder="Ingrese primer nombre"
required>
</div>
<div class="form-group col-md-3 item-div">
<label class="col-md-12 item-label" for="nombre2">Segundo Nombre</label>
<input type="text" class="form-control" id="nombre2" name="nombre2"
placeholder="Ingrese segundo nombre">
</div>
<div class="form-group col-md-3 item-div">
<div class="item-div button-div">
<button type="submit" class="btn btn-secondary">Enviar Solicitud</button>
</div>
</div>
</form>
</body>
</html>

How to get contents from a local text file to print on individual lines in a html template (Python/Flask)

screenshot of the outputI'm looking to get posts from a user to post on individual lines. At the moment I take in a name, email and comment, pass it to the app.py file and store it to a text file. I return a name, email, comment and the time of the comment. When I read the file and pass in back to the html template the posts display one after the other (see the screenshot included), and im trying to have them display one below each other. f.write("\n") results in the actual text file skipping a line however this does not occur in the template.
form_action.html
<html>
<div align = "center">
<body style="background-color: #3DC247;">
<head>
<title>Conor McGregor</title>
</head>
<body>
<div align = "center">
<h1 style="font-family:verdana;">I AM EL CHAPO</h1>
<div align = "center">
<h2 style="font-family:verdana;">YOU'LL DO NUTIN.</h2>
<div align = "center">
<h2 style="font-family:verdana;">Disscusion Page</h2>
<body>
<div id="container">
<div class="title">
<h3 style="font-family:verdana;">Please fill in your details
below and your comment to join the discussion</h3>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname" style="font-family:verdana;">Please
enter your name:</label>
<input type="text" name="yourname" /><br /><br>
<label for="youremail" style="font-family:verdana;">Please
enter your email:</label>
<input type="text" name="youremail" /><br /><br>
<label for="yourcomment"style="font-family:verdana;">Please
enter your comment:</label>
<input type="textarea" name="yourcomment" rows="4" cols="50">
<input type="submit" /><br>
</form>
</div>
</div>
</div>
</div>
<div id="container">
<div class="title">
<h1 style="font-family:verdana;"><p>Comments</p></h1>
</div>
<div id="content">
{{details}}
</div>
</div>
</body>
</html>
app.py
from flask import Flask, render_template, request, url_for
import time
import datetime
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
#app.route('/hello/', methods=['POST','GET'])
def hello():
global time
name=request.form['yourname']
email=request.form['youremail']
comment=request.form['yourcomment']
comment_time=time.strftime("%a-%d-%m-%Y %H:%M:%S")
f = open ("user+comments.txt","a")
f.write(name + ' ' + email + ' ' + comment + " " + comment_time)
f.write('\n')
f.close()
with open("user+comments.txt", "r") as f:
details = f.read()
f.close()
return render_template('form_action.html', details = details, name=name,
email=email, comment=comment, comment_time=comment_time)
if __name__ == '__main__':
app.run(debug=True)
HTML does not know what \n is. You can fix this in two ways.
Convert str details to list details
details = f.read().split('\n')
This converts the str object to list object. You could print it in your template using
{% for detail in details %}
{{detail}}
{% endfor %}
Replace \n with <br>
details = f.read().replace('\n','<br>')
and then print it as {{ details|safe }} in form_action.html.
It is important that you use the safe filter. The <br> would be escaped without it and rendered as simple text.

How do I recover the address server of user, put it in variable and execute it in command line

scriptInfo.py
import os, sys, platform, webbrowser
def main()
template = open('scriptHmtl.phtml').read()
scriptHtml.phtml
<html>
<head>
</head>
<body>
<h2><center> welcome </center></h2>
<br/><br/><br/>
...
variables
..
<form name="sendData" method="get" action="http://localhost:8000/cgi/scriptGet.py">
Name: <input type="text" name="n"><br/><br/>
First Name: <input type="text" name="fn"/><br/><br/>
Mail: <input type="text" name="ma"/><br/><br/>
Address: <input type="text" name="add"/> <br/><br/>
<input type="submit" value="OK"/>
</form>
Instead of action="http://localhost:8000/cgi/scriptGet.py", there must be a variable which contain the code to recover the server address, but I don't want how to do it.
With HTML forms you can just ignore the server and go straight to the script.
For example like
<form name="sendData" method="get" action="cgi/scriptGet.py">

Why does this work via the command line, but not via a web browser?

Why does this work via the command line, but not my via a web browser?
(both files in python only the 2nd one loads)
import cgi
import cgitb; cgitb.enable()
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
reshtml = """Content-Type: text/html\n
<html>
<head><title>login</title></head>
<body>
"""
print reshtml
User_Name = form.getvalue('User_Name')
password = form.getvalue('Pass_Word')
log="info: "
if User_Name == 'NAME' and password == 'passcode':
log=log+"login passed "
else:
log=log+"login failed "
print log
print '</body>'
print '</html>'
I invoke it using a file that passes in the parameters "User_Name" and "Pass_Word":
#!/Python27/python
print "Content-type: text/html"
print
print """
<html><head>
<title>log in</title>
</head><body>
"""
import sha, time, Cookie, os, fileinput, cgi, cgitb
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
log = "info: "
cookie = Cookie.SimpleCookie()
string_cookie = os.environ.get('HTTP_COOKIE')
string_cookie = str(string_cookie)
infoform = """
<link rel="stylesheet" type="text/css" href="styles/home.css" media="screen" />
<div id="top" style=" height:50px;width:100%;position:absolute;left:0px;top:0px;" >
<form action="router.py" method="post" target="_self">
<div id="form" style="position:absolute;left:15px;top:20px;" >
<input type="text" name="User_Name" value="User Name">
<input type="password" name="Pass_Word" value="Password">
<input type="hidden" name="status_url">
<input type="submit" value="Log in">
</div>
</form>
<div ID"home"></div>
</div>
<div id="GBbody" style="position:absolute;left:1px;top:55px;height:100%;width:100%;" >
<p id="disply">
<center><h2>
Hi, and welcome!
</h2></center>
<h4>
Did you know: just the movie player and code that goes with it takes<br>
474 lines of code so-far, and may not work many web browsers (for the time being), however <br>
Google chrome is fully compatible at this point.
</h4>
</p>
</div>
"""
loginas = """
<form action="home.py" method="post" target="_self">
<input type="submit" value="Continue last session" style="position:absolute;right:15px;top:20px;">
</form>
"""
if "sess" in string_cookie:
infoform = infoform.replace('<div ID"home"></div>',loginas)
print infoform
else:
print infoform
print "</body></html>"
but, it prints out an Internal Server Error page, help? Post script I have just reinstalled python 2.7.3
Try using Flask it not only has debug support but all the tool you need to make a web service, also if you don't want to use Flask. look at your server(Apache or nginx) logs

Retrieving value from Python SimpleCookie and using it in SELECT query

I posted a question yesterday :
Redirect python script to another python script for validation of login credentials
after i was done with that bit, i had another problem related to cookies. I sent the cookies in the header from the python script code:
#Create Cookie
C= Cookie.SimpleCookie()
#take the value of usernameLogin into the variable username
username= form.getvalue('usernameLogin')
#Set-Cookie header with the usernameLogin key
C['usernameLogin'] = username
this code is in the previous python script validate.py
i want to send the cookies to the next script page1.py
this is my code for page1.py :
import cgi
import cgitb
import sqlite3
import Cookie
import os
user_name=""
user_id=""
useridDb=""
resultid=""
resultname=""
idUser=""
if os.environ.has_key("HTTP_COOKIE"):
C= Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE",""))
if C.has_key("usernameLogin"):
user_name= C['usernameLogin'].value
print user_name
form= cgi.FieldStorage()
cgitb.enable()
#Open connection
conn= sqlite3.connect("manager.db")
page1head= """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Excursions</title>
<link rel='stylesheet' type='text/css' href='/page1.css/' />
<script lang="javascript" type="text/javascript" src="/suggestions.js/"> </script>
</head><body>
<div id="container">
<div id="header">
<h1>Field Note Manager</h1>
<p class="description">Observe...Record...Save!</p>
</div>
<!-- Content Section -->
<div id="wrapper">
<!-- Main Content Section -->
<div id="content">
<h2>Excursions</h2>
<table CELLPADDING="10" ><tr><th> <strong> Location </strong> </th><th> <strong> Date </strong> </th> <th> Time </th></tr>"""
page2head="""</table>
</div>
</div>
<!-- Logout Section -->
<div id="navigation">
<input type="hidden" name="greeting"/>
<form action="http://localhost:8000/cgi-bin/logout.py">
<p><input type="submit" name="logoutBtn" value="Logout" /> </p>
</form>
</div>
<!-- Extra Section for Queries -->
<div id="extra">
<h2>Quick Links</h2>
<dl> <dd><a href="http://localhost:8000/cgi-bin/query.py"/>Query the Database</a> </dd></dl>
<dl> <dd><a href="http://localhost:8000/cgi-bin/addFieldNote.py"/>Add Field Note</a> </dd></dl>
</div>
<!-- Footer -->
<div id="footer">
<p>Copyright 42578647, 2012</p>
</div>
</div>
"""
page1foot= """
</body>
</html>
"""
print "Content_type: text/html\n\n"
print page1head
#print excursion details
cur=conn.cursor()
resultid= cur.execute("SELECT userid FROM login WHERE username=?",[user_name])
cur.fetchone()
for data in resultid:
idUser= int(data)
resultname= cur.execute("""SELECT location,excurDate,excurTime FROM excursion WHERE user=?""",[idUser])
cur.fetchall()
for record in resultname:
print"<tr><td>",record[0],"</td><td>",record[1],"</td><td>",record[2],"</td></tr>"
print page2head
print page1foot
It prints the page, but no queries are generated. Is it because the cookie has not been retrieved and parsed or is there some problem with the SELECT statement?
I found out the answer. The cookies had not been set before the header in the previous validate.py

Categories

Resources