Main Page | Recent changes | Edit this page | Page history

Printable version | Disclaimers | Privacy policy

Not logged in
Log in | Help
 

Notes: Recitation 10

From 6.00 reference wiki

Contents

Introduction

Throughout the term you have been using your workspace to submit your problem sets. The workspace code provides a secure (it's hard to impersonate you; unlike with email) and convenient (deadline looming? you don't have to run down to Stata with a print-out) mechanism for turning in your problem sets.

The workspace 'program' is actually written entirely in Python. Over the next two recitations we will discuss how you can write programs like this.

Because of some cool Python modules and the scripts.mit.edu service provided by Athena, writing programs like the workspace isn't that hard.

Python Web Scripts

The main difference between the workspace code and the programs you have been writing thus far, is that the workspace code runs on a server machine, rather than on your machine. It is important that you are clear about where the program is running.

When you try to log into your workspace, your web-browser sends a special kind of message over the network to an athena server. In response to this message, a Python program is started on the athena server. This program performs some processing and then uses print statements to output some messages. The output of this Python program is sent back to your web-browser (on your computer), and you see your workspace.

When you click on the Upload file button, the contents of the file you have chosen are sent over the network to the athena server. Another Python program is started on the athena server, to handle the incoming file. This server-side Python program saves the file to disk and sends you back a success message (or an error message, if you're unlucky).

Getting Started

If you look at your browser's address-bar when you are logged into your workspace, you will see that it starts with scripts-cert.mit.edu rather than web.mit.edu. This is because you need to sign up for a special athena service to be able to run Python scripts on athena servers.

To sign up for the service:

 athena% add scripts
 athena% signup-web

After you have done this, your athena home directory should have the web_scripts subdirectory. Any Python scripts you put in that directory will be run on an athena server.

Once you are signed up, your scripts will automatically be accessible at URLs starting with (replace YOUR_USER_NAME below with your athena username):

 http://scripts.mit.edu/~YOUR_USER_NAME/

Note for windows athena: If you are running a windows machine, you should be able to get an athena% prompt by logging in remotely: SSH X.dialup.mit.edu

More information on signing up can be found here:

Your First Web Script

Hello World

Start idle, and save the following code as the file hello.py in your web_scripts subdirectory. This is probably the simplest possible Python web script you can write.

  print 'Content-type: text/html\n\n'
  print "Hello World"

Don't worry about what the first print means. It is essentially telling your web browser to display the text.

Now enter the following into your web-browser's address bar (replacing YOUR_USER_NAME with your athena username):

  http://scripts.mit.edu/~YOUR_USER_NAME/hello.py

If everything is working, you should see the following in your browser.

  Hello World

Dealing with Exceptions

At this stage, unfortunately, if your Python program caused an exception, you would see a really cryptic error message in your browser. In order to get 'meaningful' exception messages, you should add the following line to the start of any Python web script you write:

  import cgitb; cgitb.enable()

Outputing HTML

The html_util Module

We mentioned in lecture that web-pages are written in a markup language called HTML. This language is interpreted by web-browsers to display all that fancy-formatted text.

Technically, the output of any Python web script (everything print'd) must constitute a complete, valid HTML document. To shield you from having to learn HTML, we have provided you a Python module that provides a HTMLDocument class that lets you construct and output HTML documents.

Caveat: When using html_util everything output by your program must be output using the HTMLDocument methods. You should not use print statements. If you're lucky, your scripts will still work with the print statements, but you'll see some weird output, and it'll be hard to debug.

Sample Script: Simple Text

import cgitb; cgitb.enable()
from html_util import HTMLDocument

doc = HTMLDocument("Hello World")  # create a document with a title

doc.new_section("Hello World!")    # big bold text

doc.new_paragraph()                # start a new paragraph
doc.write_text("This is some text, nothing too fancy.")

doc.print_html()                   # output the HTML

Sample Script: Formatted Text

import cgitb; cgitb.enable()
from html_util import HTMLDocument

doc = HTMLDocument("Hello World")  # create a document with a title

doc.new_section("Hello World!")    # big bold text

doc.new_paragraph()                # start a new paragraph
doc.write_text("This is some text, nothing too fancy.")

doc.new_paragraph()                # a paragraph with formatted text
doc.write_text("You can make some text ")
doc.write_text("bold", bold=True)
doc.write_text(", or ")
doc.write_text("italic", italic=True)
doc.write_text(", or ")
doc.write_text("colored", color='red')
doc.write_text(", or even ")
doc.write_text("use multiple effects.", bold=True, typewriter=True, color='blue')
   
doc.print_html()                   # output the HTML

Sample Script: Boxes

import cgitb; cgitb.enable()
from html_util import HTMLDocument

doc = HTMLDocument("Hello World")  # create a document with a title

doc.new_section("Hello World!")    # big bold text

doc.new_paragraph()                # start a new paragraph
doc.write_text("This is some text, nothing too fancy.")

# let's put something in a coloured box...
doc.new_paragraph()

doc.begin_center()      # Everything output between a 'begin_center'
                        # and an 'end_center' will be centered horizontally
                        # in the web-browser

doc.begin_div_block(type="yellow", width="50%")
                        # Everything between a 'begin_div_block' and
                        # an 'end_div_block' will be in a box. You can
                        # pick the color-scheme of the box by giving
                        # a different type parameter. You can also control
                        # the width of the box, using the width parameter.

txt=\
"""
This text is inside the box. The width of this box is 50% the width of the 
browser window. Generally, you can do anything inside a box that you can do 
outside. You can even have boxes inside boxes."
"""
doc.new_paragraph()
doc.write_text(txt)


doc.new_paragraph()                # a paragraph with formatted text
doc.write_text("You can make some text ")
doc.write_text("bold", bold=True)
doc.write_text(", or ")
doc.write_text("italic", italic=True)
doc.write_text(", or ")
doc.write_text("colored", color='red')
doc.write_text(", or even ")
doc.write_text("use multiple effects.", bold=True, typewriter=True, color='blue')

doc.end_div_block()     # end part of Document in the box.

doc.end_center()        # End centered part of document.

doc.new_paragraph()                
doc.write_text("This text is after the box.")
   
doc.print_html()       # output the HTML

Authenticating Users

The workspace doesn't ask you for a special password. It uses the same web-certificates mechanism used by WebSIS to authenticate that you are who you claim to be. Using the web certificate you send it through your browser, the athena server can authenticate you, determining your name and email address.

The authentic_user module allows your web scripts to be able to do this:

Sample Script: get_user_info

import cgitb; cgitb.enable()
from html_util import HTMLDocument
from authentic_user import get_user_info

doc = HTMLDocument("Hello")  # create a document with a title

userinfo = get_user_info()

if userinfo:  # if we have an authenticated user
    doc.new_section("Welcome")    # big bold text

    doc.new_paragraph()                # start a new paragraph
    doc.write_text("Hello ")
    doc.write_text(userinfo['name'], bold=True)

    doc.new_paragraph()
    doc.write_text("Your email address is: ")
    doc.write_text(userinfo['email'], typewriter=True, bold=True)

else: # if we don't know who this is
    doc.new_section("Who are you?")

    doc.new_paragraph()
    doc.write_text("I don't know who you are...")

doc.print_html()                   # output the HTML

Secure Connections

get_user_info will return None whenever your script is accessed using an address (a URL) that begins with

  http://scripts.mit.edu/

For get_user_info to return a valid athena user's information, the script must be accessed using a URL that begins with:

  https://scripts-cert.mit.edu/

The use of the https and the scripts-cert enables a secure connection, and asks the user for their MIT web certificate, which allows our Python web scripts to trust that the athena username returned by get_user_info is not someone impersonating the real user.

Next Week

Next week we will use what we've learnt today to write a set of web scripts that take input from users (e.g., 'what is your favourite color?') and saves the submitted info to a file on the athena server. These scripts will be similar to, for example, the sign-up web script you used at the start of the class.

Recitation Example Code

The code for the above examples, and their required modules, is online:

Retrieved from "http://slice.csail.mit.edu../../../r/e/c/Notes%7E_Recitation_10_eb10.html"

This page has been accessed 61 times. This page was last modified 17:43, 4 May 2006 by 6.00 reference wiki user Asfandyar.


[Main Page]
Main Page
Recent changes

Edit this page
Discuss this page
Page history
What links here
Related changes

Special pages
Bug reports