Build a fast WEB development environment for Python Server Pages and Oracle.

Source: Internet
Author: User
Tags fast web pprint oracle developer

Build a fast WEB development environment for Python Server Pages and Oracle. -On the Water side-blog channel-csdn.net

Build a fast WEB development environment for Python Server Pages and Oracle. Category: Technology space 2008-06-12 10:43 301 People Read Comments (0) Collection ReportPythonoracleserverwebapache Database

directory (?) [+]

    1. Background for Python and Python server Pages
    2. Solution components
    3. Oracle Database 10g Quick Release
      1. Install and run the Oracle database shortcut
    4. Installing Apache HTTP Server 20
    5. Install Python
    6. Installing Mod_python
      1. Installing Mod_python
    7. Configure Apache HTTP server to process PSP
    8. Using Mod_python
    9. Cx_oracle
      1. Installing Cx_oracle
      2. Using Cx_oracle
    10. Next steps
 

A variety of server-side technologies that act as a middle tier between Web servers and databases have benefited today's developers, including JavaServer Pages (JSP), Active server Pages (ASP), PHP, and PL/SQL Server Pag ES (if you are an Oracle developer).

I first approached the Python programming language in 2003 and since then began to indulge in the unique charm of the language and its ease of use. It's a high-level language, almost like writing in plain English, just like programmers know about pseudo-code. Python's dynamic nature allows you to write the most concise code to accomplish even the most complex tasks.

In this article, I'll briefly describe a simple way to create a full Python server pages/oracle database 10g fast WEB development environment. This article assumes that you are not installing any components on a Windows or Linux system. (if it is already installed, you can skip some steps accordingly.) All the mentioned components are free to download and do not require any license fees.

Background for Python and Python server Pages

Python offers powerful self-detection capabilities, dynamic typing, fully object-oriented, scalability, and platform independence (Windows, Linux, Solaris, Mac OS, NOKIA/S60, Pocket PC, and so on). It enables you to achieve high productivity and result-oriented and focus on solving problems rather than dealing with language intrinsic characteristics. Python is very readable and easy to maintain (by making specific demands on code styles). I have a lot of Python single-line programs that can actually perform complex tasks (sometimes two lines, and if you have import statements), they are far more powerful than "Hello-world" programs.

One of the biggest advantages of Python is its extensive standard library, which provides out-of-the-box module groups for most programming tasks (known by Python programmers as "policy with batteries"), including file I/O, System interaction, networking, data analysis and operations, threading, monitoring, unit testing, self-detection, XML Processing and so on.

You'll be fascinated by the speed with which Python is developed-and ultimately you can make your computer understand rather than misunderstand your intentions. In addition, with the built-in document string (docstring)-the inline help string-Other programmers can quickly understand the essence of your class or function. (Creating documents from source code is a breeze.) For these reasons, Google and NASA use a lot of Python, and Microsoft is developing its own version of Python on the. NET platform, called IronPython.

Python Server Pages (PSP) is to Python as Java Server Pages is to Java. Pages rendered using the PSP perform 50 times times better than pages that are processed by conventional CGI. Mod_python contains a number of specialized modules that make WEB development easier.

Solution components

A complete Web development environment must contain at least three basic components: a Web server, a database, and a server-side back-end technology. There are also functional requirements, such as reliability, scalability, and interoperability. To meet these criteria, I chose to use Apache HTTP Server 2.0, Oracle Database 10g Express (XE), and Python 2.4 (with Mod_python and cx_oracle modules). (Read on and find out why you chose these three items.) )

Not only do Linux users still need to type too much content, but Windows users must also enjoy the simple installation of all of these components (just click Next). I have simplified the installation process to take advantage of the available binaries.

Oracle Database 10g Quick Release

In February 2006, Oracle launched the production version of the Oracle Database Express version. It is a small entry-level version of Oracle Database 10g version 2nd, which is completely free to develop, deploy, and distribute.

