#!/usr/bin/env python<br><br>import cgi<br>import MySQLdb<br>from time import strftime<br><br># feedback_time = strftime("%Y-%m-%d %H:%M:%S") # Some test data to inset into the DB. Could be form data for example<br><br><br># connect<br>db = MySQLdb.connect(host="localhost", user="*****", passwd="************", db="leke_feedback")<br><br># create a cursor<br>cursor = db.cursor()<br><br>print "Content-type: text/htmlnn"<br><br>print '''<br><br><html><br><br><br><br><link rel="stylesheet" type="text/css" href="http://rebol.vlexo.net/index.css"><br><body><br>'''<br><br>print '''<br><div id="title">not sure</div><br><div id="menu">Python CGI Test</div><br><div id="mainText"><br><h2>Results:</h2><br>'''<br><br># parse the cgi post input<br>form = cgi.FieldStorage()<br><br># attach the post input you need to a variable to send to the DB<br>feedback_for_db = form["feedback_form_data"].value<br><br>if form.has_key("feedback_form_data") and form["feedback_form_data"].value != "":<br> # execute SQL statement - sends post input to the DB<br> cursor.execute("INSERT INTO feedback_table (user_input_field) VALUES (%s)", (feedback_for_db)) <br> print "<h2>Feedback has been sent</h2>"<br>else:<br> print "<h2>An error occured! Please contact repulse.monkey@gmail.com to get in touch.</h2>"<br><br>print'''<br></div><br><br><br><br>'''<br><br>feeding something into the form returns a...<br>500 Internal Server Error<br>...<br>blah, blah<br>...<br>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.<br><br>I ran a test using 'from time import strftime' and then the time stamp line which was commented out this time. It worked fine and I could see a date stamp recorded in the DB. <br>I took it out this time and added CGI form data instead. I get the error now. <br><br>Is there a blaringly obviously error in my python code causing the error?
Could someone check my python CGI script?
Started by leke, Jul 16 2009 01:41 AM
8 replies to this topic
#1
Posted 16 July 2009 - 01:41 AM
On my feed back page...<br><a href="http://rebol.vlexo.net/Feedback/feedback_form.htm" class="bbc_url" title="External link" rel="nofollow">http://rebol.vlexo.n...edback_form.htm</a><br>a form POST link points to my cgi script...<br><br>
#2
Posted 28 July 2009 - 02:14 PM
It would be a lot easier for you to check it yourself.
In all you scripts, you should have a catch-all try statement.
I have a similar "Leave a comment" feature on my website.
Actually, even better than this, is to put the try/except clause in another file. That way, when the main code does not parse correctly, it will give you a syntax error.
Go ahead and copy the try and the except statements into your script.
The one thing this try does not catch is syntax errors, but you can check syntax by running it locally (or Run>Check Module in IDLE). I checked, and there were no syntax errors.
Also, do you have the execute permission set for Everyone for the cgi? Make sure it's set to 755.
In all you scripts, you should have a catch-all try statement.
I have a similar "Leave a comment" feature on my website.
Actually, even better than this, is to put the try/except clause in another file. That way, when the main code does not parse correctly, it will give you a syntax error.
#!/usr/bin/env python
try:
print "Content-Type: text/html"
print
import cgi, cgitb, os, time, urllib
newline = "
n"
def appendwithsuffix(filepath, appendstr, suffix):
fr = open(filepath, 'r')
oldcontent = fr.read()
fr.close
newcontent = oldcontent[:-len(suffix)] + appendstr + suffix
fw = open(filepath, 'w')
fw.write(newcontent)
fw.close()
print "<html>"
print "<head>"
print '<link rel="icon" type="image/vnd.microsoft.icon" href="http://www.python.org/favicon.ico">'
print "<title>Submit Form</title>"
print '<meta http-equiv="refresh" content="1;url=/main">'
print "</head><body>"
q = os.environ["QUERY_STRING"]
ql = q.split('&')
if ql == ['']: ql = []
qd = {}
for x in ql:
sp = urllib.splitvalue(x)
qd= dict(qd.items()+[(sp[0],sp[1])] )
def q(x):
try: return qd[x]
except: return None
formfields = ['author', 'url', 'comment']
info = {'about':None, 'time':None}
for formfield in formfields: info[formfield]=None
if q('about'): info['about'] = q('about')
info['time'] = time.localtime(time.time()-7200)
form = cgi.FieldStorage()
for formfield in formfields:
if form.getvalue(formfield): info[formfield] = form.getvalue(formfield)
appendwithsuffix('commentlog.py', `info`+',n', "}")
print 'n<!--'
for x in info: print "info[" + `x` + "] == " + `info[x]` + "
"
print 'n-->'
def quotehtml(x): return x.replace('&', '&').replace('"', '"').replace('<', '<').replace('>', '>')
if not info['author']: info['author'] = '(anonymous)'
if not info['comment']: info['comment'] = ''
if info['url']:
if info['url'].find("://") == -1: info['url'] = 'http://'+info['url']
info['url'] = info['url'].replace('"', '%22')
info['fmttime'] = "%s/%s/%s %s:%s:%s PDT"%(info['time'][1], info['time'][2], info['time'][0], info['time'][3], str(info['time'][4]).zfill(2), str(info['time'][5]).zfill(2))
html = ''
html+= '<div>'
if info['url']: html += '<a alt="Go to %s's website." href="%s">'%(quotehtml(info['author']), info['url'])
html += quotehtml(info['author'])
if info['url']: html += '</a>'
html += ' <font color=gray><small>%s</small></font>
[indent]%s[/indent]</div>n
nn'%(quotehtml(info['fmttime']), quotehtml(info['comment']).replace("n", "
"))
appendwithsuffix('index.html', html, 'nn</body></html>')
print '<h1>Comment Submitted:</h1>n'
print html
print '
[url="/main"]Home[/url]'
print "</body>n</html>"
except:
import sys, cgi
exc_info = sys.exc_info()
print '<table bordercolor=#500000 bgcolor=#FFFFA0><tr><td>'
print '<style>h3 {color:#800000; background-color:#FFFFA0; font-family:verdana; font-size:15}</style>'
print '<style>pre {color:#901010; background-color:#FFFFc0; font-family:courier; font-size:15}</style>'
print '<p><h3>[b]Python Error[/b]</h3></p>'
cgi.print_exception(exc_info[0],exc_info[1],exc_info[2])
print '</td></tr></table></html>'
Go ahead and copy the try and the except statements into your script.
The one thing this try does not catch is syntax errors, but you can check syntax by running it locally (or Run>Check Module in IDLE). I checked, and there were no syntax errors.
Also, do you have the execute permission set for Everyone for the cgi? Make sure it's set to 755.
Edited by Sean Zhu, 30 August 2010 - 08:53 AM.
change to colorful "php" code
#3
Posted 28 July 2009 - 11:38 PM
As far as I know the Mysql extension in Python is not activated here on vlexo. That is why the second script works (which writes to an file) and the first does not as it tries to write to an mysql database. But please ask Eli our Administrator for clarification.
Regards,
Jan J
Jan J
#4
Posted 29 July 2009 - 10:22 AM
Thanks Sean for the error catching example. I haven't had a lot of coding experience so I appreciate the example you submitted.
Jan, Sean's example is fine for what I need. Thanks for letting me know about the DB thing though
Jan, Sean's example is fine for what I need. Thanks for letting me know about the DB thing though
#6
Posted 30 July 2009 - 11:41 AM
What is MySql? What is DB? Just wondering.
#7
Posted 30 July 2009 - 10:49 PM
http://en.wikipedia.org/wiki/MySQL
an database is just some space to store data no, but it is a lot faster than writing data to an file or so.
an database is just some space to store data no, but it is a lot faster than writing data to an file or so.
Regards,
Jan J
Jan J
#8
Posted 11 February 2011 - 07:04 AM
Could someone explain how to start working with Python on this server?
#9
Posted 11 February 2011 - 08:34 AM
I found the reply and posted on http://vlexoforums.c...ic/9280-python/
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users












