简体   繁体   English

如何在python中使用mysql数据库调试cgi脚本。 我是如何调试的新手

[英]How do i debug my cgi script with mysql database in python. I am new to how to debugg

My code is showing some error when runing on server. 我的代码在服务器上运行时显示一些错误。 i checked the server error log and still not knowing what the exact it mean to say. 我检查了服务器错误日志,但仍然不知道要说的确切含义。 It says premature end of script. 它说脚本过早结束。 Now I want to debug my code to check each and every line of code to what does it do ? 现在我想调试我的代码以检查每一行代码是做什么的? How am i supose to debugg my code. 我该如何调试我的代码。 I am really new to this. 我真的很陌生。

#!/usr/bin/python
import cgitb
import MySQLdb
import cgi

cgitb.enable()

form = cgi.FieldStorage()

f_name = form.getvalue('firstname', '')
l_name = form.getvalue('lastname', '')
age = form.getvalue('age', 0)
gender = form.getvalue('gender', '')

db = MySQLdb.connect("localhost", "root", "gaurav", "Info")

cursor = db.cursor()

sql =  "INSERT INTO PERSON (F_Name, L_Name, Age, Gender) VALUES ('%s',' %s',' %d',' %s')" % (f_name, l_name, age, gender)

try:
    cursor.execute(sql)
    #print "Hello !!"
    #print "no of rows inserted: %d " % cursor.rowcount
    db.commit()

except:
    db.rollback()

db.close()

print "Content-type:text/html"
print "<html>"
print "<h1>DATABASE</h1>"
print "</html>"

The problem is that in HTTP, the headers have to end with a blank line. 问题是在HTTP中,标头必须以空行结尾。 So, instead of sending one header line and a 3-line body, you're sending four header lines, all but one of which are nonsense, and then exiting without ever finishing the headers. 因此,您将发送四个标题行,而不是发送一个标题行和一个3行的正文,除了其中的一个都是废话,然后不完成标题就退出。

So, the server complains that the script exited without finished writing the response. 因此,服务器抱怨脚本没有完成写响应就退出了。

Try this: 尝试这个:

print "Content-type:text/html"
print
print "<html>"
print "<h1>DATABASE</h1>"
print "</html>"

If you want to log every line of code, as you said in the comments, there are two ways to do it. 如您在注释中所述,如果要记录每一行代码,可以通过两种方法进行记录。

The quick&dirty way is to just open a file and write into it. 快速和肮脏的方法是只打开一个文件并将其write For example: 例如:

#!/usr/bin/python
import cgitb
import MySQLdb
import cgi

with open('/tmp/logfile.log', 'wb') as logfile:

    logfile.write('About to enable cgitb\n')
    cgitb.enable()

    logfile.write('About to create FieldStorage\n')
    form = cgi.FieldStorage()

    logfile.write('About to get firstname\n')
    f_name = form.getvalue('firstname', '')
    logfile.write('Firstname is {}. About to get lastname\n'.format(firstname))
    l_name = form.getvalue('lastname', '')
    logfile.write('Lastname is {}. About to get age\n'.format(lastname))
    # and so on

A cleaner way is to use the logging module that comes with Python: 一种更干净的方法是使用Python随附的logging模块:

#!/usr/bin/python
import cgitb
import MySQLdb
import cgi
import logging

logging.info('About to enable cgitb')
cgitb.enable()

logging.info('About to create FieldStorage')
form = cgi.FieldStorage()

This is simpler (no need to add \\n onto the end, the logger can format strings for you so you don't have to do it manually with .format or % , etc.). 这更简单(无需在末尾添加\\n ,记录器可以为您设置字符串格式,因此您不必使用.format%等手动进行.format )。 And it's a lot more flexible (you can log different messages at different levels, you can configure where the logs go—eg, send them to your system log instead of a file in /tmp, etc.). 而且它更加灵活(您可以在不同级别记录不同的消息,可以配置日志的位置,例如,将它们发送到系统日志而不是/ tmp中的文件等)。 And it's more robust (no need to worry about forgetting to close the file and losing the last log messages—note that in the non- logging example, I used a with statement to get the same effect, but that required indenting the whole program). 而且它更健壮(不必担心会忘记close文件并丢失最后的日志消息,请注意,在非logging示例中,我使用了with语句来获得相同的效果,但是需要缩进整个程序) 。

If you have time to work through the Logging Tutorial , you should do so. 如果您有时间完成“ 日志记录教程” ,则应该这样做。


Finally, if you're pretty sure some line is raising an exception, but you can't find the exception information anywhere in the server logs, here's how to log the exception: 最后,如果您确定某个行引发了异常,但是您无法在服务器日志的任何位置找到异常信息,则可以通过以下方法记录异常:

import traceback
try:
    the line that raises
except Exception:
    traceback.print_exc(None, logfile)
    raise

This captures the exception, prints out the exact same detailed traceback you would have gotten in a console interpreter session, but into the log file you opened earlier instead of to the console, then lets the exception propagate normally. 这将捕获异常,并打印出与在控制台解释器会话中完全相同的详细回溯,但是将其打印到您先前打开的日志文件中,而不是输出到控制台,然后让异常正常传播。

If you're using the logging module, you can use its own built-in exception logging, or if you want to customize things you can use sys.exc_info and traceback.format_exception to get a string (or series of strings) to log. 如果使用logging模块,则可以使用其自己的内置异常日志记录,或者如果要自定义内容,则可以使用sys.exc_infotraceback.format_exception获取要记录的字符串(或一系列字符串)。

By checking all the possibility of error i found a solution that sequence of import matters here 通过检查所有可能的错误,我找到了一个解决方案,在这里导入顺序很重要

it should be like 它应该像

import cgi
import MySQLdb

instead of 代替

import MySQLdb
import cgi

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我试图在 python 的 json 输出中获取与 name 关联的值。 我不知道该怎么做 - I am trying to get the values associated with name in my json output in python. I dont know how to do it 如何解决我的Python CGI脚本问题? - How can I troubleshoot my Python CGI script? 如何使用JavaScript从CGI脚本调用python函数? - How do I call a python function from a cgi script with javascript? 如何使用cgi接受带有python脚本的发布请求? - How do I accept post requests with a python script using cgi? 如何获得在 Apache2 中运行的 Python cgi 脚本 - How do I get a Python cgi script running in Apache2 在Python中使用urllib2。 如何获取我正在下载的文件的名称? - Using urllib2 in Python. How do I get the name of the file I am downloading? 我想将dataframe的值替换为python中的列名。 我应该怎么做? - I want to replace values of dataframe as a column name in python. How am I suppose to do that? 我是 web 在 Python 上刮擦的新手。 如何仅过滤链接和文章标题? - I am new to web scraping on Python. How to filter only link and article title? 如何将本地 Python 代码中的变量传递给写入 MySQL 数据库的远程 PHP 脚本? - How do I pass a variable from my local Python code to a remote PHP script that writes to a MySQL database? 如何在 python 中的字符串之间添加空格。 我正在从 ms access 数据库中获取数据 - how to add space between a string in python. I am fetching the data from ms access database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM