python demo presented by: noor ilyani safie (2006609641) sazimah mohamed salleh (2006138033)...

72
Pathways to Scientific Teaching II: Active Learning & Assessment Diane Ebert-May Department of Plant Biology Michigan State University [email protected] http://first2.org

Upload: augusta-nicholson

Post on 28-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Python DemoPython Demo

Presented by:Noor Ilyani Safie (2006609641)

Sazimah Mohamed Salleh (2006138033)Saidatul Nurah MS (2006138035)

Build a Rapid Web Development Environment for Python Server Pages and Oracle

Solution Components

The complete Web development environment must consist of at least three essential components: the Web server, database, and server-side backend technology. There are also functional requirements like reliability, scalability, and interoperability. To address them we have chosen:

** Apache HTTP Server 2.0, ** Oracle Database 10g Express Edition (XE), and ** Python 2.4 (with mod_python and cx_Oracle modules)

Windows users will certainly take advantage of "Click Next" installations of all these components, although Linux users still won't be required to type much. We've simplified the installation procedure to make use of the available binaries.

Oracle Database 10g Express Edition

In February 2006, Oracle announced the production release of Oracle Database XE. It is an entry-level, small-footprint version of Oracle Database 10g Release 2 and is completely free to develop, deploy, and distribute.

Available for Windows and Linux operating systems, Oracle Database XE is an excellent choice for PHP, Java, or .NET developers. Furthermore, with the great amount of available third-party modules and drivers, it can be accessed from a range of different programming languages, including Python.

Oracle Database XE comes in two flavors• Western European

• Universal.

Installing and Running Oracle Database XE

Download OracleXEUniv.exe for Windows

On Windows: 1. Login to Windows using account with Administrator privileges. 2. Remove the ORACLE_HOME variable from your system if it has been set up

before. 3. Double-click the downloaded installation executable from the step 1.

4. In the Oracle Database 10g Express Edition - Install Wizard, click Next.

5. In the License Agreement window, select I accept and then click Next.

6. When the Choose Installation Location window pops up, you can either accept the default directory target or select the desired target location clicking the Browse button. After completing this step, click Next.

7. If you are prompted for a port number, you should specify one. The default port numbers for Oracle Database XE are

• 1521 for Oracle database listener • 2030 for Oracle Services for Microsoft Transaction Server • 8080 for XE administrative graphical interface accessible via Web

browser

8. Now you need to set password for SYS and SYSTEM database administrative accounts. In the Specify Database Passwords window, enter the desired password and confirm it below. Click Next.

9. The Summary window offers an overview of the installation parameters you have set through the whole process. If you accept them, click Install to begin installation.

10. Click Finish to complete the installation process. If you would like to launch the administrative browser interface, select the Launch the Database homepage option. You have successfully installed Oracle Database XE on Windows.

Installing Apache HTTP Server 2.0

Apache HTTP Server is currently deployed on at least two-thirds world's Web servers, according to the latest Netcraft statistics. Enabling even the most scalable architectures, it is available for a choice of system platforms, including Microsoft Windows and Linux.

Apache is however much more than just a Web server. Apache Software Foundation provides support for many open-source, enterprise-grade products, including the famous Struts framework, Tomcat servlet container, Derby database, Axis platform, FOP processor, and Xerces parser, to name just a few. Apache HTTP Server is quite easy to configure and provides unmatched flexibility for various server-side configurations. It also serves as the heart of Oracle HTTP Server, as you may already know.

On Windows:

1. Login as Administrator and download the MSI Installer apache_2.0.55-win32-x86-no_ssl.msi; double-click it to begin the installation process.

2. Apache HTTP Server 2.0 - Installation Wizard will be shown. Click Next to continue.

3. In the License Agreement window select I accept the terms in the license agreement and click Next.

4. You will find some Apache HTTP server information in the Read This First window, click Next to continue.

5. The Server Information dialog will appear. At this point you need to enter the following information:

Network Domain - DNS domain in which your server currently is or will be registered in, for the full DNS name py.oracle.com you would need to enter just oracle.com.

Server Name - server's full DNS name without skipping anything like in the above Network Domain.

Administrator's Email Address - by default this email will be shown to clients along with error messages generated by the server.

