Python 相当于基于 Perl 函数的 cgi 样式
Python equivalent of a Perl function-based cgi style
有人教我像这样使用 Perl cgi (CGI(':standard')):
#!/usr/local/bin/perl
use CGI qw/:standard/; # load standard CGI routines
print header, # create the HTTP header
start_html('hello world'), # start the HTML
h1('hello world'), # level 1 header
end_html; # end the HTML
当移动到 Python 时,我发现我必须这样做:
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word</title>'
print '</head>'
print '<body>'
print '<h1>Hello Word!</h1>'
print '</body>'
print '</html>'
Python 是否可以像在 Perl 中那样使用基于函数的 cgi 方法?在尝试创建这样一个包时,您预计会遇到哪些主要挑战(如果不存在的话)?
这是使用 bottle
Python web framework 以 "function-based" 风格编写的 CGI 脚本:
#!/usr/bin/env python
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(server='cgi') # transform the application into a valid CGI script
要安装 bottle
模块,运行 通常的 pip install bottle
或 download a single bottle.py
file.
要尝试,请使脚本可执行:
$ chmod +x cgi-bin/cgi-script
在当前目录启动[开发] CGI服务器:
$ python3 -mhttp.server --cgi --bind localhost
打开页面:
$ python -mwebbrowser http://localhost:8000/cgi-bin/cgi-script/hello/World
除非你必须使用CGI,否则请考虑其他deployment options。
有人教我像这样使用 Perl cgi (CGI(':standard')):
#!/usr/local/bin/perl
use CGI qw/:standard/; # load standard CGI routines
print header, # create the HTTP header
start_html('hello world'), # start the HTML
h1('hello world'), # level 1 header
end_html; # end the HTML
当移动到 Python 时,我发现我必须这样做:
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word</title>'
print '</head>'
print '<body>'
print '<h1>Hello Word!</h1>'
print '</body>'
print '</html>'
Python 是否可以像在 Perl 中那样使用基于函数的 cgi 方法?在尝试创建这样一个包时,您预计会遇到哪些主要挑战(如果不存在的话)?
这是使用 bottle
Python web framework 以 "function-based" 风格编写的 CGI 脚本:
#!/usr/bin/env python
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(server='cgi') # transform the application into a valid CGI script
要安装 bottle
模块,运行 通常的 pip install bottle
或 download a single bottle.py
file.
要尝试,请使脚本可执行:
$ chmod +x cgi-bin/cgi-script
在当前目录启动[开发] CGI服务器:
$ python3 -mhttp.server --cgi --bind localhost
打开页面:
$ python -mwebbrowser http://localhost:8000/cgi-bin/cgi-script/hello/World
除非你必须使用CGI,否则请考虑其他deployment options。