Having trouble executing a python script from the web browser - python

I'm new to HTML and looking to integrate a python script which runs after i retrieve values from a HTML page.
I'm trying to run a sample script which takes two values (name and number) and returns a list of unique codes.
This is my python script (forms.cgi).
#!C:\Python34\Python.exe
import CampaignID, cgi
print ("Content-Type: text/html\n\n")
form = cgi.FieldStorage()
name = form.getvalue('Name')
number = form.getvalue('Number')
codes = CampaignID.CodeGen(name,number)
print(codes)
This is my below HTML script
<html>
<head>
<title>Campaign generation</title>
</head>
<body>
<form name = 'Campaign' action = 'forms.cgi' method = 'get'>
<fieldset>
<legend> Enter your restaurant Name </legend>
<label>Name <input type = 'text' name ='Name' size = '30'></label>
<br/>
<legend> No. of Coupons </legend>
<label>Number <input type = 'text' name ='Number' size = '4'></label>
<br/>
<hr/>
<input type = 'submit' value = 'submit review'/>
</fieldset>
</form>
After filling in the values , i am getting the python file source code on the page. I'm running apache (XAMPP)
Please let me know where im going wrong.
KJ

Your action attribute is pointing to a local file on disk. It needs to be pointing to a URL served by Apache.

Related

How to run python function once user inputs into form field

I am an html page with a form to enter your email:
<!DOCTYPE html>
<html>
<body>
<h1>The form novalidate attribute</h1>
<p>The novalidate attribute specifies that the form data should not be validated when submitted.</p>
<form action="/action_page.php" novalidate>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
<p><strong>Note:</strong> The novalidate attribute of the form tag is not supported in Safari 10 (or earlier).</p>
</body>
</html>
Is there a way to run a python script when the user enters his email address and then takes the input and runs it through this def function:
def send_email():
email_address=form_input
print(email_address)
So basically, when a user enters an email in the form, it takes the value and runs it through the send email function. I am new to using python with html so the syntax is confusing me. Any ideas or suggestions as to how to but it in the html file?
No, it is not possible to do it just in html.
If you use .php as backend script, read this php form handling
If you want to use python as backend script, you need to use ajax, e.g. ajax intro. In this case, need to run web server that take ajax request and respond the request

Pass HTML input to python script

I have a Python script and I want to create a very simple HTML form with 3 fields (username, password and an ID) and a submit button.
When I click Submit I just want to pass these three parameters into my Python script and run the script.
I tried to do it using CGI. I created a cgi-bin folder and added my test.py file in there. The Python code is the following:
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
username = form.getvalue('username')
password = form.getvalue('password')
room_id = form.getvalue('room_id')
#More code here...
Then I created an index.html file:
<!DOCTYPE html>
<html>
<body>
<form name="search" action="/[path to file]/test.py" method="get">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
Room ID: <input type="text" name="room_id"> <br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Finally, I added a server.py file:
import CGIHTTPServer
CGIHTTPServer.test()
I run the server.py file and go to 0.0.0.0:8000. I gave the input but when I click Submit the python code is printed in the form and it is not executed.
I am looking for the simplest and fastest way to make this HTML form execute the script. It is only for test purposes and I do not want to spend time creating a complex web application.
Is CGI a good idea? If yes, what am I doing wrong?

Getting value from an input in html using python

So, I'm making a program in python that is executed when the user gives values in an input in HTML. Everything runs OK.
from bs4 import BeautifulSoup # parsing
r = open("C:/Python27/Pruebas/pruebahtml.html")
soup = BeautifulSoup(r,"html.parser")
R4sem = soup.find("input",attrs={'id':'R4sem'})["value"]
R5sem = soup.find("input",attrs={'id':'R5sem'})["value"]
r.close()
txt = open('C:/Python27/Pruebas/Pruebaconfigfechas.txt','w')
Encabezado = """Due-Date-Function "DD_General"
Type PiecewiseConstant
Multiplier 1
Calculation-Policy Time-Relative
DueDate-Policy FODuedateToBucketEndTime
Attribute "FechaTope" \n"""
fechar4 = "\nDATE -4 weeks Score "
fechar5 = "\nDATE -5 weeks Score "
txt.write(Encabezado+fechar4+R4sem+fechar5+R5sem)
txt.close()
But when checking the new text file, R4sem and R5sem are empty. So my question is, I can't read the values that the inputs have or there's another way to do this. The users are gonna be usin the HTML constantly so the values are gonna be changing, so I thought that using inputs would be the best solution.
If needed I can put also the HTML code I have.
EDIT: Here's the HTML code.
<!DOCTYPE html>
<html>
<head>
<title>*AJAW*</title>
</head>
<body>
<p>Penalidadeshtml v0.1.3</p>
<div>
<form action="file:///C:/Python27/Pruebas/dist/lectura.exe">
Retraso 4 sem: <input type="text" name="R4sem" id="R4sem" value=""><br>
Retraso 5 sem: <input type="text" name="R5sem" id="R5sem" value=""><br>
<br>
<input type="submit" value="Grabar">
</form>
</div>
</body>
</html>
Well, I solved this by creating the text file I needed in the HTML, so it was easier to send the values the user put and have the document I was asked to deliver.
Thanks for the comments.

