how to store html form data into file - python

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.

Related

How should I put python inputs when I create html file in python?

from email import message
def main(): # Creates a main function to initiate the program
global name, info
name = input("Enter your name: ") # Makes inputs that requires an user to enter info
info = input("Describe yourself: ")
main() # The program starts here
f = open('test3.html','w')
message = """<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""
f.write(message)
f.close()
Hello, I am creating a py file that accepts the user's inputs (which are {name} and {info} in my code) and creates a .html file. I tried to use + name + or + info + but both not worked. Are there any other ways that I can use to make it work correctly? Thank you so much for reading my question
Use an f string
from email import message
def main(): # Creates a main function to initiate the program
global name, info
name = input("Enter your name: ") # Makes inputs that requires an user to enter info
info = input("Describe yourself: ")
main() # The program starts here
f = open('test3.html','w')
# add 'f' before the first quotation mark
message = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""
f.write(message)
f.close()
You probably also want to refactor your code to look like this:
from email import message
def main(): # Creates a main function to initiate the program
name = input("Enter your name: ") # Makes inputs that requires an user to enter info
info = input("Describe yourself: ")
with open('test3.html', 'w') as f:
body = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""
f.write(body)
if __name__ == "__main__":
main()
In the original, you imported message, but then overrode that import by assigning a variable with that same name, so this new version fixes that (though message is now an unused import, unless this isn't the entire code file)

How do I retrieve the server address via a button

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 ?

Python: getting address of file in bottlepy

How can I get address of file in bottlepy?
I tried it, but it returns %s.shp
#get('/upload')
def upload_form():
return '''
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="filer" /><br />
<input type="submit" />
</form>
'''
#post('/upload')
def upload_submit():
file_csv = request.get("filer") # I want to get file address (string)
map = inflation_map.InflationMap(file_csv)
map.draw_image()
return file_csv
When you do :
request.get("filer")
you will just get the name of the file. You need to save it on to the file system by specifying a path.
It is documented here : http://bottlepy.org/docs/dev/tutorial.html#file-uploads

Problems of GET and POST methods in Python

File name mypage.py
Python code
form = cgi.FieldStorage()
name = form.getfirst('name', 'empty')
id = form.getfirst('id', 'empty')
print """\
Content-Type: text/html\n
<html>
<body>
<p>Name: "%s"</p>
<p>ID: "%s"</p>
</body>
</html>
""" % (name, id)
HTML inside the same file
<form name="frm" method="post" action="mypage.py?id=33">
<input type="text" name="name" value="MyName" />
<input type="Submit" id="btn" value="Send" />
After submitting the form (pressing Send button), I can see this URL with following output
localhost:8000/cgi-bin/mypage.py?id=33
Name: "empty"
ID: "33"
if I change the form method POST to GET
<form name="frm" method="get" action="mypage.py?id=33">
then I can see this URL with following output
localhost:8000/cgi-bin/mypage.py?name=MyName
Name: "MyName"
ID: "empty"
I don't understand why I am not receiving text field value with POST method ? And why I am unable to receive id value in query string with GET method ?
Its simple python page without any framework. BTW I am using "python-bugzilla 0.8.0" downloaded from here but i think my given code is just a simple page and has nothing to do with this package.
Any help would be appreciated.
Thanks in advance,
Your GET is proper:
<form name="frm" method="get" action="mypage.py?id=33">
But your POST is not:
<form name="frm" method="post" action="mypage.py?id=33">
You can't add a GET style variable (?id=33) to the action of your POST. It should be:
<form name="frm" method="post" action="mypage.py">
<input type="hidden" name="id" value="33">
See HTTP Methods: GET vs. POST: "Query strings (name/value pairs) are sent in the URL of a GET request" and "Query strings (name/value pairs) are sent in the HTTP message body of a POST request".
Not adhering to these rules would cause unexpected results such as you are seeing.
Technically, a POST target url should not have GET parameters, so the ?id=33 in the target is invalid. I'm also guessing that it's confusing to the FieldStorage module, that might be why you are getting unexpected results.
You should properly use POST and GET per my other answer. That said, I'm worried about your use of form.getfirst and variable names.
Per the documentation:
FieldStorage.getfirst(name[, default]) - This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name.
You've named your name variable name which is a silly name. See, lots of names. And your form has a name. And it's a field. Same with ID. You should change your variable names as such:
<form name="MyForm" method="post" action="mypage.py">
<input type="text" name="FullName" value="MyName" />
<input type="text" name="FormID" value="33" />
<input type="Submit" id="btn" value="Send" />
and change your Python as follows:
form = cgi.FieldStorage()
FullName = form.getfirst('FullName', 'empty')
FormID = form.getfirst('FormID', 'empty')
print """\
Content-Type: text/html\n
<html>
<body>
<p>Name: "%s"</p>
<p>ID: "%s"</p>
</body>
</html>
""" % (FullName, FormID)
That's the code for a proper POST and printing of the variables. Does it work?
Thanks for the help.
problem was here.
form = cgi.FieldStorage()
As I've mentioned in comments of your answers that I've printed "form" and here is output: "FieldStorage(None, None, [])".
So, if FieldStorage doesn't have any value then it doesn't matter which function is being used to get the form value. But it was really good information and practical as well.
previously form = cgi.FieldStorage() was declared inside another function which was wrong, that's why FieldStorage was empty.
Here is WRONG code.
def myfunction ():
cgitb.enable()
form = cgi.FieldStorage()
Solution 1:
form = cgi.FieldStorage() shall define inside the run() function and pass this form as parameter of other function to get values of form.
i.e.
def run():
cgitb.enable()
form = cgi.FieldStorage()
myfunction(form)
Now its working
def myfunction (form):
name = form.getfirst('name', 'empty')
id = form.getfirst('id', 'empty')
Solution 2:
form = cgi.FieldStorage() shall define directly inside the main function then don't need to pass it as parameter .
i.e.
if __name__ == "__main__":
cgitb.enable()
form = cgi.FieldStorage()
Now its working too and form is accessible inside the myfunction.
def myfunction ():
name = form.getfirst('name', 'empty')
id = form.getfirst('id', 'empty')
Thanks everybody.

Python webpage login error

I am trying to create create a kind of webserver withy python and cherrypy.
I wish to put the htmls into separate files and embedd them into my python script. The code i used to do that is.
#cherrypy.expose
def welcome(self, loginAttempt = None):
""" Prompt the user with a login form. The form will be submitted to /signin
as a POST request, with arguments "username", "password" and "signin"
Dispaly a login error above the form if there has been one attempted login already.
"""
#Debugging Process Check
print "welcome method called with loggedIn = %s" % (loginAttempt)
if loginAttempt == '1':
""" If the user has attempted to login once, return the original login page
with a error message"""
page = get_file("loginPageE.html")
return page
else:
page = """
<form action='/signin' method='post'>
Username: <input type='text' name='username' /> <br />
Password: <input type='password' name='password' />
<input type='submit' name='signin' value='Sign In'/>
</form>
"""
return page
where loginPageE.html is
<html>
<head>
<title>Failed Login Page</title>
</head>
<body>
<!-- header-wrap -->
<div id="header-wrap">
<header>
<hgroup>
<h1>Acebook</h1>
<h3>Not Just Another Social Networking Site</h3>
</hgroup>
<ul>
<form action='/signin' method='post'>
Username: <input type='text' name='username' />
Password: <input type='password' name='password' />
<input type='submit' name='signin' value='Sign In'/>
</form>
</ul>
</header>
</div>
</body>
</html>
However I keep on getting an error message that reads
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 74, in welcome
page = get_file("loginPageE.html")
NameError: global name 'get_file' is not defined
I was wondering if anyone could please help?
Thanks in advance
Well, from the error, evidently python doesn't know what the get_file() function is. Are you sure that at that point of time where you invoke this function inside the welcome() function, get_file() has been defined?
get_file isn't one of the standard Python functions, so it must be a custom one you used to have. You can create a simple function to read a file and return its contents as a string like this:
def get_file(path):
f = open(path, 'r')
output = f.read()
f.close()
return output
You can read up on Python file management at http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
def get_file(path):
with open(path, 'r') as f:
return f.read()
However, consider using a proper template engine. Jinja2 is really good and it allows you to use conditionals etc. in templates - something you'll certainly want at some point. Besides that, it does nice things such as variable autoescaping for you if you ask it to.

Categories

Resources