zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python3.x 的 CGIHTTPServer

2023-09-14 08:58:20 时间


在Python2.6版本里,/usr/bin/lib/python2.6/ 目录下会有 BaseHTTPServer.py, SimpleHTTPServer.py, CGIHTTPServer.py

但是在Python3.4里,就没有上面的3个文件,而是合闭到了 /usr/bin/python3.4/http/server.py文件里了。

在python2.6里启动CGI服务命令是:


$ python -m CGIHTTPServer 8080
在python3.4里则是:


$ python3.4 -m http/server --cgi 8080

端口号是可选参数。


前面有在博文里提到2.6里的CGIHTTPServer.py有bug。python2.6 CGIHTTPServer.py源码分析

看一下在3.4是怎么解决的。

打开 http/server.py 分析 CGIHTTPRequestHandler。

(1)修改了_url_collapse_path_split(path) 

122720_EDvT_243525.png

最后返回的不再是 (/ + /.join(head_parts), tail_part),而是整个整理好的完整路径,是个string。

如果传入的path为"/dir/../cgi-bin/sub/./hello.py?aa=12",那么返回的collapsed_path应该是:"/cgi-bin/sub/hello.py?aa=12"

(2)在调用_url_collapse_path()的 is_cgi() 也做了修改

123312_D0fJ_243525.png

值得注意的是L960在给_url_collapse_path()传path里,用了urllib.parse.unquote()。

130052_vKtO_243525.png

L916,找到第2个"/"的位置。L962,以"/"的位置将collasped_path拆成head, tail两部分。

如上,返回的collapsed_path="/cgi-bin/sub/hello.py?aa=12",那么head="/cgi-bin",tail="sub/hello.py?aa=12"

而self.cgi_info中保存的就是("/cgi-bin", "sub/hello.py?aa=12")

(3)修改了run_cgi()

124017_p1sb_243525.png

由于前面在 is_cgi() 中得到 self.cgi_info=("/cgi-bin", "sub/hello.py?aa=12"),那么在L981~982,dir="/cgi-bin",rest="sub/hello.py?aa=12",path="/cgi-bin/sub/hello.py?aa=12"

L983~L993的功能是将rest中的目录移到dir中去。执行后的结果是:dir="/cgi-bin/sub",rest="hello.py?aa=12"


后面的就没什么可讲述的了,与python2.6一致。


数据持久化技术(Python)的使用 - 传统数据库连接方式:mysql(PyMySQL) - ORM 模型:SQLAlchemy MyBatis、 Hibernate ## PyMySQL pip install pymysql ## 简单使用 利用 pymysql.connect 建立数据库连接并执行 SQL 命令(需要提前搭建好数据库): import pymysql
【Python】Python3之i18n 最近在完成阿里云MVP共创任务定pgAdmin4定制任务的时候,接触到了Python的本地化与国际化,了解了Python多语言化的基本知识,记录一下分享。其中涉及Python基础类库gettext,大家可访问link。
闲来无事,找点段子一乐呵,就逛到糗事百科,这次爬取没有什么难度,唯一值得说道的是增加了一点点的代码健壮性。 import requests from lxml import etree
李名赫 博主从事的是物联网行业,目前在某知名智能家居科技公司担任家庭智能中心研发主管。欢迎交流!