Oracle Database Express is the first choice for PHP, Java, or. NET developers for Windows and Linux operating systems. In addition, with a large number of available third-party modules and drivers, the database can be accessed through a variety of different programming languages, including Python.

Oracle Database Express has two versions of Western European and general. The former supports only LATIN1 characters, while the latter's default character set is Al32utf8. The generic version also includes an administrative interface translated into Brazilian Portuguese, Chinese (simplified and Traditional), English, French, German, Italian, Japanese, Korean, and Spanish. No one wants to be limited to using LATIN1, so I recommend installing and using the generic version.

Install and run the Oracle database shortcut

Download the OracleXEUniv.exe for Windows or oracle-xe-univ-10.2.0.1-1.0.i386.rpm for the RPM-based Linux version. (Oracle database Express is also available for Debian, but this is beyond the scope of this document.) )

On the Windows platform:

  1. Log on to Windows with an account that has administrator privileges.
  2. If the oracle_home variable has been set before the system, remove it.
  3. Double-click the installation executable file that you downloaded in the first step.
  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 accept the default directory, or you can select the desired destination by clicking the Browse button. When you have completed this step, click Next.
  7. If you are prompted to enter a port number, you should specify one. The default port number for Oracle database Express is
    • 1521, for Oracle database Listener
    • 2030, for the Oracle Services for Microsoft Transaction Server
    • 8080, for the XE graphical management interface accessible via Web browser
  8. Now, you need to set the password for the SYS and system database administrator accounts. In the specify Database Passwords window, enter the required password and confirm. Click Next.
  9. The Summary window displays the installation parameters that are set during the entire process. If you accept these parameters, click Install to start the installation.
  10. Click Finish to complete the installation process. If you want to start the Admin browser interface, select the Launch the Database homepage option. You have successfully installed the Oracle database shortcut on Windows.
on the Linux platform:
    1. Log in as the root user.
    2. Change the current path to the directory where you downloaded the RPM installer in the first step.
    3. Run the following file to start the installation process:
      (The installation process begins.) )
    4. Now, when prompted to run the following command, you need to set parameters for the installed database:
      #/etc/init.d/oracle-xe Configure
    5. Enter the following details:
      • HTTP Port for the Oracle Database Express graphical user interface (default is 8080)
      • Port for Oracle database Listener (default is 1521)
      • Passwords for SYS and system Management database accounts
      • Whether you want to start the database automatically after the system restarts
    6. You can reconfigure the database at any time by running the following command:
      #/etc/init.d/oracle-xe Configure
    7. To control a DB instance by starting or stopping it, either use the menu option installed with XE or run the following command from the command line:
      #/etc/init.d/oracle-xe Start
      Or
      #/etc/init.d/oracle-xe Stop

You can now sign in to the XE graphical management interface by opening http://127.0.0.1:8080/apex/in your browser. (If the database is configured with custom parameters, you need to change the path accordingly.) )

Installing Apache HTTP Server 2.0

Based on the latest statistics, Apache HTTP Server is currently deployed at least two-thirds of the world's Web servers. Because it can even support the most scalable architecture, it can be used on a variety of system platforms, including Microsoft Windows and Linux.

However, Apache is more than just a WEB server. Apache Software Foundation supports many open source enterprise-class products, including the well-known Struts framework, Tomcat servlet container, Derby database, Axis platform, FOP processor, and Xerces par Ser and so on, countless. Apache HTTP Server is very easy to configure and provides unmatched flexibility for a variety of server-side configurations. In addition, as you know, it can also act as the core of Oracle HTTP server.

