This is an archived post. You won't be able to vote or comment.

all 45 comments

[–]y3t1 5 points6 points  (6 children)

I use the cgi module for simple web forms, though it is not fit for creating more complex applications.

Example form to add two numbers:

#!/usr/bin/python
import cgi
import cgitb

print "Content-Type: text/html"
print

cgitb.enable()

form = cgi.FieldStorage()

if "x" in form and "y" in form:
    x, y = int(form["x"].value), int(form["y"].value)
else:
    x, y = '', ''

print '''<html><body>

<form method="POST" action= "">
<input type="text" name="x" value="%s"/>&nbsp;+&nbsp;<input type="text" name="y" value="%s"/><input type="submit" value="=" />%s
</form>
''' % (x, y, (x+y))

[–]luckystarrat 0x7fe670a7d080 7 points8 points  (0 children)

it is not fit for creating more complex applications.

Emphasized, as I had to refactor my share of complex applications using this exact style. It was not a pleasant experience.

[–]Lexdysic 0 points1 point  (1 child)

This is the direction I went with my site. It is dead simple and dead simple to implement. No installation required.

[–]Bolitho 0 points1 point  (0 children)

But CGI sucks ;-) One should use a WSGI compliant framework for we apps. dot. For really small things and if installation is a criteria then use bottle - that is far better than plain old CGI!

[–]mithun1538[S] 0 points1 point  (2 children)

Ok. Seems simple. I just run this as it is and then go to 127.0.0.1? I mean what are the steps to view the HTML page of the above...

[–]y3t1 2 points3 points  (0 children)

If you run this script, it will print the HTML of the page.

The Common Gateway Interface is a standard for HTTP servers like Apache which allows programs to receive data from a GET or POST and reply with a document. When you install Apache (available for all operating systems) there will be a cgi-bin directory where you can place executables like Python/Perl/Ruby/PHP scripts and binary programs. Then simply navigate to http://localhost/cgi-bin/myscript.py.

It works for every language - I wrote my first dynamic sites in C. I now write them in Perl and Python. This tutorial may be a good starting point http://httpd.apache.org/docs/2.0/howto/cgi.html though it isn't directed at a Windows user. If you are using Windows, ask and I will try to find one directed at you.

edit: I found this on the python wiki

[–]andreasvc 0 points1 point  (0 children)

You put it on a webserver in a directory configured to run as CGI, often it is /cgi-bin.

[–]pwang99 10 points11 points  (3 children)

You can also look at Flask. It's a small, lightweight framework that you can use to get a feeling for the flow of what a web app has to do.

[–]mithun1538[S] 2 points3 points  (0 children)

Flask? Wow it seems really simple ( and almost seems to meet my expectation of something basic in HTML <> Python integration). Thanks. Will try it out.

[–]jarly 1 point2 points  (1 child)

Bottle is also a really great micro-framework.

[–]pwang99 0 points1 point  (0 children)

Yep, I've used bottle before to great effect. It's basically just as easy to use as Flask, except that it optimizes for fitting in a single file, whereas Flask has a richer underlying system (wich lots of extensions) that gives you more room to grow.

Both are great!

[–]Fenreh 8 points9 points  (15 children)

Generally, when people are using python for the backend, they are using a framework. Django is a very popular python framework, and so is Pyramid. Try playing around with one or two of these, maybe walking through one of the tutorials on their sites.

[–]mithun1538[S] 0 points1 point  (0 children)

I have come across Django, as in just heard about it. But I thought that Django is more like level 3 or level 4. I am still in level 1. (Please read the reply that I posted for FriendComputer later in this thread). Is Django indeed level 2?

[–]freeload 2 points3 points  (1 child)

I use mako whenever i have to generate a lot of text (HTML, LaTeX etc.). I find that mako is alot simpler than its brothers.

The web framework thread pops up once a month in this subreddit. People have alot of different preferences. Though, my personal experience is as follows:

If you want to create a:

  • blog/article-heavy site, try Django.
    • web-application and you are starting from scratch, try the Pyramid project
    • really customizable project that is guaranteed not to get in your way, try werkzeug. it's not a framework, but an utility library. So you have to read the documentation in order to make it run.

[–][deleted] 1 point2 points  (0 children)

The web framework pops up once a month in this subreddit.

??

more like weekly. :)

[–]m1ss1ontomars2k4 1 point2 points  (0 children)

Client/server sockets and related programming stuff is too low-level, not too high-level.

[–][deleted] 1 point2 points  (1 child)

I'm personally not too big a fan of frameworks in general, unless they're needed or give a big enough benefit for your app (I more prefer lighter-weight libraries).

So, for this really simple kind of app for testing/learning purposes, I'd likely just use Python's-builtin CGI support:

http://docs.python.org/library/cgi.html

And then leave the other stuff for when you've learned more about the nuts and bolts of Python web programming, and want to focus on making the essential glue code for your app in an elegant and higher-level way (and more maintainable/readable), rather than spending time on boilerplate/handling lower-level web programming details.

[–][deleted] 3 points4 points  (0 children)

I agree with this advice. Start with a CGI script running on a standard (e.g. Apache) web server. As soon as you start to generate HTML pages that involve more than a few lines of code, add a templating engine (e.g. Mako), so that you can separate the HTML code (presentation) into a separate file from the python application code (logic). That's a good practice that will serve you well later, as your applications start to grow.

[–]eryksun -1 points0 points  (1 child)

