亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development Python Tutorial What is CGI? A detailed introduction to Python CGI programming

What is CGI? A detailed introduction to Python CGI programming

May 19, 2017 pm 12:42 PM

What is CGI

CGI is currently maintained by NCSA. NCSA defines CGI as follows:

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

Web browsing

In order to better understand how CGI works, we can start with the process of clicking a link or URL on a web page:

1. Use your The browser accesses the URL and connects to the HTTP web server.

2. After receiving the request information, the web server will parse the URL and check whether the accessed file exists on the server. If the file exists, it will return the content of the file, otherwise it will return an error message.

3. The browser receives information from the server and displays the received file or error message.

CGI programs can be Python scripts, PERL scripts, SHELL scripts, C or C++ programs, etc.

CGI Architecture Diagram

What is CGI? A detailed introduction to Python CGI programming

Web server support and configuration

Before you perform CGI programming, make sure that your Web server supports CGI and The CGI handler has been configured.

Apache supports CGI configuration:

Set the CGI directory:

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

All HTTP server execution CGI programs are saved in a pre-configured directory. This directory is called the CGI directory, and by convention, it is named /var/www/cgi-bin.

The extension of CGI files is .cgi, and python can also use the .py extension.

By default, Linux The cgi-bin directory where the server is configured to run is /var/www.

If you want to specify other directories for running CGI scripts, you can modify the httpd.conf configuration file as follows:

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

Add the .py suffix in AddHandler so that we can access it. Python script file ending with py:

AddHandler cgi-script .cgi .pl .py

The first CGI program

We use Python to create the first CGI program. The file name is hello.py and the file is located in /var/www/cgi -bin directory, the content is as follows:

#!/usr/bin/python# -*- coding: UTF-8 -*-print "Content-type:text/html"print                               # 空行,告訴服務(wù)器結(jié)束頭部print &#39;<html>&#39;print &#39;<head>&#39;print &#39;<meta charset="utf-8">&#39;print &#39;<title>Hello Word - 我的第一個(gè) CGI 程序!</title>&#39;print &#39;</head>&#39;print &#39;<body>&#39;print &#39;<h2>Hello Word! 我是來自菜鳥教程的第一CGI程序</h2>&#39;print &#39;</body>&#39;print &#39;</html>&#39;

After saving the file, modify hello.py and modify the file permissions to 755:

chmod 755 hello.py

What is CGI? A detailed introduction to Python CGI programming

##This hello.py The script is a simple Python script. The output content of the first line of the script "Content-type: text/html" is sent to the browser and tells the browser that the displayed content type is "text/html".

Use print to output a blank line to tell the server to end the header information.

HTTP header

The "Content-type:text/html" in the content of the hello.py file is part of the HTTP header. It will be sent to the browser to tell the browser about the file. Content type.

The format of the HTTP header is as follows:

HTTP 字段名: 字段內(nèi)容

For example:

Content-type: text/html

The following is a simple CGI script that outputs CGI environment variables:

#!/usr/bin/python# -*- coding: UTF-8 -*-# filename:test.pyimport osprint "Content-type: text/html"printprint "<meta charset=\"utf-8\">"print "<b>環(huán)境變量</b><br>";print "<ul>"for key in os.environ.keys():    print "<li><span style=&#39;color:green&#39;>%30s </span> : %s </li>" % (key,os.environ[key])print "</ul>"

GET and POST method

The browser client transmits information to the server through two methods, the two methods are the GET method and the POST method.

使用GET方法傳輸數(shù)據(jù)

GET方法發(fā)送編碼后的用戶信息到服務(wù)端,數(shù)據(jù)信息包含在請(qǐng)求頁面的URL上,以"?"號(hào)分割, 如下所示:

www.test.com/cgi-bin/hello.py?key1=value1&key2=value2


有關(guān) GET 請(qǐng)求的其他一些注釋:

GET 請(qǐng)求可被緩存

GET 請(qǐng)求保留在瀏覽器歷史記錄中

GET 請(qǐng)求可被收藏為書簽

GET 請(qǐng)求不應(yīng)在處理敏感數(shù)據(jù)時(shí)使用

GET 請(qǐng)求有長(zhǎng)度限制

GET 請(qǐng)求只應(yīng)當(dāng)用于取回?cái)?shù)據(jù)

簡(jiǎn)單的url實(shí)例:GET方法

以下是一個(gè)簡(jiǎn)單的URL,使用GET方法向hello_get.py程序發(fā)送兩個(gè)參數(shù):

/cgi-bin/test.py?name=菜鳥教程&url=www.runoob.com

以下為hello_get.py文件的代碼:

#!/usr/bin/python# -*- coding: UTF-8 -*-# filename:test.py# CGI處理模塊import cgi, cgitb 
# 創(chuàng)建 FieldStorage 的實(shí)例化form = cgi.FieldStorage() 
# 獲取數(shù)據(jù)site_name = form.getvalue(&#39;name&#39;)site_url  = form.getvalue(&#39;url&#39;)print "Content-type:text/html"printprint "<html>"print "<head>"print "<meta charset=\"utf-8\">"print "<title>菜鳥教程 CGI 測(cè)試實(shí)例</title>"print "</head>"print "<body>"print "<h2>%s官網(wǎng):%s</h2>" % (site_name, site_url)print "</body>"print "</html>"

文件保存后修改 hello_get.py,修改文件權(quán)限為 755:

chmod 755 hello_get.py

簡(jiǎn)單的表單實(shí)例:GET方法

以下是一個(gè)通過HTML的表單使用GET方法向服務(wù)器發(fā)送兩個(gè)數(shù)據(jù),提交的服務(wù)器腳本同樣是hello_get.py文件,hello_get.html 代碼如下:

<!DOCTYPE html><html><head><meta charset="utf-8"><title>菜鳥教程(runoob.com)</title></head><body>
<form action="/cgi-bin/hello_get.py" method="get">站點(diǎn)名稱: <input type="text" name="name">  <br />
站點(diǎn) URL: <input type="text" name="url" /><input type="submit" value="提交" /></form></body></html>

【相關(guān)推薦】

1.?詳解cgi向文本或者數(shù)據(jù)庫寫入數(shù)據(jù)實(shí)例代碼

2.?分享在IIS上用CGI方式運(yùn)行Python腳本的實(shí)例教程

3.?使用CGI模塊建立簡(jiǎn)單web頁面教程實(shí)例

4.?分享一個(gè)PythonCGI編程的實(shí)例教程

5.?詳解XML與現(xiàn)代CGI應(yīng)用程序的示例代碼

6.?FastCGI 進(jìn)程意外退出造成500錯(cuò)誤

The above is the detailed content of What is CGI? A detailed introduction to Python CGI programming. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

PHP integrated AI emotional computing technology PHP user feedback intelligent analysis PHP integrated AI emotional computing technology PHP user feedback intelligent analysis Jul 25, 2025 pm 06:54 PM

To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python pandas melt example python pandas melt example Jul 27, 2025 am 02:48 AM

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

See all articles