on the Windows platform:
  1. Log in as Administrator and download MSI Installer apache_2.0.55-win32-x86-no_ssl.msi; Double-click the program to begin the installation process.
  2. The Apache HTTP server 2.0-installation Wizardwill appear on the screen. Click Next to continue.
  3. In the License Agreement window, select the I accept the terms in the License agreementand click Next.
  4. You will see some Apache HTTP server information in the Read This first window, click Next to continue.
  5. The Server Information dialog box appears. At this point, you need to enter the following information:
    • The Network domain-server is currently in or about to be registered to the DNS domain, for the full DNS name py.oracle.com, just enter oracle.com.
    • Server name-The full DNS name of the server and cannot omit any information like the Network Domain above.
    • Administrator ' s email address-by default, the e-mail message is displayed to the client along with the error message generated by the server.
    • Select the account for which you want to install Apache server, either for all users or for the current user only. (If you do not want Apache to damage the default HTTP 8080 port for Oracle Database Express, I recommend that you choose the first more convenient option.) )
  6. When you are finished setting these parameters, click Next.
  7. In the next Setup Type window, you need to choose whether to install typical or Custom . Unless you want to change the target location, use typical installation, which skips the title and library used to compile the module. (Pre-compiled modules will be used in a later step.) At this point, I named the Apache installation directory apache_home. Click Next to continue.
  8. When The program window is displayed, click Install to start the installation process.
  9. Click Finish to complete the installation.

On the Linux platform (RPM method):

    1. If your system already contains Apache HTTP server, you can skip this section. Most Linux editions have Apache installed by default, but you need to make sure that you have version 2.0.x installed. (Use the rpm-qa | grep apache command to self-detect.) )
    2. Download httpd-2.0.55-1.i386.rpm.
    3. Run the following command to install:
      # RPM-IVH httpd-2.0.55-1.i386.rpm
      (The default location forapache_home may vary depending on the--prefix parameter, typically/usr/local/apache2.) )
    4. Installation from the source process is described on http://httpd.apache.org/docs/2.0/install.html; if your version cannot handle RPM, the content provided here will be a good guide.

To check if Apache HTTP server is working properly, go to HTTP://127.0.0.1/and see if the default Welcome page is displayed.

However, the configuration of Apache is incomplete and you still need to install Python and Mod_python. Follow these steps to complete the installation of the Python interpreter on your operating system.

Install Python

On the Windows platform:

    1. Go to http://www.python.org/and locate the direct link to the MSI file (named Windows Installer) in the Quick links section. (As of this writing, the current version of Python is 2.4.3). Save the Python-2.4.3.msi file to your computer.
    2. Log on as a user with administrative privileges and double-click the downloaded installer executable file. The following screen will appear and you will need to choose whether to install Python for all users or currently logged-in users. When you have selected the options you want, 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 the features that you want to install on the system. It is recommended that you keep the default state for all of these items, but you can make changes if you decide to include only a subset of them. Once you have selected the desired features, click Next to start the installation.
    5. Click Finish to complete the installation.

On the Linux platform:

The Linux installation of Python depends entirely on the system version. There are a number of installation options here, and if your system is not too old, you have a higher chance of using Python 2.4. Please visit http://www.python.org/download/linux/to view available options.

Installing Mod_python

We will use Mod_python to connect python to Apache HTTP server, a module originally written by Gregory Trubetskoy and generously donated to the Apache software Foundation. The module has been available on the Internet since 2000 and became part of the Apache module group in 2002.

Mod_python gives you access to many low-level Apache internal information and provides superior flexibility over other Apache-based server-side solutions such as mod_php or Mod_perl. You don't necessarily use these internal information, but because we're focused on fast web development, we'll cover the high-level interface that it provides for the PSP.

With Mod_python, you can take advantage of Python and its modules to write server Pages that can be cached and packaged in a reusable template format. Note that the PSP engine is one of the many interpreters provided by Mod_python, but because we want to embed Python code directly into the page source code, the PSP is the preferred solution.

Installing Mod_python

Troubleshooting Windows installation

Under some system configurations, Apache cannot find the path to the Python libraries and modules. A simple workaround is to change the account running the Apache 2 service.

