The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
Importing MySQLdb module causes malformed header error.. pls help!!!
Discuss Importing MySQLdb module causes malformed header error.. pls help!!! in the Python Programming forum on Dev Shed. Importing MySQLdb module causes malformed header error.. pls help!!! Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 5th, 2003, 07:55 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
Importing MySQLdb module causes malformed header error.. pls help!!!
Hello, im having this error while using Apache and the MySQLdb module.
[error] [client 127.0.0.1] malformed header from script. Bad
header=*** You don't have the (right): c:/program files/apache
group/apache/cgi-bin/fig28_18.py
I have connected all databases already. If I remove the import MySQL
statement, theres no problem. But i need to use the database. . what
could possibly be wrong???
pls help.. I have the MySQLdb installed in my Python directory
already..
#!c:\Python23\python.exe
import cgi
import MySQLdb
def printContent():
print "Content-type: text/html\n\n"
print
print """
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head><title>Registration results</title></head>
def printReply():
from convert import genPrime, genPrimeE
p1 = genPrime()
q1 = genPrime()
e1 = genPrimeE()
N1 = p1 * q1
M1 = (p1-1)*(q1-1)
print 'e1 %d, m1 %d' %(e1,M1)
while(e1 % M1 == 0):
e1 = genPrimeE()
connection = MySQLdb.connect( db = "try" )
cursor = connection.cursor()
cursor.execute("insert into trials (p,q,n,m) values
('p1','q1','n1','m1');")
authorList = cursor.fetchall()
cursor.close() # close cursor
connection.close()
printContent()
form = cgi.FieldStorage()
personInfo = { 'firstName' : form[ "firstname" ].value,
'lastName' : form[ "lastname" ].value,
'email' : form[ "email" ].value,
'phone' : form[ "phone" ].value,
'book' : form[ "book" ].value,
'os' : form[ "os" ].value,
'message' : form["message"].value }
printReply()
thanks!!
|

November 6th, 2003, 11:38 AM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
|
Hey kiranb, sorry for the lack of responce.. i've been having a little trouble setting up apache on my new XP box.
Anyway, i can't really run your script because i dont know where your blocks end. Could you attach the full page and the 'convert' module or pur your code inside a [ CODE ][ /CODE ] tag (without the spaces)
One thing i can tell you about your code; on line 10 you have a multiline string - in Python strings which start with """ or ''' can span mulitple lines - which is causing everything below line 10 in your program to be a string.. you can fix this in a few ways:
1. escape the middle " with a backslash
2. use the raw string flag r"""
3. close the string """ becomes """"""
The third is probably what your looking for
Mark.
__________________
programming language development: www.netytan.com – Hula
|

November 7th, 2003, 06:35 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
|
complete code...
hello mark, thanks for replying. This is the complete code:
Code:
#!c:\Python23\python.exe
import cgi
import sys
import MySQLdb
def printContent():
print "Content-type: text/html\r\n"
print
print """
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>Registration results</title></head>
<SCRIPT language="JavaScript">
<!--
function blur()
{
this.form.message.blur();
}
//-->
</SCRIPT>
<body>"""
def printReply():
connection = MySQLdb.connect( db = "try")
cursor = connection.cursor()
from convert import genPrime, genPrimeE
p1 = genPrime()
q1 = genPrime()
e1 = genPrimeE()
N1 = p1 * q1
M1 = (p1-1)*(q1-1)
print 'e1 %d,' %e1
print 'm1 %d' %M1
while(e1 % M1 == 0):
e1 = genPrimeE()
cursor.execute("insert into trials(p,q) values ('4','546');")
authorList = cursor.fetchall()
cursor.close()
connection.close()
from convert import convertToBlocks
list = convertToBlocks(form["message"].value)
from convert import encryptBlock
encList = []
for i in list:
x = encryptBlock(i,e1,N1)
encList.append(x)
nProd = 0
for i in encList:
nProd = (nProd + i) * 10000
personInfo['message'] = nProd
print """
<form method = "post" action = "http://127.0.0.1/cgi-bin/whee.py" name = "fig18">
<span style = "font-weight: bold">
The following information has been saved in our database:
</span><br />
<table style = "border: 0; border-width: 0;
border-spacing: 10">
<tr><td style = "background-color: yellow">Name </td>
<td style = "background-color: yellow">Email</td>
<td style = "background-color: yellow">Phone</td>
<td style = "background-color: yellow">OS</td>
<td style = "background-color: yellow">Message</td></tr>
<tr><td>%(firstName)s %(lastName)s</td><td>%(email)s</td>
<td>%(phone)s</td><td>%(os)s</td></td><td>%(message)s</td></tr>
</table>
<br /><br /><br />
<textarea rows="10" cols="50" onFocus="blur()" name="msg">%(message)s</textarea>
<input type = "submit" value = "next" >
</form></body></html>
""" % personInfo
def printFormError():
print """<span style = "color: red; font-size 15pt">
FORM ERROR</span><br />
You have not filled in all fields.
<span style = "color: blue"> Click the Back button,
fill out the form and resubmit.</span><br /><br />
Thank You."""
printContent()
form = cgi.FieldStorage()
try:
personInfo = { 'firstName' : form[ "firstname" ].value,
'lastName' : form[ "lastname" ].value,
'email' : form[ "email" ].value,
'phone' : form[ "phone" ].value,
'book' : form[ "book" ].value,
'os' : form[ "os" ].value,
'message' : form["message"].value }
printReply()
except KeyError:
printFormError()
_______________________________
this is the convert :
#generate a prime number (Oct.15,2003 1:15am)
def genPrime():
from random import randint
nPrime = 0
while (nPrime == 0):
nPrime = 1
i = 2
p = randint(50,100)
while ((nPrime!=0) & (i<p)):
if (p%i == 0):
nPrime = 0
else:
i = i+1
return p
def genPrimeE():
from random import randint
nPrime = 0
while (nPrime == 0):
nPrime = 1
i = 2
p = randint(10,50)
while ((nPrime!=0) & (i<p)):
if (p%i == 0):
nPrime = 0
else:
i = i+1
return p
#convert string to code. (a = 01, b=02, c=03 ... )
#(Oct.17,2003 8:00pm)
def convertToBlocks(word): #word = string to be converted
alphabet = { 'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8,
'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16,
'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24,
'y':25, 'z':26, ',':27, '.':28, '?':29, '0':30, '1':31, '2':32,
'3':33, '4':34, '5':35, '6':36, '7':37, '8':38, '9':39, '!':40,
' ':00, '@':41, '$':42, '(':43, ')':44, '-':45, '_':46, '/':47}
nLength = len(word)
i=0
nNum = 0
#print 'The String: %s' %word
while (i < nLength):
nNum = (nNum * 100) + alphabet[word[i]]
i = i + 1
#print '\nThe String converted: %d' %nNum #-- nNum contains the whole string converted to 1 number
nNumLen = len(word) * 2
while (nNumLen % 4 != 0):
nNum = nNum * 10
nNumLen = nNumLen + 1
#print 'The number is now divisible by 4: %d' %nNum #-- nNum is now divisible by 4
nTempLen = nNumLen
nTempNum = nNum
aBlocks = []
while (nTempNum != 0):
nDiv = 1
nCtr = nTempLen-4
while (nCtr > 0):
nDiv = nDiv * 10
nCtr = nCtr - 1
aBlocks.append(nTempNum / nDiv ) #divides the number into blocks of 4 and puts it in list aBlocks
nTempNum = nTempNum % nDiv
nTempLen = nTempLen - 4
print aBlocks
return aBlocks
# returns the d needed for decryption(Oct.16 9:00pm)
def getd(e,M): #M = (p-1)(q-1), e is prime
i=1
nFlag = 0
while ((i<M) & (nFlag == 0)):
if ((e*i) % M == 1):
nFlag = 1
else:
i = i+1
return i
#returns the encrypted code of a block (Oct.16 9:10pm)
def encryptBlock(nNum, e, N): #nNum = block of the msg, N = (pq), e is prime
i = 1
nProduct = 1
while (i <= e):
nProduct = nProduct * (nNum % N)
i = i + 1
return (nProduct % N)
Edit: formatted your code as described above 
Last edited by netytan : November 7th, 2003 at 10:04 AM.
|

November 7th, 2003, 10:47 AM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
Mmmm, this is proving pretty slow to crawl though.. i can't really test it since i dont have the database set up to connect too and etc.
I'm not really sure what your trying to do either, obviosuly your getting data from a form and printing that into the current page, but the database stuff seems pointless:
1. your adding a static value to the table.
2. you call fetchall but don't do anything with it.
What are your trying to do here? Maybe it would be easier to start over.. i don't see how importing MySQLdb could cause a malformed header error but hey
Oh your also importing sys when you don't need it. i wouldn't import from within functions either.. bad joo joo  . You might also want to add an if __name__ == '__main__' statment and call your page inside that..
Take care,
Mark.
|

November 7th, 2003, 11:33 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
|
Hi Mark,
to explain the code.. im actually just testing if a database works while using forms and linking one form to the other w apache. this explains the static data for the database.. hehe(sorry i dint explain that before). And, one thing wierd is that if i remove the "import MySQLdb" line and remove all the dbase conection statements, the code processes fine and the next html page is shown.
My major concern is storing all the values entered by the user from the previous page into a dbase for later use. I need to keep track of each person and his details..like a personal profile.
Im making something like a message board where many members can join and post and view messages but all of these messages are encypted and meant for one person.
I need to keep track of the data so that the user may view his/her profile or messages sent.. etc.
Is there another way to do this since databases are giving me a problem? The Cgi works fine w/o the mysqldb importation...
|

November 8th, 2003, 10:16 AM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
Well to answer your question yes MySQLdb will work with forms  the problem is definatly to do with your database stuff.. i trust you've read the MySQLdb tutorial on devshed? If not i'd suggest you do before you go any further. pop a try-final block around your database stuff and i'll bet it works.. in theory anyway
http://www.devshed.com/Server_Side/...ySQL/page1.html
there are a few alternatives to MySQL:
1. Pickle a dictionary object and recall it then needed (has a few drawbacks but reqires no thirdparty modules)
2. PostgreSQL or SQLite (a great module, i'm currently using it in a project of mine named Nickle; i'm pretty impessed so far)
For the encryption side of things you may want to check out some other ecryption tools, anyone who's read this could read your encryption w/o much trouble (you posted the keys  , i wouln't have asked you too post it if i'd known what it was for. sorry)
http://sourceforge.net/projects/pysqlite/
http://www.amk.ca/python/writing/pycrypt/pycrypt.html
Mark.
|

November 8th, 2003, 11:44 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
|
hello mark,
thanks for your quick replies. I really appreciate it since my project is due in 2 weeks. Its actually a school project and im this is the first time for me to use python... so im in the process of learning and doing the project.
Well since i still cant find whats wrong and i still get the previous error, im thinking i should try something else and move on to files. I never knew there was pickling in python. It might be one my solutions. And its less complicated i think.
Iv tried a sample code from a book but how do u store more than one objects? is it possible to save many in one file?
this is the code iv tried:
import pickle
obj = {'one':1, 'two':2}
file = open('filename','w')
pickle.dump(obj,file)
thanks,
kiran
|

November 8th, 2003, 12:41 PM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
|
Hi kir, Python has good pickle support and best of all its very easy to use!
As with most things the Python shell comes in very handy for showing this:
>>> import cPickle
>>> def some():
return 'some Python function!'
>>> def more():
print 'another Python function'
>>> functions = {'some':some, 'more':more}
>>> functions['some']()
'some Python function!'
>>> functions['more']()
another Python function
>>> cPickle.dump(functions, file('pickled.pk', 'w'))
>>> del functions
>>> functions
Traceback (most recent call last):
File "<pyshell#12>", line 1, in -toplevel-
functions
NameError: name 'functions' is not defined
>>> functions = cPickle.load(file('pickled.pk', 'r'))
>>> functions['some']()
'some Python fucntion!'
>>> functions['more']()
another Python fucntion
>>>
I used cPickle because thats what i'm used too, theres really no differance in the two modules but cPickle is faster than pickle.
Note: you can also store function objects inside lists and tuples too, i used a dictionary because it's a little easier to see whats happening and you used a dictionary in your own example.
This is just one way of storing multiple objects there may well be others but i havn't tested any i.e. appending to a pickled file?
|

November 8th, 2003, 12:51 PM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
Quote:
I really appreciate it since my project is due in 2 weeks. Its actually a school project and im this is the first time for me to use python... so im in the process of learning and doing the project.
Well since i still cant find whats wrong and i still get the previous error, im thinking i should try something else and move on to files. |
Don't give up  , read the MySQL tutorial and try a CGI script to just deal with that.. when you have that working all you have to do is add the forms (very simple).
If it wasn't a school project i'd write it for you lol (i have a bad habbit of doing that), it seems like an interesting but pretty simple project. Not sure if you could learn Python and write it in two weeks but hey  , what exactly was the brief or projevt you where set?
Continue from the previous shell:
>>> some = functions['some']
>>> some()
'some Python function!'
>>> more = fucntions['more']
>>> more()
another Python function
Mark.
|

November 10th, 2003, 10:54 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
The pickle module is working alright and ive decided to use that.  thanks.
Do you know how to access the current date? and eventually add 6 months to it...
|

November 10th, 2003, 11:36 AM
|
 |
Hello World :)
|
|
Join Date: Mar 2003
Location: Hull, UK
|
|
Ok if its working for you then  , what your looking for here is the time module:
>>> import time
>>> time.time()
1068485299.1670001
>>> hour = 60 * 60
>>> day = hour * 24
>>> week = day * 7
>>> time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + week * 4))
'Mon, 08 Dec 2003 17:33:13'
http://www.python.org/doc/current/lib/module-time.html
Mark.
|

November 10th, 2003, 05:21 PM
|
|
Contributing User
|
|
Join Date: Mar 2003
Posts: 325
Time spent in forums: 7 h 58 m 36 sec
Reputation Power: 11
|
|
I personally think it teaches bad practice to use flat files instead of a database. Database schema design and concepts are important for a good back end design, similarly to OO design bing more usable and offering better high level design and implementation rather than proceedural and functional programming. Its a shame you had such a time restriction that you had to convert to flat files.
If you ever use the db, may I suggest you simplify your code and use something like this :
File: dp.py
Code:
#!/usr/bin/python
import MySQLdb
### return a mysql cursor handle
def connect():
### set database parameters
host = "localhost"
user = "username"
pwd = "pass"
db = "db"
### connect
db = MySQLdb.connect(host, user, pwd, db)
### return the db object
return db
### this can be called on its own with a query as argument
### it returns the result
def executeQuery(query):
### create a db object
### if not in this file, use: "mydb = db.connect()"
mydb = connect()
### get the db handle
handle = mydb.cursor()
### execute the query
handle.execute(query)
### get the results
result = handle.fetchall()
### close the db connection
mydb.close()
### return the results
return result
Then to execute a query just use this:
Code:
import db
result = db.executeQuery("SELECT *FROM blah")
for row in result:
print row[0], row[1], ...... etc
Makes you code much more readable
|

November 25th, 2003, 04:40 AM
|
|
Junior Member
|
|
Join Date: Nov 2003
Posts: 6
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
thanks
Hi Mark and the rest who replied.
Thanks for all your help regarding python.. Im finally finished with my project. The pickle module really helped me to solve my database problem.
Iv made a something like a message board where people post encrypted messages meant for a single recipient. The members of the group also have a calendar to set appointments or schedules. Messages are digitally signed then encypted using rsa.
Well, thanks for all your responses and help. Im finally done! =)
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|