思路
刚开始想着直接使用python的render_template函数,实验之后发现无法连接到服务器,放弃。
从头思考,发现 python cgi 的操作是用 print 输出 HTML 语句,这里使用网上的例子:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print "Content-type:text/html"
print # 空行,告诉服务器结束头部
print '<html>'
print '<head>'
print '<meta charset="utf-8">'
print '<title>Hello World - 我的第一个 CGI 程序!</title>'
print '</head>'
print '<body>'
print '<h2>Hello World! 我是来自菜鸟教程的第一CGI程序</h2>'
print '</body>'
print '</html>'
然后就想到是否可以直接读取 HTML 文件的内容到 cgi 文件中:
import os
BASE_DIR=os.path.abspath(__file__)
file = os.path.join(BASE_DIR,'login.html')
print("Content-type:text/html\n")
with open file as fd
sata=fd,read()
print(sata)
运行之后报错:
no such file or directory:
/home/桌面/c/htdocs/http.py/login.html
这里我的 HTML 文件是在htdocs目录下,但是获取的绝对路径是到py文件这里,所以需要获取上级目录,将代码修改之后:
import os
BASE_DIR=os.path.abspath(os.path.dirname(__file__))
file = os.path.join(BASE_DIR,'login.html')
print("Content-type:text/html\n")
with open file as fd
sata=fd,read()
print(sata)
运行程序,成功运行。