Run the services.msc command and select Apache 2from the list of available services; Right-click and select Properties. On the Log on tab, set the This account option and enter a password for the current user. Press OK and restart the service.

on the Windows platform:

    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 file.
    2. Click Next to continue.
    3. The Mod_python installer will attempt to find the default Python 2.4 interpreter. To accept the selection, click Nextagain.
    4. To start the installation process, press the Next button.
    5. At the end of the installation, the installer will ask for the location of Apache 2 (apache_home). Navigate to the correct directory using the tree browser and press OK.
    6. Click Finish to complete the installation.

On the Linux platform:

    1. This step requires compiling the module. To do this, download the mod_python-3.2.8.tgz file from http://www.apache.org/dist/httpd/modpython/and place it in the/tmp directory of the Linux system.
    2. You need to compile Mod_python as a dynamic shared object (DSO) to be loaded by the server at run time. This allows you to compile the Apache server without recompiling it. Ideally, ./configure in the/tmp directory; Make should be sufficient to compile the module. Depending on your system configuration, there may be situations where you need to manually specify Apache, Python, and/or Flex locations. If you encounter a compilation error, consult the official Mod_python installation Guide.
    3. Finally, you need to install the compiled module. You need to install as root. Still in the/tmp directory, run the make install and wait until the execution completes.

Configure Apache HTTP server to process PSP

