Display Python output in HTML - python

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()

Related

Methods on linking a HTML Tornado server and Python file

This is my sample HTML file
<html>
<head>
<title>
</title>
</head>
<body>
<form action="">
Value a:<br>
<input type="text" name="Va">
<br>
Value b:<br>
<input type="text" name="Vb">
<br><br>
<input type="submit">
</form>
<textarea rows="4" cols="10">
</textarea>
<p>
</p>
</body>
</html>
And a given template Tornado server code:(I also need help on the explanation of each section of the following code)
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.gen
import tornado.options
tornado.options.parse_command_line()
class APIHandler(tornado.web.RequestHandler):
#tornado.web.asynchronous
def get(self):
self.render('template.html')
#tornado.gen.engine
def post(self):
try:
num = int(self.get_argument('num'))
except:
num = 5
self.render('template.html')
app = tornado.web.Application([(r"/next_rec",APIHandler),])
if __name__ == "__main__":
server = tornado.httpserver.HTTPServer(app)
server.bind(48763)
server.start(5)
tornado.ioloop.IOLoop.current().start()
and finally my python code:
if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
print a+b
I am using a simple 'a+b' function to test out this feature. But my problem is I can't figure out a way to link them together. So my ultimate goal is to click on the "Submit" button on the HTML, pass on two values to the Tornado server, use it as input in my python script and finally show the output in the text area of the HTML or on another page. I'm know there are tons of information on the web, but I'm completely new to Tornado (near 0 knowledge) and most of them I can't really understand. Help on methods or keywords for search is much appreciated, thank you very much. (please keep answers as basic as possible, it will help a lot, thanks!)
First of all you should check the official documentation. It is quite simple and it targets the newcomers.
Also in this short guide, the sections of a similar code as your is being explained with simplicity.
Now for your code:
On your template you need to specify that the form should send a post request on submit by adding <form method="post" id="sum_form">
Also you need to make sure that you will be submit the data added in the form on an event: $("#sum_form").submit();
On your post method you need to read the passed numbers from your client's form, add them and then send them back to the template as a parameter.
For example:
def post(self):
numA = int(self.get_argument('Va'))
numB = int(self.get_argument('VB'))
sumAB = numA + numB
self.render('template.html',sumAB=sumAB)
In you template.html you need to add a field where you will display the passed sum as a jinja variable : {{sumAB}}

How to insert data to HTML page with Python?

I have some data and I would like to write it into an HTML page.
In PHP in would be possible just to write
<?php .... take the data and print it ?>
How can it be done with Python?
Should I generate the WHOLE page with Python or can I just extract this data and place it in the needed place in the HTML page?
This should be accessed from a web server when someone requests a URL.
If you use a framework like Flask or Django, you can use templates to render data into HTML without having to print out the entire HTML from Python (actually, it does that behind-the-scenes, but you only have to write your template once).
Flask uses a templating language called Jinja2, which lets you write templates like this:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
Hello, {{ name }}.
</body>
</html>
and render them out like this:
#app.route('/index')
def index():
title = "My Page"
name = "Foo"
return render_template('mytemplate', title=title, name=name)
Django has a similar function with its inbuilt templating system.
If you are running on a cheap webhost, you might not have the flexibility for running a full-blown web framework like Django or Flask (which have a lot of dependencies and should be run in a WSGI server). On my webhost, Siteground, I use a microframework called Bottle.py, which is similar to Flask but has only a single-file dependency so it can run wherever Python is running, using CGI. I have it set up as detailed in this post, by running it as CGI—app.run(server='cgi')—and use .htaccess rules with mod_rewrite to remove the app.py from the URL.
Documentation: https://pypi.python.org/pypi/html/
Do like this:
print("Content-type: text/html\n")
print("""<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Обработка данных форм</title>
</head>
<body>""")
print("<h1>Обработка данных форм!</h1>")
print("<p>TEXT_1: {}</p>".format(text1))
print("<p>TEXT_2: {}</p>".format(text2))
print("""</body>
</html>""")
You can push the data to mysql and fetch that using php code.
python code for pushing to mysql
php code for fetching from mysql

Bottle Display Image using File://

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')

Handle HTML Form Data with Python?

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?

how do i print outputs to html page using python?

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 ;)

Categories

Resources