I execute my script in command line.
When I execute ./script.py server_adress param2 param3 param4 it opens a page with html form and a button, when we type on the button, I want to retrieve this server address.
that's a part of the code of the script.py :
import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
def main( server_IP, code_name, code_version, install_path):
template = open('scriptHmtl.phtml').read()
contenu = string.Template(template).substitute(
code_name = code_name,
code_version = code_version,
install_path = install_path,
os = user_os,
user_name = user_login
)
f = tempfile.NamedTemporaryFile(prefix='/tmp/info.html', mode='w', delete=False)
f.write(contenu)
f.close()
webbrowser.open(f.name)
if __name__ == "__main__":
server_IP = sys.argv[1]
code_name = sys.argv[2]
code_version = sys.argv[3]
install_path = sys.argv[4]
user_os = sys.platform
sys.argv.append(user_os)
user_login = getpass.getuser()
sys.argv.append(user_login)
config_file = open("config.txt", "w")
json.dump(sys.argv, config_file)
main(server_IP, code_name, code_version, install_path)
and here, the code html to get the address , scriptHtml.py
<html>
<body>
App: ${code_name}<br/><br/>
cv: ${code_version}<br/><br/>
path install: ${install_path}<br/><br/>
<form name="Data" method="get" action="http://localhost:8000/cgi/scriptGet.py">
Name: <input type="text" name="name"><br/><br/>
First name: <input type="text" name="fn"/><br/><br/>
Mail: <input type="text" name="mail"/><br/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
action="http://localhost:8000/cgi/scriptGet.py" -> I think the problem is here.
What you really want to do here is use a proper Python Web Framework.
CGI went out of fasion decdaes ago?
Example: (Using circuits):
#!/usr/bin/env python
"""Forms
A simple example showing how to deal with data forms.
"""
from circuits.web import Server, Controller
FORM = """
<html>
<head>
<title>Basic Form Handling</title>
</head>
<body>
<h1>Basic Form Handling</h1>
<p>
Example of using
circuits and its
<b>Web Components</b> to build a simple web application that handles
some basic form data.
</p>
<form action="/save" method="POST">
<table border="0" rules="none">
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td colspan=2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</body>
</html>"""
class Root(Controller):
def index(self):
"""Request Handler
Our index request handler which simply returns a response containing
the contents of our form to display.
"""
return FORM
def save(self, firstName, lastName):
"""Save Request Handler
Our /save request handler (which our form above points to).
This handler accepts the same arguments as the fields in the
form either as positional arguments or keyword arguments.
We will use the date to pretend we've saved the data and
tell the user what was saved.
"""
return "Data Saved. firstName={0:s} lastName={1:s}".format(
firstName, lastName
)
app = Server(("0.0.0.0", 8000))
Root().register(app)
app.run()
Disclaimer: I'm the developer of circuits.
NB: There are many other good Python Web Frameworks:
flask
bottle
Django
... etc ...
contenu = string.Template(template).substitute(
code_name = code_name,
code_version = code_version,
install_path = install_path,
os = user_os,
user_name = user_login
server_IP = http:8000/cgi/scriptGet.py
)
scriptHtml.py
<form name="Data" method="get" action="${server_IP}">
that is something like that ?
Related
here is my code to upload images to folder and name to the database and it isn't working.
i am getting an error 'bytes' object has no attribute 'image' Exception occured
#html code -->#
<html>
<head>
<TITLE> Product Image</TITLE>
</head>
<body>
<form enctype="multipart/form-data" action="productimg.py" method=post>
<table align=center cellspacing=20 cellpadding=10 >
<th align="center" colspan=3 > <u>Upload Image of the Goods</u></th>
<tr ><th colspan="4"> Enter your details below and wait minimum for half an hour.</th></tr>
<tr>
<td> Product Image : </td><td> <input type=file name="image" accept = "image/*" accept=".png/*" value="image"> </td>
</tr>
<tr>
<td> </td> <td> <input type=Submit > <input type=Reset> </td>
</tr>
</table>
</form>
</body>
</html>
i am getting an error 'bytes' object has no attribute 'image' Exception occured in pyhton code.
#python code -->#
#!C:\Users\Pc\AppData\Local\Programs\Python\Python38-32\python.exe
print('Content-type:text/html\n\r')
import cgi
import sys
from myconnect import *
message=0
try:
con,cur=myconnect()
form= cgi.FieldStorage()
# Get here.
fileitem=form.getvalue('image');
#fileitem = form['image']
# Test if the file was uploaded
if fileitem.image:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.image)
open('/uploads/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
query=f"select product_delivery_id from tbl_product_deliver order by product_delivery_id desc"
cur.execute(query)
pid=cur.fetchone()
update=f"UPDATE `tbl_product_deliver` SET `product_image`='{fn}' WHERE `product_delivery_id`='{pid}'"
cur.execute(update)
con.commit()
else:
message = 'No file was uploaded'
except Exception as e:
print(e)
print("Exception occured")
You cannot use a python script like php. Typically you have to configure an eventhandler waiting for a post-request. For doing this in python you need a framework like flask or bottle for receiving post request and instead of productimg.py you use the route you've set with this framework as action in html.
Your FieldStorage object is called without arguments, so you create an empty Fieldstorge object with no data.
A FieldStorage object receiving a post request looks like this:
fs= FieldStorage(fp=request.body, headers=request.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':request.headers['Content-Type'], })
However ensure you solved issue 1 before doing issue 2.
With bottle use this python code:
from bottle import post, request, run
#post('/upload')
def getImage():
#printing the raw data
print(request.body)
#insert your code here
run(host='localhost', port=8080)
and change in html:
action="http://localhost:8080/upload
Good luck
I have 2 scripts. One is my main.py script where it will call my other script to print an HTML page. The second script is html_pages.py. I'm trying to print an HTML page by importing html_pages.py and calling the welcome_page or login_page function.
Whenever I try to reach the page it says "Internal error". This was working previously when I had the login_page and welcome_page as a string stored in the main script. But it doesn't work when I try to call the function from a different script.
my main.py script contains:
#!/usr/bin/python3
import html_pages
if "HTTP_COOKIE" in os.environ :
cookie_info = os.environ["HTTP_COOKIE"]
cookies = cookie_info.split(';')
for cookie in cookies:
cookie_split = cookie.split('=')
cookie_dict[cookie_split[0].strip()] = cookie_split[1].strip()
CookieUsername = cookie_dict.get('username')
CookiePassword = cookie_dict.get('password')
CookieToken = cookie_dict.get('CSRFtoken')
#Connect to the database
import pymysql
conn = pymysql.connect(db='project2', user='algarcia1', passwd='root', host='localhost')
c = conn.cursor()
#Collect info about the user
query = "SELECT * FROM bank WHERE username='{CookieUsername}'"
c.execute(query.format(CookieUsername=CookieUsername))
conn.commit()
user = c.fetchone()
print(html_pages.welcome_page(user[0],user[3],user[4]))
else:
cookie_dict["username"] = "undefined"
cookie_dict["password"] = "undefined"
print(html_pages.login_page())
My HTML_pages.py script looks like this:
#!/usr/bin/python3
#Create a login HTML page
def login_page(status):
loginpage = """Content-Type: text/html
<!DOCTYPE html>
<!-- HTML code to send a POST request to login.py -->
<html>
<head>
<title>Safe Bank Website</title>
</head>
<body>
<form action="login.py" method="POST">
<h1>Safe Bank Website</h1>
<strong>Username:</strong><br>
<input type="text" name="username"><br>
<strong>Password:</strong><br>
<input type="text" name="password"><br>
<strong>CSRF token:</strong><br>
<input type="text" name="CSRFtoken"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>"""
print(login_page.format())
def welcome_page(username, chequings, savings):
#Create a welcome HTML page
welcomepage = """Content-Type: text/html
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {{ border: 2px solid black; text-align: left;}}
th, td {{ padding: 5px; }}
</style>
</head>
<body>
<h2>Welcome {cookie_info}!</h2>
<table style="width:100%">
<tr>
<th>Chequings</th>
<th>Savings</th>
</tr>
<tr>
<td>{chequings}</td>
<td>{savings}</td>
</tr>
</table>
Transfer money
</body>
</html>"""
print(welcome_page.format(cookie_info=username,chequings=chequings,savings=savings))
There are so many good python Web-Frameworks like Flask or Django. That make it easy so build webpages in a secure way. Especially Flask is very easy to use. Try them out and look how such frameworks do it.
In most cases it's more solid for future use to use a framework where you have a good structure.
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:
My HTML code:
<html>
<head>
<title>INFORMATION</title>
</head>
<body>
<form action = "/cgi-bin/test.py" method = "post">
FirstName:
<input type = "text" name = "firstname" /><br>
LastName:
<input type = "text" name = "lastname" /><br>
<input type = "submit" name = "submit "value = "SUBMIT">
<input type = "reset" name = "reset" value = "RESET">
</form>
</body>
My PYTHON CODE (test.py) which is in cgi-bin directory:
#!usr/bin/python
form = web.input()
print form.firstname
print form.lastname
what should i do to store html data in some file ??
Just write it to a file!
#!usr/bin/python
import cgi
form = cgi.FieldStorage()
with open ('fileToWrite.txt','w') as fileOutput:
fileOutput.write(form.getValue('firstname'))
fileOutput.write(form.getValue'(lastname'))
Oh, and you need to have write permission into the file. So for example if you are running apache, sudo chown www-data:www-data fileToWrite.txt should do it.
with open('/path/to/form.txt','w') as out_fh:
out_fh.write(form.firstname)
out_fh.write(form.lastname
The webserver will need to have write permission to the directory you want to create the file in.
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