< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162148041040021164115000057

Python Active Scripting

Active Scripting is a technology developed by Microsoft that allows scripting languages to be embedded inside Web browsers. Currently, Microsoft Internet Explorer 4 and above supports client-side scripting, whereas Internet Information Server (IIS) supports server-side scripting, using a component called Active Server Pages (ASP). In both cases, the scripting code is embedded inside the HTML code. There is a limitation to using Python as a client-side solution for your Web applications: Each client machine must have Python installed. That's probably the greatest disadvantage that Python has among the other Active Scripting languages because Internet Explorer provides core support for VBScript and JScript. Other problems with using Python as a client-side scripting language include the fact that it is only supported in Internet Explorer, it only works on Windows, and it requires that the Python Active Scripting component be installed. It is probably okay in controlled environments, but on the Internet, hardly anyone meets this criteria, so you can't rely on it.

In order to implement security procedures, not all Python commands are available. Commands that execute some critical operations—such as open files, create sockets, and so on—are hidden behind a "sandbox", in a concept similar to the one used by Java. For more information, check out

Python and Microsoft ActiveX Scripting

http://www.python.org/windows/win32com/ActiveXScri pting.html

Active Scripting

http://msdn.microsoft.com/scripting

The Python for Windows extensions come with more details about the use of Active Scripting along with Internet Explorer. For now, let's take a look at the following code:

					
<script language=python>
msg = "Hello Python World! I am counting down!<br>"
document.write(msg)
counter = 10
while counter > 0:
    document.write(counter)
    document.write("<br>")
    counter = counter - 1
document.write("Booooom!")
</script>

				

This code must be inserted in a HTML file in order to be executed. Next, you have a slightly modified code. This one uses the alert() function to put a message box in the user's screen. As you already know, each application exposes its own object model, and for example, the alert() function is part of the object model exposed by the Internet Explorer, which is similar to the Dynamic HTML object model. Actually, everything here happens as COM transactions.

					
<script language=python>
msg = "Hello Python World! I am counting down!<br>"
document.write(msg)
counter = 10
while counter > 0:
    document.write(counter)
    document.write("<br>")
    counter = counter - 1
alert("Booooom!")
</script>

				

A script tag can be executed in two places: in the client machine (default behavior) or in the server. The next structure shows how to let the application know where it needs to execute the script.

					
<SCRIPT RunAt=Server Language=Python >
   #This code runs at the server
</SCRIPT>
<SCRIPT Language=Python >
   #This code runs at the client
</SCRIPT>

				

The next example demonstrates how you can cause your Python code to interact with standard HTML code. Note that you cannot use leading whitespaces in the Python block. In order to handle events such as the ones shown here, you need to have the notation object_event in mind. Also note that in Python, you have to inform the complete namespace of the object, including the form name. This is something that VBScript handles better by allowing you to use just the object name.

					
<FORM NAME = "myform">
  <INPUT TYPE="Text" NAME="txt1" SIZE=40><br>
  <INPUT TYPE="Text" NAME="txt2" SIZE=40><br>
  <INPUT NAME="B1" TYPE="BUTTON" VALUE="Click me">
  <SCRIPT LANGUAGE=Python>
def myform_onClick():
    myform.txt1.value = document.location
def txt1_onChange():
    myform.txt1.value = ""
    myform.txt2.value = ""
def txt2_onFocus():
    myform.txt2.value = myform.txt1.value
  </SCRIPT>
</FORM>

				

In order to have full exposition with the Active Scripting technology, you also need to take a look at Windows Scripting Host (WSH). WSH is part of Windows 98 and 2000, but it can also be downloaded from http://msdn.microsoft.com/scripting for the other Windows environments (95 and NT). WSH runs Python files that have the extension .pys. These files are regular text files that can freely use the object model exposed by WSH. Note that .pys files are not correctly registered—you need to explicitly specify either cscript.exe or wscript.exe on the command line.

Now, that you are ready to write your programs, you might also need to debug your Active Scripts. You have two tools for the job, both provided by Microsoft:

  • The first one is a free product called The Windows Script Debugger. This version can be downloaded from http://msdn.microsoft.com/scripting/.

  • The other option is to use Microsoft Visual Interdev that comes as part of Microsoft Visual C++. This option is not free because it's attached to the commercial product.

Using COM Objects

Active Scripting is a COM-based technology that works by providing a specific language's object model to the user. In Chapter 7, "Objects Interfacing and Distribution," you learned that each application exposes a progID in order to interface with other systems. Therefore, when you say Language = Python inside a script tag, you are actually opening an interface to a progID called Python. As you might be wondering, VBScript, JScript, and Python are COM progID s used to handle each one of these languages.

In our case, after you specify that the scripting language is Python, you acquire access to the interface exposed by the Python object model. As you can see in the next ASP example, within the COM scripting connection, you are still able to use other COM interfaces.

This example opens an ODBC connection to the database identified in the connection string. In order to test this example, make sure that your system has the informed DSN, and that the database has the necessary table. This code must be saved in a file using the .asp extension in order to let it run under Microsoft IIS.

After you execute it, it reads the selected columns from a database table and displays the columns and contents in a HTML table structure. Obviously you'll need this particular table in your database for it to work, but you should be able to adapt it. Note that this code is a straight conversion from VBScript, except for the fact that the Execute statement returns atuple.

						
<%@ LANGUAGE = Python %> <% import win32com.client 
graphics/ccc.gifoconn=win32com.client.Dispatch("ADODB.connection")
oconn.Open ("DSN=db_sql_server")
objRecords, thing = oconn.Execute (
  "SELECT currency_desc, symbol FROM tb_currency")

Response.Write("<TABLE border=1><TR>")

for objField in objRecords.Fields:
  Response.Write("<TH>"+objField.Name+"</TH>")

Response.Write("</TR>")

while not objRecords.EOF :
  Response.Write("<TR>")
  for objField in objRecords.Fields:
    Response.Write("<TD>"+objField.Value+"</TD>")
  objRecords.MoveNext()
  Response.Write("</TR>")

Response.Write("</TABLE>")

oconn.close
oconn=None
%>

					

ASP and Microsoft ActiveX Scripting

Active Server Pages, commonly referred to as ASP, is Microsoft's solution to server-side scripting applications. The difference between Active Server Pages and HTML pages is that with simple HTML pages, the client browser requests a Web page from a Web server. The server sends the file to the client, and the page is shown on the client's browser. On the other hand, with Active Server Pages, the server gets a chance to alter the file before sending it to the user. So, for every request for a file with an .asp extension, the server runs the file through a interpreter that parses the ASP commands. You can have your ASP code connect to any ODBC-compliant database, and dynamically insert the data into your HTML pages.

To use Active Server Pages, you must be running a Microsoft Web Server, specifically Internet Information Server (IIS) 3.0 or up—Microsoft's Internet Information Server is a Web Server that supports both CGI and ASP. If your Web site runs on a UNIX system, you can still use Active Server Pages, but you need to use third-party tools to translate the ASP before it is sent to the client. Of course, there are other (possibly better) options when not using IIS. ASP is not necessarily the best choice.

Tip

Note that for everything you can do with ASP, you can also do using straight CGI scripting.



ASP is not language dependent, and though most of the things you will find in the market are written in VBScript or JScript, you can actually configure ASP to use any other scripting language that supports the Microsoft ActiveX Scripting interface. This includes VBScript, JScript, PERLScript, PScript, and of course, Python.

The object model defined by ASP is different from the object model defined by Internet Explorer. The first thing you will notice is that ASP code has some special tags:

  • The <%@ language=Python %> tag defines that all scripting tags after that will, by default, belong to Python.

  • The <% %> tag is equivalent to <script> </script>.

  • <%= %> allows you to replace part of the contents to be displayed with the value of a variable. For instance,

    								
    <%
    name = "Andre" %>
    Whassup <%= name %> !
    
    							

