/* jquery */ /* jquery accordion style*/ /* jquery init */

Understanding Web Server Python Scripts

HTML, CSS and JavaScript are known as client-side web languages because they run inside the web browser.

Other languages, for example PHP, run back on the web server. The good news is that another server-side web development language is Python.

In server-side mode the Python script files are copied to the appropriate folder in the web server's directory structure (refer to your web server documentation for this folder's name).

These Python script files are then referenced by calls embedded in the HTML web pages.

One typical use for server scripts is to extract the GET or POST parameter valves from HTTP requests. Another is to validate and process user-entered data on a web form.

HTML Form Example

In Python we can access web form data using the FieldStorage() method, from the cgi module.

Take a look at this HTML snippet from a simple web form:

<form method="POST" action="post.py" value="">
   Search: <input type="text" name="search">
   <input type="submit" name="Submit">

Inside the web form HTML code we have a text entry field named search and a Submit button.

The form tag itself contains an action parameter value that names a server-side Python script file, here it's post.py. This script is called when the Submit button is clicked.

Let's see what this post.py script might look like:

import cgi

data = cgi.FieldStorage() #initialise
txt = data.getvalue('search') #get search field value

After importing the cgi module we use it to call the FieldStorage() method and assign the returned value to a Python variable called data.

In the next line we use data and the getvalue() method to assign the search field data value to a Python variable called txt.

The txt variable can now be used for whatever purpose you like. For example to initiate a Google search request.

More Raspberry Pi Python Coding Tutorials

No comments: