必须使用哪种Content-type来编写Python CGI程序?
在编写Python CGI程序时,需要指定Content-type,来告诉Web服务器返回的数据类型,以便正确地处理响应内容。
那么,到底应该使用哪种Content-type呢?以下是几个常见情况,以及针对不同情况应该使用的Content-type:
阅读更多:Python 教程
返回HTML页面
如果要返回一个HTML页面,那么应该设置Content-type为text/html:
#!/usr/bin/env python
# coding: utf-8
print("Content-type:text/html")
print()
print("<html>")
print("<head>")
print("<title>Hello, World!</title>")
print("</head>")
print("<body>")
print("<h1>Hello, World!</h1>")
print("</body>")
print("</html>")
返回JSON数据
如果要返回JSON格式的数据,那么应该设置Content-type为application/json:
#!/usr/bin/env python
# coding: utf-8
import json
data = {
"name": "Tom",
"age": 18,
"gender": "male"
}
print("Content-type: application/json")
print()
print(json.dumps(data))
返回XML数据
如果要返回XML格式的数据,那么应该设置Content-type为text/xml:
#!/usr/bin/env python
# coding: utf-8
xml_data = """<?xml version="1.0" encoding="UTF-8" ?>
<bookstore>
<book category="科幻">
<title>亚瑟王</title>
<author>斯蒂芬·金</author>
<year>1998</year>
<price>13.50</price>
</book>
<book category="计算机">
<title>Python学习手册</title>
<author>Mark Lutz</author>
<year>2019</year>
<price>29.99</price>
</book>
</bookstore>
"""
print("Content-type: text/xml")
print()
print(xml_data)
返回文件
如果要返回文件,那么应该设置Content-type为application/octet-stream,同时还需要设置Content-Disposition头:
#!/usr/bin/env python
# coding: utf-8
filename = "test.txt"
content = "Hello, World!"
print("Content-type: application/octet-stream")
print("Content-Disposition: attachment; filename=" + filename)
print()
print(content)
我们可以将上述代码保存为cgi脚本,然后通过浏览器访问该网址,就可以测试各种Content-type的使用效果。需要注意的是,不同的浏览器支持的Content-type可能有所差异,需要根据具体情况选择合适的Content-type。
结论
在编写Python CGI程序时,需要根据情况选择不同的Content-type,以便正确地处理响应内容。常见的几种Content-type包括text/html、application/json、text/xml和application/octet-stream等。需要根据具体情况选择合适的Content-type。