Python CGI ProgrammingIn the Python CGI programming, we will learn how we can run the Python Script on the web; we will learn how Python file can be executed as CGI Script and discuss the its configuration of web-browser to Python script run as a CGI. Also, we will learn the following topics:
What is CGI?The word CGI is the acronyms of the "Common Gateway Interface", which is used to define how to exchange information between the web server and a custom script. The NCSA officially manages the CGI scripts. The Common Gateway Interface is a standard for external gateway programs to interface with the server, such as HTTP Servers. In simple words, it is the collection of methods used to set up a dynamic interaction between the server, and the client application. When a client sends a request to the webserver, the CGI programs execute that particular request and send back the result to the webserver. The users may submit the information in web browser by using HTML or This additional information can be the hostname of the client, the query string, the requested URL, and so on. The webserver executes and sends the output to the web browser (or other client application). Sometimes the server passes the data by a query string that is the part of the URL. A query string may not be conventionally a hierarchical path structure such as the following link. Python provides the CGI module, which helps to debug the script and also support for the uploading files through a HTML form. So here the question arises what does a Python CGI script output look like? The HTTPs server gives back the output as two sections separated by a blank line. The first section grasps the number of headers, notifying the client what kind of data is following. Let's understand the following example of generate the minimal header section in the Python CGI programming. Example - In the above example, the first statement says that, the server that html code follows; the second blank line indicates the header is ended here. Let's understand the following example of generating the minimal header section in the Python CGI programming. Example - Web BrowsingBefore understanding the CGI concepts, we should know the internal process of web page or URL when we click on the given link.
However, we can set a HTTP server so that whenever user requests in a particular dictionary, then it should be sent to the client; instead, it executed as a program and whatever the result is sent back for the client to display. This process is called the Common Gateway Interface or CGI and the programs are called CGI scripts. We can write the CGI programs as Python Script, PERL, Script, Shell Script, C or C++, programs, etc. Configure Apache Web server for CGIWe need to configure the Apache Web server in order to run the CGI script on the server. CGI Architecture![]() Using the cgi modulePython provides the cgi module, which consists of many useful built-in functions. We can use them by importing the cgi module. Now, we can write further script. The above script will stimulate an exception handler to show the detailed report in the web browser of occurred errors. We can also save the report by using the following script. The above feature of the cgi module is helpful during the script development. These reports help us to debug the script effectively. When we get the expected output, we can remove this. Previously, we have discussed the users save information using the form. So how can we get that information? Python provides the FieldStorage class. We can apply the encoding keyword parameter to the document if the form contains the non-ASCII character. We will find the content tag in the section in our HTML document. The FieldStorage class reads the form information from the standard input or the environment. A FieldStorage instance is the same as the Python dictionary. We can use the len() and all dictionary function in the FieldStorage instance. It overlooks fields with empty string values. We can also consider the empty values using the optional keyword parameter keep_blank_values by setting True. Example - In the above example, we have used the form ["name"], here name is key. This is used to extract the value which is entered by the user. We can use the getvalue() method to fetch the string value directly. This function also takes an optional second argument as a default. If the key is not present, it returns the default value. If the submitted form data have more than one field with the same name, we should use the form.getlist() function. It returns the list of strings. Look at the following code, we add the any number of username field, which is separated by commas. If the field is uploaded file, then it can be accessed by value attribute or the getvalue() method and read that uploaded file in bytes. Let's understand the following code if user upload the file. Example - Sometimes an error can interrupt the program while reading the content of the uploaded file (When a user clicks on Cancel Button or Back Button). FieldStorage class provides the done attribute to set to the value -1. If we submit the form in the "old" format, the item will be instances of the class MiniFieldStorage. In this class, the list, file, and filename attributes are always None. Generally, the form is submitted via POST and contains a query string with both FieldStorage and MiniStorage items. Here, we are defining the FieldStorage attribute in the following table.
The FieldStorage instance uses the many built-in methods to manipulate the users' data. Below are a few FieldStorage's methods. FieldStorage Methods:
Running First Python File as CGIIn this section, we will discuss how can run the CGI program over the server. Before doing this, we must ensure that our system has the following configuration-
If you already have the XAMPP server in your system then you can skip this part. Installing the XAMPP serverXAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl, and it provides the localhost server to test or deploy websites. Generally, it gives the two essential components for its installation, first is - Apache that creates a local server and MySQL, which we can use a database. Follow the below steps to install xampp. Step - 1: Visit its official website (https://www.apachefriends.org/download.html) and download the latest version. ![]() Step - 2: Once the download is complete, click on the run button. ![]() Step - 3: Now, Click on the Next Button. ![]() Step - 4: Next, it will display the xampp components. We can remove some of these but we will install all components of xampp, it won't affect our application. ![]() Step - 6: Now, our set up is ready to install, start the installation by clicking the Next button. ![]() It will take away on the webserver and start installing all packages and files. ![]() Step - 7: Here, the download has completed. Select your desire language, and then, it will display the following dashboard of xampp. ![]() Python InstallationTo install the Python, visit out Python installation guide (https://www.w3cschoool.com/how-to-install-python). First CGI ProgramWe have created a new folder called example in xampp's htdocs folder. Then, we write a Python script, which includes the HTML tags. Let's see the following directory structure and the demo.py file. ![]() demo.py And, its directory structure as follow. ![]() Type the localhost/example/demo.py into the web browser. It will display the following output. ![]() Note - We need to start the Apache server then execute the CGI script. Our script demo.py will run on host 127.0.0.1 by default.Let's understand another example of CGI script. Example - 2: Structure of a Python CGI ProgramLet's understand the following structure of the program.
Legend of SyntaxesWhen scripting a CGI program in Python, take note of the following commonly used syntaxes. HTML HeaderIn the above program, the line Content-type:text/html\r\n\r\n is a portion of the HTTP, which we will use in our CGI programs.
CGI Environment VariablesWe should remember the following CGI environment variable along with the HTML syntax. Let's understand the commonly used CGI environment variables.
Functions of Python CGI ProgrammingThe CGI module provides the many functions to work with the cgi. We are defining a few important functions as follows.
Debugging CGI ScriptsFirst, we need to check the trivial installation error. Most of the time, the error occurs during the installation of the CGI script. In the beginning, we must follow the installation instructions and try installing a copy of this module file cgi.py as a CGI script. Next, we can use test() function from the script. Type the following code with a single statement. Advantages of CGI ProgrammingThere are various advantages of using CGI programming. Below are some of its advantages.
Disadvantages of CGIConsider the following disadvantages of CGI.
Common Problems and SolutionsWe can face problems during the implement the CGI script on the server. We have listed below the few common problems and their solutions.
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com