to which account to install Apache serve—either for All Users or only for the Current User. (Since you don't want Apache to corrupt Oracle Database XE default HTTP 8080 port, I recommend selecting the first, more convenient option)

6. After setting these parameters, click Next.

7. In the next Setup Type window you will be given a choice to select Typical or Custom features. Unless you want to change the target location, use the Typical installation, which skips headers and libraries for compiling modules. (You'll be using pre-compiled modules in later steps.) From this point on I will refer to the Apache installation directory as APACHE_HOME. Click Next to continue.

8. When the Ready to Install the Program window shows up, click Install to initiate the installation process.

9. Click Finish to complete.

Installing Python : On Windows:1. Go to http://www.python.org/ and in the Quick Links section locate the direct link to

the MSI file named Windows Installer. (Python 2.4.3 at the time of writing). Save the python-2.4.3.msi file on your computer.

2. Logged in as user with Administrative rights, double-click the downloaded installer executable. The screen shown below will appear when you will be given a choice to install Python for all or just currently logged user. After selecting the desired option, click Next.

3. In the Select Destination Directory window, leave the default path or change it to the desired target location and click Next.

4. At this point you can enable or disable features to be installed on your system. I suggest leaving all those items in their default state, but if you decide not include some of them, feel free to do so. After selecting desired features, click Next to begin the installation process.

5. Click Finish to complete.

Installing mod_python

We will connect Python to Apache HTTP Server using mod_python, module originally written by Gregory Trubetskoy and generously donated to the Apache Software Foundation. This module has been available on the Internet since 2000, and became part of Apache modules collection in 2002.

Mod_python gives you access to many low-level Apache internals and provides unrivalled flexibility compared to other server-side, Apache-based solutions (like mod_php or mod_perl). You may or may not use these internals, but since we'd like to focus on rapid web development, I will describe the high-level interface it provides, focusing precisely on PSP.

With mod_python you can take the full advantage of Python and its modules, writing server pages that can be cached and wrapped in reusable templates. Please note that the PSP engine is one of many interpreters mod_python provides, but since we would like to embed Python code directly in the page source, PSP is the preferred solution.

Installing mod_python

On Windows:

1. Download mod_python-3.2.8.win32-py2.4.exe from http://www.apache.org/dist/httpd/modpython/win/3.2.8/ and double-click the downloaded executable.

2. Click Next to continue.

3. Mod_python installer will try to locate the default Python 2.4 interpreter. To accept the choice click Next again.

4. To begin the installation process, press the Next button.

5. Upon installation end, the installer will ask for Apache 2 location (APACHE_HOME). Use the tree browser to navigate to the appropriate directory and press OK.

6. Click Finish to complete installation.

Configuring Apache HTTP Server to Handle PSP

After mod_python installation you must make Apache aware of it. For this purpose open APACHE_HOME/conf/httpd.conf for editing(for default Linux location of httpd.conf, consult your system documentation) and append the following lines at the end:

LoadModule python_module modules/mod_python.soAddHandler mod_python .psp .psp_PythonHandler mod_python.pspPythonDebug On

The first line loads mod_python into Apache. The actual path of mod_python.so may vary but the installer should give you the proper path upon finishing. (On Linux most likely it would be libexec/mod_python.so.) The second line informs Apache which files should be handled by PythonHandler, specified on the third line (more about .psp_ usage in the section below).

The last directive switches mod_python into debugging mode; when PythonDebug directive is set to On, it will dump traces for the first unhandled exception in the running application. Setting this flag is highly recommended for development purposes, but make sure you turn it off on production environments so as to not expose certain system internals to visitors.

If you would like mod_python pages to be used as default index pages, locate in

httpd.conf the following line and change it from DirectoryIndex index.html index.html.var to DirectoryIndex index.html index.psp index.html.var

Now restart Apache. On Windows you usually do that with the Apache Monitor in the system tray or by running net stop apache2 and then net start apache2; on Linux it's as simple as apachectl restart.

Using mod_python

PSP are plain text files that include Python code surrounded with <% and %> tags. Python expressions are enclosed within <%= and %> tags. Directives enable inclusion of other PSP pages; they are wrapped by <%@ and %> tags. The least frequently used tags are <%-- and --%> which, as you might guess, are simply comments that are never rendered to the resulting code.

Let's start with the simple Hello Python example. Under APACHE_HOME/htdocs create a file hello.psp with the following content:

<html><%import sys%>Hello! You have <%=len(sys.modules)%> Python modules at your command.</html>

Now go to http://127.0.0.1/hello.psp with your web browser. You will see how many Python modules are installed on your system. Of course, this information is trivial to us. Mod_python doesn't offer a function equivalent to PHP's phpinfo(), which gives detailed information about the interpreter. In the next step, we'll write one for PSP ourselves.

Under APACHE_HOME/htdocs, create a file pspinfo.psp with the following content:

<%%req.content_type = 'text/plain‘

import mod_pythonimport pprintimport sys%>

PYTHON <%%=sys.version %>MOD_PYTHON <%%=mod_python.version %>

PATH = <%%=pprint.pformat(sys.path)%>AVAILABLE MODULES<%%=pprint.pformat(sys.modules)%>

Now open http://127.0.0.1/pspinfo.psp and you should see results similar to those shown below.

PSP uses Python code to output parts of the page using blocks which are distinguished by indentation (like Python itself). The last indentation will persists until either the end of the document or until another Python block. Take a look at the following example (blocks.psp).

<%for i in range(5): j = 2**i # Loop block begins%><%="%d<sup>%d</sup>=%d"%(2, i, j)%><%# This will close the loop block%>Outside the loop block

In above example, We've used code blocks (<% %>) and expressions (<%= %>) together. When writing own scripts, please mind the difference between them: expression can contain only a single Python statement.

This give an excellent in-depth look into the rendering engine. It also explains the logic behind mod_python engine: before execution, PSP pages get rendered into pure Python code.

The last information you need to begin developing basic PSP applications are sessions and form handling. Consider the following example of a basic login scenario (basic_login.psp). The password provided on the page should be a reversed UID:

Remember the AddHandler mod_python .psp .psp_ directive? Now we will make use of the debugging .psp_ address to see what's happening behind the scenes. When you go to http://127.0.0.1/blocks.psp you'll see PSP-produced Python Code and the source code, side by side.

<%if 'uid' in form and 'passwd' in form and form['passwd']==''.join(reversed(form['uid'])):

session['uid'] = form['uid']%>user <%=session['uid']%> logged in<%else:%><form action="basic_login.psp">UID<br/><input type="text" name="uid"/><br/><br/>Password<br/><input type="password" name="passwd"/><br/><br/><input type="submit" value="Login"/></form><%#%>

Note that Python does not limit you to use strings or integers as dictionary keys—any hashable value will fit. You can, for example, store a file object in the session pool to refer to it at any time during the session. Mod_python treats GET and POST requests equally, storing them in the form dictionary, making it easy to check whether the value has been set by the user. Python dictionaries have some very useful built-in methods, the most usable at this point are:

D.keys() - returns a list of dictionary D keys D.has_key(k) - returns True if dictionary D has a key k, else False D.get(k[, d]) - returns value of D[k] if D has key k, else returns d (d defaults to

None); can be very useful during form handling, e.g. <%=form.get('is_sure', 'not sure')%>

cx_Oracle

cx_Oracle Python module allows easy access to Oracle Database. It has been developed by Anthony Tuininga (Computronix) in conformance to the DB API 2.0 specification, which means you use the same set of methods and properties you can use to connect to MySQL or PostgreSQL.

Cx_Oracle has all the methods and properties of DB API 2.0 specification (PEP 249) except the nextset() cursor method and Binary() constructor. Note however that cx_Oracle introduces many own extensions to the standard API, which greatly enhances working with Oracle databases. Each such extension is clearly marked in cx_Oracle documentation but basically, if you have already used DB API 2.0 in the past, you should feel like home.

Installing cx_OracleOn Windows: 1. Download cx_Oracle-4.1.2-win32-10g-py24.exe and double-click the downloaded installer. 2. Click Next to continue. 3. The installer will try to locate the default Python 2.4 interpreter. To accept the choice, click Next. 4. To begin the installation process, press the Next button. 5. Click Finish to complete installation.

Using cx_Oracle

As we've mentioned earlier, cx_Oracle is based on DB API 2.0 specification, which makes it extremely easy to use. Consider the following example to familiarize with the basic steps for connecting to the database and issuing queries. Create a file ora.psp under APACHE_HOME/htdocs to see whether the cx_Oracle module is working properly. (Replace username and passwords with values applicable to your configuration.):

<%import cx_Oracledb = cx_Oracle.connect('username', 'password', '127.0.0.1/XE')c = db.cursor()

c.execute('select * from dual')req.write(c.fetchall()[0][0])

db.close()%>

When you open http://127.0.0.1/ora.psp you should see the X character in your browser as the only value in the system DUAL table.