Premature end of script headers 或 End of script output before headers

在测试 Python DB-API 使用流程脚本时,访问出现如下错误:

查看 Apache 日志,错误信息如下:

Premature end of script headers: dblink.py

或者

End of script output before headers: dblink.py

dblink.py 脚本内容如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "数据库用户名", "数据库密码", "数据库", charset='utf8mb4')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()

通过调试发现,应该是没有标记 HTTP 头部信息结束导致,程序修改如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "数据库用户名", "数据库密码", "数据库", charset='utf8mb4')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Content-type:text/html"
print                               # 空行,告诉服务器结束头部
print "Database version : %s " % data

# 关闭数据库连接
db.close()

其中," Content-type:text/html" 为 HTTP 头部的一部分,它会发送给浏览器并告诉浏览器文件的内容类型,用 print 输出一个空行用于告诉服务器结束头部信息。

访问结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值