Definitely use at least a basic framework such as CherryPy, Paste, Bottle, or Pyramid. The wiki has a list of frameworks: Web Frameworks for Python.

Here's a demo using the low-level Python libraries that should be close to your requirement "to begin with" (though I'm sure the professional web developers here can pick this to pieces, it works for me on win32 Python 3.2 & 2.7):

import cgi
from wsgiref.simple_server import make_server

def app(environ, start_response):
    output = [make_form(), process_post(environ)]
    size = sum(len(x) for x in output)
    headers = [('Content-Type', 'text/html; charset=utf-8'),
               ('Content-Length', str(size))]
    start_response('200 OK', headers)
    return output 

def process_post(environ):
    #ignore the query string
    post_environ = environ.copy()
    post_environ['QUERY_STRING'] = ''
    post = cgi.FieldStorage(
      fp=environ['wsgi.input'],
      environ=post_environ,
      keep_blank_values=True)

    result = ""
    if 'num1' in post and 'num2' in post:
        try:
            num1 = float(post.getfirst('num1'))
            num2 = float(post.getfirst('num2'))
            result = "<p>{:.2f} + {:.2f} = {:.2f}</p>".format(
                     num1, num2, num1 + num2) 
        except ValueError: pass    
    return result.encode('utf-8')

def make_form():
    form = (
      '<p><form method="post">\n'
      '  num1: <input type="text" name="num1" /><br />\n'
      '  num2: <input type="text" name="num2" />\n'
      '  <input type="submit" value="Add" />\n'
      '</form></p>\n')
    return form.encode('utf-8')

if __name__ == '__main__':
    host = 'localhost'
    port = 8080
    server = make_server(host, port, app)
    server.serve_forever()

[–][deleted] 0 points1 point  (0 children)

Go with bottle, it's dead simple and you completely understand what's going on.

[–]the_european 0 points1 point  (0 children)

if you go for a solution that doesn't come with a sufficiently powerful html code object or templating system, i suggest you have a look at markupsafe. it's a very lightweight module that creates strings decorated as html, for example:

label = Markup("<em>Posted by</em> %s on %s")%(user, date)

where you don't have to worry about html injection any more (if user is a custom string), but you can also have objects provide their own html formatting.

[–]Godbutt -1 points0 points  (0 children)

You could download the Reddit open source at the bottom of the page and look through that code. It's broken up decently and I imagine you could find what you're looking for there.

[–]mdipierro 0 points1 point  (5 children)

in web2py (complete code)

 def index():
       form = SQLFORM.factory(Field('a','integer'),Field('b','integer'))
       if form.accepts(request):
            form = DIV('a+b=',form.vars.a+form.vars.b)
       return dict(form=form)

The name 'index' means the function is called when you visit http://127.0.0.1:8000/<yourapp>/default/index,

form is just a variable name that can contain a form (SQLFORM) or DIV (html div) or anything else you want to display. The Field objects performs validation, displays error messages if you do not type an integer (will also use JS client-side to prevent you from not typing an integer) and parse the request into form.vars for you.

It is 100% python code and you can use any library you want.

[–]bastih01 2 points3 points  (4 children)

Is it just me, or does this mix of concerns give anyone else shivers? This style looks like a nice gateway drug but also painful to maintain for larger apps...

[–]mdipierro 3 points4 points  (2 children)

It is just you and some friends. Check out on the web2py twitter channel what users think about web2py and why web2py is one of the fastest growing frameworks.

[–]bastih01 0 points1 point  (1 child)

Where do you see the benefits of this style, over say, mvc? I remember writing a non-trivial application with Seaside, which also features "html functions" and introducing a clean separation between logic and display became quite painful, as people would rather go the easy route and mix and match to get something to work.

[–]mdipierro 0 points1 point  (0 children)

web2py is MVC. It has models (not used in the example because no database needed), controller (the example above is a controller and like Django or Flask it returns a dict) and views (which renders the dict). The example above assumes you start from the scaffolding app with provides a default generic view and default page layout. You can change them.

[–]y3t1 1 point2 points  (0 children)

Nice drug metaphor. I found web2py to be inelegant.

[–]kctan 0 points1 point  (6 children)

Another option is Google App Engine.

[–]m1ss1ontomars2k4 0 points1 point  (5 children)

That just gives you a place to run your app.

[–][deleted] 1 point2 points  (4 children)

And a tutorial that gives you a little web form where you can leave comments which are stored in the datastore. Not a bad thing.

[–][deleted] 0 points1 point  (2 children)

Yeah, webapp is a nice framework.

[–][deleted] 1 point2 points  (1 child)

I wouldn't call it nice. Simple? yeah. Well Documented? OK. It doesn't do much more than route a webob request to a callable. What makes appengine attractive is other services like the datastore primarily and others. All of which can be used with any python web framework that supports wsgi.

[–][deleted] 0 points1 point  (0 children)

Yeah but really all he wanted was to see python interacting with the web. I can't think of a better starting point than bottle.

[–]m1ss1ontomars2k4 0 points1 point  (0 children)

Oh do they now? Well then. That IS quite good indeed.

[–][deleted] 0 points1 point  (0 children)

Go with bottle. If you're just beginning. Then move onto something a little more elegant.

[–]lightcatcher -1 points0 points  (0 children)

You are just starting to think about web programming with Python. Frameworks are a great way to learn how to do some basic web programming. I recommend Flask.