I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks!
3 Answers
You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Note: Flask sits on top of Werkzeug and may need other libraries like sqlalchemy for DB work or jinja2 for templating.
1 Comment
Peter Hansen
It's worth noting that Flask is actually a layer over Werkzeug, which is not quite as tiny, though still small enough to be manageable. It does mean you have about 3-4 implicit dependencies though, not merely Flask. (As someone with similar goals to the OP, I don't consider this to be remotely a problem, compared to things like Turbogears2.)
You can use cgi...
#!/usr/bin/env python
import cgi
def myMethod(some_parameter):
// do stuff
return something
form = cgi.FieldStorage()
my_passed_in_param = form.getvalue("var_passed_in")
my_output = myMethod(my_passed_in_param)
print "Content-Type: text/html\n"
print my_output
This is just a very simple example. Also, your content-type may be json or plain text... just wanted to show an example.
4 Comments
Ned Batchelder
cgi is in the standard library. This is as standalone as you can get.shoold
does it require a web server like apache2 on the machine?
blockhead
Presumably you have a web server installed? How else are you displaying your webpage?
shoold
You don't need a full blown web server to display "Hello World!" in HTML. You could write a quick script in python and import the base http server and execute it on some port.
In addition to Flask, bottle is also simple and WSGI compliant:
from bottle import route, run
@route('/hello/:name')
def hello(name):
return 'Hello, %s' % name
run(host='localhost', port=8080)
# --> http://localhost:8080/hello/world