I've been stumbling along with the same problem for almost a year now. I always find a way to work around it, but I'm tired of finding work arounds.
What I need is to create a button on a Web Page (preferable HTML, not PHP or ASP) that runs a python script on the server. I'd also like the ability to have this button send information from a form to the script.
I need to do this on a local host and through a web service hosted on the Amazon Cloud. I won't be able to install anything extra on the Amazon Cloud service, such as PHP or CGI.
I'd really like an easy solution, I'm an expert with python and I can write webpages that whistle, but I just can't find a simple solution to this problem.
My ideal solution would be something like the mail to tag:
Send Mail
Except:
Run Script
Now I highly doubt a solution like that exists, but well I can dream right.
The script I am trying to run:
Returns a Unique ID from the user
Sends the ID to a GIS program that creates a map based on the ID (the ID selects the area of the map)
The map is then exported to a PNG, wrote into an HTML document and then displayed for the user in a new tab.
EDIT ---------------------------
Thanks to #Ketouem answer I was able to find a great solution to my issue. I'll post some of the code here so that others can benefit. Make sure you download the Bottle Module for python, its great.
# 01 - Import System Modules
from bottle import get, post, request, Bottle, run, template
# 02 - Script Variables
app = Bottle()
# 03 - Build Temporary Webpage
#app.route('/SLR')
def login_form():
return '''<form method="POST" action="/SLR">
Parcel Fabric ID: <input name="UID" type="text" /><br />
Save Location: <input name="SaveLocation" type="text" value="D:/Python27/BottleTest/SLR_TestOutputs"/><br />
Air Photo On: <input name="AirPhoto" type="checkbox"/><br />
Open on Completion: <input name="Open" type="checkbox"/><br />
Scale: <input name="Scale" type="text" value="10000"/><br />
<input type="submit" />
</form>'''
# 04 - Return to GIS App
#app.route('/SLR', method='POST')
def PHPH_SLR_Script():
# I won't bother adding the GIS Section of the code, but at this point it send the variables to a program that makes a map. This map then saves as an XML and opens up in a new tab.
# 04 - Create and Run Page
run(app, host='localhost', port=8080)
You could use Bottle : http://bottlepy.org/docs/dev/index.html which is a light web framework
Related
I am trying to display the image on my local machine. I only use the website from my own machine. I am not expecting visit from outside. I found a solution here: Get Flask to show image not located in the static directory, But it doesn't work for me. I have tried:
relative path, abs path. None of them works. Where I did it wrong?
QUESTION:
for test purpose, my file system is like this:
C:/jackson/Python34_workspace/Python34_Projects/Learn-Bottle/app05_rend_local_img/
picuture_gallery/Desert.jpg
views/index.tpl
main.py
python script is this
#bottle.route("/")
def index():
return bottle.template("index.tpl")
#bottle.post('/result')
def result():
return bottle.template("index.tpl")
And this is my template.
<form action="/result" method="POST">
<br>
<input type="submit" value="Submit">
<br>
</form>
<div>
<img src="file:///C:/HSH/Python34_workspace/Python34_Projects/Learn-Bottle/app05_rend_local_img/picture_gallery/Desert.jpg">
</div>
--- Some comment ---
I have tried
src="file:///picuture_gallery/Desert.jpg"
after I clicked submit, it doesn't display. But if I drag it to the browser, it works. How could that be?
An URL using the file procotol is never requested from the server. The client (browser) always looks for it on the local system.
So it doesn't matter how you configure your Bottle application, the browser will not ask it for such an URL.
If you want the Botte application to deliver static files, do something like this:
from bottle import static_file
#route('/static/<filename>')
def server_static(filename):
return static_file(filename, root='/path/to/your/static/files')
What is the simplest way to display the Python ystockquote (http://goldb.org/ystockquote.html) module output in HTML? I am creating an HTML dashboard which will be run locally on my computer and want to insert the stock output results into the designated HTML placeholders. I am hoping that because it is local I can avoid many CGI and server requirements.
I would use a templating system (see the Python wiki article). jinja is a good choice if you don't have any particular preferences. This would allow you to write HTML augmented with expansion of variables, control flow, etc. which greatly simplifies producing HTML automatically.
You can simply write the rendered HTML to a file and open it in a browser, which should prevent you from needing a webserver (though running python -m SimpleHTTPServer in the directory containing the HTML docs will make them available under http://localhost:8000)
Here is a simple server built using web.py (I have been playing with this for a while now, so this was a fun question to answer)
import web
import ystockquote
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def POST(self):
history = ystockquote.get_historical_prices(web.input()['stock'], web.input()['start'], web.input()['end'])
head = history[0]
html = '<html><head><link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"><body><table class="table table-striped table-bordered table-hover"><thead><tr><th>{}<th>{}<th>{}<th>{}<th>{}<th>{}<th>{}<tbody>'.format(*head)
for row in history[1:]:
html += "<tr><td>{}<td>{}<td>{}<td>{}<td>{}<td>{}<td>{}".format(*row)
return html
def GET(self):
return """<html>
<head><link href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css' rel='stylesheet'>
<body>
<form method='POST' action='/'><fieldset>
Symbol <input type='input' name='stock' value='GOOG'/><br/>
From <input type='input' name='start' value='20130101'/><br/>
To <input type='input' name='end' value='20130506'/><br/>
<input type='submit' class='btn'/></fieldset></form>"""
if __name__ == "__main__":
app.run()
I'm trying to use Python and HTML together. What I'm trying to do is create an HTML Form that will submit data to a python file and that python file will then handle the data. But I'm not getting it to work.
Here is my python code:
form = cgi.FieldStorage() # instantiate only once!
name = form['Sample Name'].value
and this is my HTML code:
<form method='POST' action='/functionGen.py'>
Name: <input type='text' name='Sample Name'>
<input type='submit' value='Begin Storing'>
</form>
What ends up happening is I just see my python code in the browser, the file doesn't begin handling the data.
What can I do?
You should know, that you are getting plain python source document via http protocol now. If you want to use CGI mechanism, you should place youre .py in cgi-enabled directory. It means that you need http server.
related questions
How to run Python CGI script
How do I set up a Python CGI server?
form.html:
<form action="p.py" method="post">
<input type="text" id="id_text" name="name_text" />
<input type="submit" id="id_submit" name="name_submit" />
</form>
p.py:
#!/usr/bin/python
#what to write here...
Both files are put in /var/www/ , now from http://example.com/form.html, if I click the submit button would I execute the p.py and how can I get the value of textbox?
It's apache/httpd webserver installed on computer.
1st, to make p.py run by apache, you need to check:
1, config apache site for a python script, you may choose: cgi/fastcgi
such as: ScriptAlias /cgi-bin/ /usr/local/xxxxxx/cgi-bin/
2, make sure your p.py file is runable, modify by chown/chmod
2nd, to get the value from a form, you need to understand cgi knowleges and get data from environment,
or much easier by using cgi module:
import cgi
form = cgi.FieldStorage()
v = form.getvalue('id_text','')
print """Content-type: text/html
<html>
<body> submit value:%s </body>
</html>""" % (v)
at last, I suggest:
put runable scripts to a separated dir, away from /var/www/
using a web framework for web develop. It's too deep to use cgi level technology in 2012.
I want user to enter a sentence then I break up that sentence into a list. I got the html page down but i have trouble passing that sentence to python.
How do I properly send the user input to be processed by python and output it to a new page?
There are many Python web frameworks. For example, to break up a sentence using bottle:
break-sentence.py:
#!/usr/bin/env python
from bottle import request, route, run, view
#route('/', method=['GET', 'POST'])
#view('form_template')
def index():
return dict(parts=request.forms.sentence.split(), # split on whitespace
show_form=request.method=='GET') # show form for get requests
run(host='localhost', port=8080)
And the template file form_template.tpl that is used both to show the form and the sentence parts after processing in Python (see index() function above):
<!DOCTYPE html>
<title>Break up sentence</title>
%if show_form:
<form action="/" method="post">
<label for="sentence">Input a sentence to break up</label>
<input type="text" name="sentence" />
</form>
%else:
Sentence parts:<ol>
%for part in parts:
<li> {{ part }}
%end
</ol>
%end
request.forms.sentence is used in Python to access user input from <input name="sentence"/> field.
To try it you could just download bottle.py and run:
$ python break-sentence.py
Bottle server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
Now you can visit http://localhost:8080/.
Have you tried Google? This page sums up the possibilities, and is one of the first results when googling 'python html'.
As far as I know, the two easiest options for your problem are the following.
1) CGI scripting. You write a python script and configure it as a CGI-script (in case of most HTTP-servers by putting it in the cgi-bin/ folder). Next, you point to this file as the action-attribute of the form-tag in your HTML-file. The python-script will have access to all post-variables (and more), thus being able to process the input and write it as a HTML-file. Have a look at this page for a more extensive description. Googling for tutorials will give you easier step-by-step guides, such as this one.
2) Use Django. This is rather suited for larger projects, but giving it a try on this level may provide you certain insights, and wetting your appetite for future work ;)