How to run a Python script in a web page - python

I'm very new to Python. I just know what Python is.
I have created the below code (in Python IDLE):
print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;
Then I saved this page in my localhost as index.py
I run the script using
http://localhost/index.py
But it does not show the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?

In order for your code to show, you need several things:
Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.
Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.
Setting this up can be quite the hassle, so be prepared.

As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python
print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Using the Flask library in Python, you can achieve that.
Remember to store your HTML page to a folder named "templates" inside where you are running your Python script.
So your folder would look like
templates (folder which would contain your HTML file)
your Python script
This is a small example of your Python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template("my-form.html") # This should be the name of your HTML file
#app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"
if __name__ == '__main__':
app.run()
This a small template of HTML file that is used:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>
This is a small little way through which you can achieve a simple task of comparing two strings and which can be easily changed to suit your requirements.

If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you
need to create an HTML file (I'm going to call it runpython.html). (Remember to move the Python file to htdocs as well.)
Add in this to your HTML body (and inputs as necessary).
<form action = "file_name.py" method = "POST">
<input type = "submit" value = "Run the Program!!!">
</form>
Now, in the Python file, we are basically going to be printing out HTML code.
# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.
import cgitb
import cgi
cgitb.enable() # This will show any errors on your webpage
inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']
print "Content-type: text/html" # We are using HTML, so we need to tell the server
print # Just do it because it is in the tutorial :P
print "<title> MyPythonWebpage </title>"
print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

Well, the OP didn't say server or client side, so I will just leave this here in case someone like me is looking for client side:
Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just simple JavaScript code.

With your current requirement, this would work:
def start_html():
return '<html>'
def end_html():
return '</html>'
def print_html(text):
text = str(text)
text = text.replace('\n', '<br>')
return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
webpage_data = start_html()
webpage_data += print_html("Hi Welcome to Python test page\n")
webpage_data += fd.write(print_html("Now it will show a calculation"))
webpage_data += print_html("30+2=")
webpage_data += print_html(30+2)
webpage_data += end_html()
with open('index.html', 'w') as fd: fd.write(webpage_data)
Open the index.html file, and you will see what you want.

Related

Calling a function on HTML page, not found

I am writing a tool to record and monitor downtime on a range of equipment.
I have my file structure as below:
File Structure
Sites is just a subfolder containing individual HTMLS for where the equipment is located.
Currently, flask runs webapp.py which contains:
>from . import app
>#app = (__init__.app)
>from . import views
>from . import ReportingTool
views.py has all of my #app.route's in it, up until the [site].html files. From there, on the [site].html file I ask for input from the user. I haven't started writing code to record the user input in any meaningful way, just want to get the data to a python script and commit them to variables. To this end, in the html file I have
<body>
<div class="menu">
<form method="post" enctype="multipart\form-data" action="{{ url_for('downTime') }}">
<fieldset class="datafieldset">
This then requests different data from the user in the form of multiple field sets as seen here: fieldsets
as you see in the code snippet above I set the action to be url_for('downTime'), downTime is a function in my python file ReportingTool.py. this throws out an error, "werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'downTime'. Did you mean 'supportguide' instead?" traceback
Is there something I need to add or specify on the html document to enable this page (and the other [site].html pages to call functions from the ReportingTool.py file? the #app.route that calls the [site].html file is this and that is called with a redirected from here I've only got it setup like that becuase I wanted the name for the site to appear in the address bar.
Thanks in advance.
I am not sure on steps to fix as I am kind of throwing myself in the deep end to learn basic coding by creating an application for my workplace to replace an excel spreadsheet I created.
You are not reaching the downTime function in the ReportingTool.py file. I suggest trying add_url_rule in your views.py by adding the /reported endpoint referencing the downTime function in ReportingTool.py. Something like this;
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
This answer is based on the responds for this question. You are trying to reach a function in a different file from your main view file. Assuming you are calling the page with the form from a function in the views.py file.
Solved with info from Kakedis' input, and the links they provided.
I added:
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
to webbapp.py, then:
#app.route('/reported')
def downTime():
try:
DTref = request.form['refDT']
except:
DTref = "No Reference"
print(DTref)
print("reported")
return(render_template("/UserRip.html"))
to ReportingTool.py
This now prints the above to console to confirm it's pulling the correct func and brings the user back to the starting page.

HTML form return displays python code instead of executing

Coming from only basic front end experience here and running into trouble using method="get" on my python script.
The entire python code is returned to the browser instead of just the print statement. I am using python SimpleHTTPServer and expect that I may be missing some configuration, but I am having quite a bit of trouble determining a solution.
Here is the HTML:
<form name="search" action="\cgi-bin/test.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>
Here is the Python (and also what gets returned to the browser when the form is submitted):
#!/usr/bin/env python3
import cgi
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
I know this is probably pretty basic, but I am stumped. I appreciate any guidance to be offered.
If you use Python 2 then you should use CGIHTTPServer instead of SimpleHTTPServer
python2 -m CGIHTTPServer
If you use Python 3 then you should use http.server --cgi
python3 -m http.server --cgi
And code has to be executable.
On Linux you do:
chmod +x cgi-bin/test.py
On Windows you have to assign extension .py to python. I don't use Windows to give more info.
Script has to send information what type of data it sends - text, HTML, image, PDF, Excel, etc. - and empty line which separates header and body.
print("Content-Type: text/html")
print() # empty line beetwin header and body
print(searchterm)
Without this information it may send it as file for downloading.
If you want to display text in console then you may have to use "standard error" because "standard output" and print() is send to browser
import sys
sys.stderr.write(searchterm + '\n')
#!/usr/bin/env python3
import cgi
import sys
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
# send text on console
sys.stderr.write('searchterm: ' + searchterm + '\n')
# send text to browser
#print("Content-Type: text/plain") # send all as text
print("Content-Type: text/html") # send all as HTML
print()
print(searchterm)

Bottle Displays Old Template?

I made a first draft of a template, called batch.tpl. I have updated it, however, the old template still displays. I have shut off the controller script and turned it back on multiple times. I have removed everything from the template except for the following:
cat views/batch.tpl
<HTML>
<HEAD>
<TITLE> Batch Manager </TITLE>
</HEAD>
<BODY>
THIS ISN'T DISPLAYING IN BROWSER
</BODY>
</HTML>
Yet that will not show, just the old template.
Here is my controller:
cat brew_bottle.py
from bottle import route, run, template, debug, post, request
import MySQLdb
import pymongo
from datetime import datetime, timedelta
import datetime
#route('/batch')
def batch():
con = MySQLdb.connect('localhost', 'root', 'pi', 'brew')
cursor = con.cursor()
batch_sql = "SELECT name, material, start_date, active, end_begin_date, end_end_date, min_temp, max_temp FROM batch WHERE active='Y'"
cursor.execute(batch_sql)
batches = cursor.fetchall()
return template('batch', batches=batches)
#...
debug(True)
run(host='0.0.0.0', port='8080', reloader=True)
However, when I go to http://<hostname>:8080/batch, I see the old template that I had wrote:
I am sure I am missing something easy. What is it?
I created a new directory and moved everything to it. Then when I start the python script, I am able to see the correct page. But the python script in the old directory displays the old template?
According to the Bottle docs, auto reloading (reloading) is only triggered by changes to module files.
Changes in template files will not trigger a reload. Please use debug
mode to deactivate template caching.
Turn on Bottle's debug mode this way:
bottle.debug(True)
Here is an incomplete list of things that change in debug mode:
The default error page shows a traceback. Templates are not cached.
Plugins are applied immediately. Just make sure not to use the debug
mode on a production server.
N.B., I see that someone already asked you whether restarting the server caused the updated template to appear, and that you indicated that it did not. That's highly suspicious. In any case, try fixing the problem above and see whether that solves your problem. Good luck!

Reading and writing files from html in Google App Engine

I am working with GAE and Python, I know python, but I don't know HTML, which seems to be what I need right now. I want to take in a text file write something in it then return it for download. I am using other people's examples, but far all I have is:
class MainPage(webapp.RequestHandler):
#http://bukhantsov.org/2011/12/python-google-app-engine-calculator/
def get(self):
self.response.out.write("""<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='file' name='file'/><br/>
</form>
</body>
</html>""")
I imagine there is something I need to put in the file line so I can access what the user feeds it, but I don't know what or how to access it from the python code. So what should I do here?
If I understand your question correctly, you are trying to grab the text data being sent by the user via the GET call that is defined by the form action HTML line.
Concisely, you are looking for this call:
file = self.request.get('file')
This may also be useful:
filename = self.request.GET['file'].filename
These can be used in the same location and in conjunction with your "self.response.out".
More information can be found here:
https://developers.google.com/appengine/docs/python/tools/webapp/requestclass#Request_get
Alternatively, the BlobStore APIs may be easier.
https://developers.google.com/appengine/docs/python/blobstore/overview
Possibly related:
Upload files in Google App Engine,
Get original filename google app engine
Hope that helps!
Jess

HTML forms not working with python

I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file and python file in the cgi-bin folder under Apache 2.2. If i just run a simple hello world python script in the browser, the "Hello World" message is being displayed. I'm using WinXP, Python 2.5, Apache 2.2. the code that i'm trying to run is the following:
#!c:\python25\python.exe
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Gold' and Pass == 'finger':
print '<big><big>Welcome'
print 'mr. Goldfinger !</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The answer to it might be very obvious, but its completely escaping me. I'm very new to Python so any help would be greatly appreciated.
Thanks.
This
i'm just getting the Python code
displayed in the browser
sounds like CGI handling with Apache and Python is not configured correctly.
You can narrow the test case by passing UserName and PassWord as GET parameters:
http://example.com/cgi-bin/my-script.py?UserName=Foo&PassWord=bar
What happens if you do this?
You may have to extract the field values like this
User = form.getfirst('UserName')
Pass = form.getfirst('PassWord')
I know, it's strange.

Categories

Resources