There is no restriction on the commands that you can execute on a ASP page because all the execution takes place at the Server. Thus, in theory there would be no need for high security procedures. However, there is just as much need for security in ASP files as in CGI script when you are making use of untrusted input. The fact that there is no sandbox means you have to be especially careful not to compromise your system.

Note

ASP files are stored in files with the .asp extension.



One last detail about Python/ASP programs is that the print statement does not send the information to the screen. You need to use ASP's object model Response.Write() function to do it, as you can check in the following example.

						
<%@ language=Python %>
<%
text = "this text here does not use the print command" %>
A curious fact is that <%= text %>.
<br>
Note that we still need to pay attention to the indentation in this code.
<br>
The next code block lists all the server variables.
<br><br>
<%
for k in Request.ServerVariables:
    v = Request.ServerVariables(k)
    Response.Write("<b>%s</b>=" % (k))
    Response.Write("%s<br><br>" % (v))
%>

					

Of course, you could fix the print statement problem with the following code to make print work again.

						
class ASPStdout:
    def write(self, bytes):
        Request.Write(bytes)
    def writelines(self, lines):
        for line in lines: self.write(line)
sys.stdout = ASPStdout()

					

In case you want to try something different, Microsoft Visual Interdev, which is a very popular tool for ASP development, can be integrated with Python for Windows. Although it doesn't have any specific knowledge about .py files, it doesn't expose any problems when using them.

Using its working environment, you can test and debug Python's active scripts. Another possible option that you have is to use a free debugger that can be found at http://msdn.microsoft.com/scripting.

See http://starship.python.net/crew/pirx/asp/py_asp.html for more details about using Python with ASP.

Python Server Pages

Python Server Pages is a server-side scripting engine designed along the lines of Microsoft's Active Server Pages and Sun's Java Server Pages specification. The major difference between ASP and PSP is that PSP is written in 100% Java and portable to a wide variety of platforms, whereas Web applications written in ASP can be run only on Microsoft platforms. Python Server Pages uses JPython as its scripting language, which seems to be more appropriate for scripting Web sites than the Java language itself in Java Server Pages.

A major benefit to using PSP is the huge number of add-on modules available for both Python and JPython. You can access any module that is compatible with JPython from within your PSP application's pages. Because JPython is itself written in Java, you can access Java packages from your Python Server Pages application as well. For more information, check out the following:

Python Server Pages

http://www.ciobriefings.com/psp

JRun

JRun is the Java Servlet engine recommended for use with PSP.

http://www.allaire.com/products/jrun/index.cfm

JPython

JPython is the scripting language used by PSP.

http://www.jpython.org


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

Active Scripting 2nd 3rd 4th 5th 6th 7th
Active Server Pages (ASP)
      ActiveX scripting 2nd 3rd
ActiveX
      scripting 2nd 3rd
alert() function
applications
      Visual Interdev
ASP (Active Server Pages)
      ActiveX scripting 2nd 3rd
data
      sending to screen
debugging
      Active Scripts
executing
      script tags
form name
functions
      alert()
      Response_Write()
HTML (Hypertext Markup Language)
      interacting with Python code
HTML pages
      vs. Active Server Pages (ASP)
Hypertext Markup Language (HTML)
      interacting with Python code
IIS (Internet Information Server) 2nd
Internet Information Server (IIS) 2nd
JPython
names
      form
object_event notation
pages
     HTML
            vs. Active Server Pages (ASPs)
print statements
      sending data to the screen
programming languages
     Hypertext Markup Language (HTML)
            interacting with Python code
      JPython
programs
      Visual Interdev
Response_Write() function
screens
      sending data to
script tag
script tags
scripting
      Active 2nd 3rd 4th 5th 6th 7th
security
      Active Scripting
sending
      data to screens
software
      Visual Interdev
statements
     print
            sending data to the screen
tags
      script 2nd
Visual Interdev
whitespaces
Windows Scripting Host (WSH)
WSH (Windows Scripting Host)

© 2002, O'Reilly & Associates, Inc.