search
HomeBackend DevelopmentPython TutorialShare an example tutorial of PythonCGI programming

In the past week, I continued to learn Python online and came into contact with CGI programming in Python. The official definition of CGI is as follows:

CGI (Common Gateway Interface), a common gateway interface, is a program that runs on The server, such as: HTTP server, provides an interface with the client HTML page.

I am more interested in how powerful applications Python CGI can write, so I started to learn the programming part of Python directly. First, I need to configure the web server to support CGI. My computer has already The wamp integrated development environment is installed, so there is no need to install Apache. There are many blog posts on the Internet about how to configure under Apache, and they are in the Linux environment, but I think the content of the configuration file should not be There will be big changes, so I started my tinkering journey. It turns out that using Windows for development is really a pitfall.

According to the online learning website Python CGI, you must first set up the CGI directory and modify httpd.conf in the Apache configuration file

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

and thenModify the httpd.conf file as follows:

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options +ExecCGI
   Order allow,deny
   Allow from all</Directory>

Then add the .py suffix in AddHandler so that we can access .py The python script file at the end:

After doing all this, restart the server (Apache/Wamp) and write the first CGI program. The code is as follows:

test1.py

#!D:\Python27\python # -*- coding: UTF-8 -*-print "Content-type:text/html\r\n\r\n"print &#39;<html>&#39;print &#39;<head>&#39;print &#39;<title>Hello Word - First CGI Program</title>&#39;print &#39;</head>&#39;print &#39;<body>&#39;print &#39;<h2 id="Hello-nbsp-Word-nbsp-This-nbsp-is-nbsp-my-nbsp-first-nbsp-CGI-nbsp-program">Hello Word! This is my first CGI program</h2>&#39;print &#39;</body>&#39;print &#39;</html>&#39;

The content of the first line specifies the location of the script interpreter, which can be changed according to the path of your own installation

Then enter in the browser address bar: http://localhost/cgi-bin/test1.py

Then the browser access displays the following results:

Hello Word! This is my first CGI program

No problem

Then write a second program: hello_get.py

#!D:\Python27\python# -*- coding: UTF-8 -*-# CGI处理模块import cgi, cgitb 
# 创建 FieldStorage 的实例化form = cgi.FieldStorage() # 获取数据first_name = form.getvalue(&#39;first_name&#39;)last_name  = form.getvalue(&#39;last_name&#39;)print "Content-type:text/html\r\n\r\n"print "<html>"print "<head>"print "<title>Hello - Second CGI Program</title>"print "</head>"print "<body>"print "<h2 id="Hello-nbsp-s-nbsp-s">Hello %s %s</h2>" % (first_name, last_name)print "</body>"print "</html>"

Enter localhost/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI

However Instead of outputting

##Hello ZARA ALI

as stated on the website, the following error message appears


So I was puzzled. The configuration environment was the same and the codes were exactly the same. What was the problem? Then I searched for the Apache CGI configuration method under Windows, but the results were all under Linux. configuration method, so I had no choice but to reinstall wamp and then reconfigure the CGI environment. Then I did each of the above steps again, and then copied the code on the website to the

editor Then enter again in the browser:

http://localhost/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI

The result is still the above string of error prompts, so I looked at the prompt carefully, the general meaning is:

Server internal error

The server encountered an internal error or was unable to complete my request due to misconfiguration

Please contact the server administrator via email to inform them of this error and what you did before this error occurred. What operation

For more information, please check the server error log

Because of this, I firmly believe that it is Because I configured the server wrong, when I was at a loss, I suddenly thought that the first program test1 could run correctly even when I had not modified any configuration files. Could it be that this error had nothing to do with the configuration files, so I Try to remove the statement declaring the interpreter path in the first line of test1 and run it again. The same error appears in the browser


So I am very relieved, because this confirms my guess. It has nothing to do with the configuration of the server, because my script file has Error, so the server cannot respond to the request. If this is the case, then the error of hello_get.py is also the same. Then the problem is much simpler. Just check whether there are any errors in the code.

Here I want to reflect on one of my bad habits: when I try to run a routine on the website, I always press ctrl C and then ctrl V Copy and paste it into your own editor. Simple programs are fine, but complex programs with many code blocks have the consequences of this habit: incorrect indentation format, and then running errors. This problem exists in Python This is especially obvious, because Python has very strict requirements on indentation, so you must not copy and paste Python programs into your own programs. You must type code by code to ensure that the indentation is under your control.

When I say this, I understand that people have already seen the error in my hello_get.py file - I just didn’t type it myself. In fact, I have tried copying online before The C language code is put into VC++6.0. On the surface, the syntax seems to be completely correct, but there is always an error below, and the prompt is incomprehensible, so when I encounter this situation, I can only think of this reason. This also warns everyone that the code must be typed into your program letter by letter by yourself, otherwise there will be errors that are difficult to detect.

Finally, let’s talk about how to correctly configure wamp (Apache) under Windows to correctly execute CGI scripts. The steps are very simple:

Open httpd.conf

Change line 371

ScriptAlias /cgi-bin/ "D:/wamp/bin/apache/apache2.4.9/cgi-bin/"前面的#号去掉,就是解除注释,将后面引号里的D:/wamp/bin/apache/apache2.4.9/cgi-bin/改成自己的cgi-bin所在的路径

将387行引号里的内容也改成自己的cgi-bin所在的路径

保存之后重启服务器即可

【相关推荐】

1. 详解cgi向文本或者数据库写入数据实例代码

2. 分享在IIS上用CGI方式运行Python脚本的实例教程

3. 使用CGI模块建立简单web页面教程实例

4. 什么是CGI?详细介绍Python CGI编程

5. 详解XML与现代CGI应用程序的示例代码

6. FastCGI 进程意外退出造成500错误

The above is the detailed content of Share an example tutorial of PythonCGI programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.