After installing Mod_python, you must let Apache know. To do this, open apache_home/conf/httpd.conf for editing (consult your system documentation for HTTPD.CONF's default location on Linux) and append the following line of code to the end:

LoadModule python_module modules/mod_python.soaddhandler mod_python. psp. Psp_pythonhandler Mod_ Python.psppythondebug on

The first line loads the Mod_python into Apache. The actual path to the mod_python.so may vary, but the setup program should give the correct path when it is finished. (On a Linux platform, this path is likely to be libexec/mod_python.so.) The second line notifies Apache of the files that should be processed by the Pythonhandler specified by the third row (the following section details the usage of the. psp_). The last instruction switches Mod_python to debug mode, and when the pythondebug instruction is set to ON, it dumps the trace for the first unhandled exception in the running application. It is highly recommended that you set this flag in development, but be sure to turn it off in a production environment to avoid exposing certain system internals to visitors.

If you want to use the Mod_python page as the default index page, locate the following line in httpd.conf and remove it from
DirectoryIndex index.html Index.html.var
Change to
DirectoryIndex index.html INDEX.PSP Index.html.var

Now, restart Apache. On the Windows platform, it is common to use Apache Monitor in the system bar, or to run the net stop Apache2 and then run the net start apache2 to restart; on the Linux platform, heavy Kai is as simple as apachectl restart .

Using Mod_python

The PSP is a plain text file that contains Python code with <% and %> tags. Python expressions are included in the <%= and %> tags. The directive supports the inclusion of other PSP pages, which are packaged by the <%@ and %> tags. The least common tags are <%-- and --%>, and as you can guess, these two tags just don't appear in the result code.

Let's look at a simple Hello Python example. Under Apache_home/htdocs, create a file hello.psp that has the following content:

 
  

Now, use your browser to go to HTTP://127.0.0.1/HELLO.PSP. You will see the number of Python modules installed on your system. Of course, this information is of little use to us. Mod_python does not provide a function equivalent to PHP's Phpinfo (), which can give detailed interpreter information. In the next step, we will personally write a function for the PSP.

Under Apache_home/htdocs, create a file pspinfo.psp that has 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 a result similar to the shown.

The PSP uses Python code to output parts of the page that use the indented-feature block (like Python itself). The last indentation will persist until the end of the document or 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 WI ll close the Loop block%>outside the loop block

In the example above, I used both a code block (<%%>) and an expression (<%=%>). When writing your own scripts, be aware of the differences between the two: An expression can contain only one Python statement. If you think this is hard to understand, revisit the Apache configuration in the previous step. Do you remember AddHandler mod_python. psp. PSP_ instructions? Now, we'll use the Debug. Psp_ address to see what's going on behind the scenes. Go to HTTP://127.0.0.1/BLOCKS.PSP and you'll see that the PSP-generated Python code is listed alongside the source code.

This is useful for us to get an insight into the rendering engine. It also illustrates the logic behind the Mod_python engine: The PSP page is rendered as pure Python code before execution.

Before you start developing a basic PSP application, you need to know the session and form processing. Consider the following basic login example (BASIC_LOGIN.PSP). The password provided on the page should be the reverse-order UID:

<%if ' uid ' in form and ' passwd ' in form and form[' passwd ']== '. Join (Reversed ' uid ']): form[' uid '] = session[' 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><%#%>

The PSP features two important global variables:form and session. These are the standard Python dictionaries. This will give you maximum flexibility, but be careful when assigning variables because they are not covered with protection. Session Variables can be set by setting the key value of the session dictionary variable:

session[' variable ' = value

Note that Python does not restrict you to use a string or integer as the dictionary key-any hash value applies. For example, you can store a file object in a session pool to reference it at any time during a session. Mod_python treats GET and POST requests Equally, stores them in the form dictionary, and is easy to see if the user has set the value. The Python dictionary has some very useful built-in methods that are most easily used at this time:

    • D.keys () -Returns the dictionary D key list
    • D.has_key (k) -returns Trueif dictionary D has the key K, otherwise False
    • D.get (k[, d]) -if D has a key K, the return value d[k], otherwise returns D(the default is None); This is useful in form processing. For example <%=form.get (' is_sure ', ' not sure ')%>

Cx_oracle

With the Cx_oracle Python module, access to the Oracle database can be easily achieved. This module was developed by Anthony Tuininga (Computronix) According to the DB API 2.0 specification, which means that you can connect to MySQL or PostgreSQL using the same method and attribute group.

Cx_oracle has all the methods and properties of the DB API 2.0 specification (PEP 249), in addition to the Nextset () cursor method and the Binary () constructor. Note, however, that Cx_oracle has introduced many of its own extensions to the standard API, which greatly enhances collaboration with Oracle databases. These extensions are described in detail in the cx_oracle documentation, but generally speaking, if you used DB API 2.0 in the past, these extensions should be no stranger to you.

Installing Cx_oracle on the Windows platform:
    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 attempt to find the default Python 2.4 interpreter. To accept the selection, click Next.
    4. To start the installation process, press the Next button.
    5. Click Finish to complete the installation.

On the Linux platform:

    1. Download the cx_oracle-4.1.2-10g-py24-1.i386.rpmand place it in the system's/ tmp directory.
    2. Run in the/ tmp directory:
      $ RPM-IVH cx_oracle-4.1.2-10g-py24-1.i386.rpm
Using Cx_oracle

As mentioned earlier, the Cx_oracle is based on the DB API 2.0 specification, so users are very simple to use. Refer to the following example to familiarize yourself with the basic steps of connecting to a database and issuing queries. Under Apache_home/htdocs, create a file ora.psp to see if the Cx_oracle module is functioning properly. (Replace the user name and password with the values that apply to the 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 treat the X character in your browser as a unique value in the System DUAL table.

Next steps

Just now you have set up a complete working environment for the PSP and Oracle database 10g, and have also learned the basics of Python Web development. Now you can use the PSP to write complex applications or switch to Mod_python's Publisher Handler to provide a better MVC (model-View-controller) strategy.

There are currently several application frameworks available for Python. Although I recommend that you try it, these frameworks need to be further improved to use in an enterprise-class environment. Apache and Mod_python itself are strong enough to handle most of the development tasks.

Przemyslaw Piotrowskiis an information technology specialist specializing in emerging technologies and dynamic, flexible development environments. He has a strong it expertise background (including management, development, and design) and discovers a number of software interoperability approaches. His personal blog is prpi.blogspot.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.