Sending data to server flask html

I am trying to create a simple checkbox that sends the data to server here is my html code.
<form action="." method="POST">
<div class="checksheet">
<input id="XML Parser" class="checkbox" type="checkbox"/>XML Parser
<input id="Feed Parser" class="checkbox" type="checkbox"/>Feed Parser
<input id="Text Parser" class="checkbox" type="checkbox"/>Text Parser
<input id="Case Normalization" class="checkbox" type="checkbox"/>Case Normalization
<input id="Stemmer" class="checkbox" type="checkbox"/> Stemmer
</div>
<div class="submit"><input type="submit" value="Send" name="raw_text"></div>
</form>
What I am trying to do is very similar to the question asked here: Send Data from a textbox into Flask?
But except with the text box.. I have checkboxes.
But I get this error:
Not Found
The requested URL was not found on the server.
If you entered the URL manually please check your spelling and try again.
MY server side code (in flask) is:
#app.route('/raw_text.html')
def home ():
file = "sample.xml"
contents = open(file).read()
contents = contents.decode('utf-8')
return render_template('raw_text.html', contents=contents,file=file)
#app.route('/raw_text.html',methods=['POST'])
def get_data():
print "REQUEST ",request.form()
data = request.form['raw_text']
print data
return "Processed"
Any suggestions.
Thanks
A few things:
Your checkbox elements need a name attribute, this is what is used when the data is sent to the back end. Each checkbox that is related to each other needs to have the same name.
Your action attribute needs to point to a URL. If you are posting it to the same page as the form, you can remove the attribute.
ID's cannot contain spaces.
To be accessible the check boxes need <label>s,

Displaying results from search API

I'm trying to get to grips with web2py/python. I want to get the user to fill in a search form, the term they search for is sent to my python script which should send the query to the blekko API and output the results to them in a new HTML page. I've implemented the following code but instead of my normal index page appearing, I'm getting the html response directly from blekko with '%(query)' /html appearing in it's search bar. Really need some help with this!
HTML form on the default/index.html page
<body>
<div id="MainArea">
<p align="center">MY SEARCH ENGINE</p>
<form name="form1" method="get" action="">
<label for="SearchBar"></label>
<div align="center">
<input name="SearchBar" type="text" id="SearchBar" value="" size = "100px"><br />
<input name="submit" type="submit" value="Search">
</div>
</form>
<p align="center"> </p>
Python code on the default.py controller
import urllib2
def index():
import urllib2
address = "http://www.blekko.com/?q='%(query)'+/html&auth=<mykey>"
query = request.vars.query
response = urllib2.urlopen(address)
html=response.read()
return html
I think you are misunderstanding how string formatting works. You need to put the address and query together still:
address = "http://www.blekko.com/?q='%(query)s'+/html&auth=<mykey>" % dict(query=request.vars.query)
Add a hidden field to your form, call it "submitted". Then reformat your controller function as such:
import urllib2
def index():
if request.vars.submitted:
address = "http://www.blekko.com/?q='%(query)'+/html&auth=<mykey>"
query = request.vars.query
response = urllib2.urlopen(address)
html=response.read()
return html
else:
return dict()
This will show your index page unless the form was submitted and the page received the "submitted" form variable.
The /html doesn't do anything. Glad your question got answered. There is python client code for the blekko search api here: https://github.com/sampsyo/python-blekko

Categories