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 ;)
Related
I wonder if someone can help me. I'm trying to do something like the following to get input events from a HTML text box and send them to a python function.
textarea = cgi.FieldStorage()
chars = textarea.getvalue('1')
def MyPythonFunction():
'Do something with chars'
print(<textarea oninput=MyPythonFunction() </textarea>)
I've tried all kinds of things but can't get it to work.
Thanks in advance
First, the oninput keyword of the textarea HTML tag expects JavaScript code and would interpret mypythonfunction to be a JavaScript function. You need to output an HTML form that contains a SUBMIT tag such that when the form is submitted it invokes your server-side script: the form might look like:
<form name="f" action="my_script.py" method="post">
<textarea name="chars"></textarea>
<br>
<input type="submit" name="submit" value="Submit">
</form>
Your server side script, my_script.py, which must be executable, might look like:
#!/usr/bin/env python
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
chars = form.getvalue('chars')
If you really wanted to process input a character at a time, then you would remove the SUBMIT HTML tag, put back the oninput keyword. But then you would have to specify a JavaScript function that would get invoked whenever the contents of the textarea changed. This function would have to use a technique called AJAX to invoke your server-side Python script passing the contents of the TEXTAREA as an argument. This is a rather advanced topic, but you can investigate this.
I would like to use some HTML messages in the turbogears abort function.
Although the name does not match exactly (I use the 'tg.abort' function), this is the abort definition I found :
abort
The code used currently :
from tg import abort
message="The following {} occured, this is due to {}, please visit this url : {}".format(error, reason, url)
abort(status_code=502, detail=message)
I would like to have something like this :
from tg import abort
message="""The following error occured : {}</br>
The most probable reason would be {} </br>
Your solution might be found here
""".format(error, reason, url)
abort(status_code=502, detail=message)
I think the content is automatically escaped.
The Html page generated from the abort function, endering something like this :
<html>
<head>
<title>502 Bad Gateway</title>
</head>
<body>
<h1>502 Bad Gateway</h1>
Bad gateway.<br /><br />
The following error occured : hungry<br/>
The most probable reason would be : maybe you should eat </br>
<a href="http://dummyurl">Your solution might be found here</a>
</body>
</html>
If you have any idea of how to insert html code without escaping, I would be very interested.
Also I really am focused on the abort method here, I am aware that I could use some dedicated page that would use a templating framework (like the rest of the website).
Thank you very much.
Regards
The error message is actually exposed by the controllers/error.py code in your application. So if you want to expose the message from abort details you should fetch it and return it in the ErrorController.
This is now done by default on newly quickstarted projects ( see https://github.com/TurboGears/tg2devtools/blob/master/devtools/templates/turbogears/%2Bpackage%2B/controllers/error.py_tmpl#L27 ) but it was not done on old versions.
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'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
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?