1

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>"
16
  • Why are you using CGI and not a web framework like Django, Tornado or Flask? Commented Nov 12, 2013 at 6:23
  • … or WSGI, which is specifically designed to be "CGI done Pythonically instead of 1990s-style". Commented Nov 12, 2013 at 6:24
  • 1
    Also, it is probably not a Good Idea to post your actual MySQL username and password on a public forum. Commented Nov 12, 2013 at 6:25
  • 1
    While we're at it, never ever ever put user strings into your SQL statements like that. Instead, use parameterized statements: sql = "INSERT INTO PERSON (F_Name, L_Name, Age, Gender) VALUES (%s, %s, %s, %s)", then cursor.execute(sql, (f_name, l_name, age, gender)). Commented Nov 12, 2013 at 6:25
  • 1
    @frb: I can't think of a better way to prevent SQL injection attacks than to give people an even easier way to take over your database. :) Commented Nov 12, 2013 at 6:26

2 Answers 2

2

The problem is that in HTTP, the headers have to end with a blank line. 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.

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. 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:

#!/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.). And it's a lot more flexible (you can log different messages at different levels, you can configure where the logs go—e.g., send them to your system log instead of a file in /tmp, etc.). 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).

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Now how do i debugg ?
@user2968229: The first thing to do is simplify your script—keep stripping things out until it either works, or no longer has anything to strip out. For example, if you remove all the form stuff and all the database stuff and just do the prints at the end, does it work? (One reason it might not is that some servers require you to end each line with \r\n rather than just \n.)
@user2968229. The second thing to do is to add logging into the script. For example, you can use the stdlib logging module, direct it to write to syslog or to a file (make sure it's one the web server's user has write access to!) or even to the database, and then add logging.info lines throughout your code to make sure it's running everything it should be.
removing all the database and form stuff prints the data on the web page. Someone told me to create a function in your code of debugging and check each and every line to what does it do and print that into some abc file
Now i am not getting to how do i do that ?
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.