python cgi 不用框架向本地服务器返回HTML

思路

刚开始想着直接使用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)

运行程序,成功运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值