Adriaan Joubert
Adriaan Joubert

Reputation: 195

Display password from PostgreSQL database using web.py form

I am playing around with PostgreSQL and web.py and I have noticed that if I have a username and password in a database and given that the password may contain special characters that are members of string.printable, then when I want to print the queried password to the browser through a web.py template, something goes wrong with the character escaping and the password doesn't want to display. Instead the browser offers to download a text file (with no file extension) containing the password.

In my Python file:

class login:
    ...
    def POST(self):
        ...
        cursor.execute("SELECT password FROM tbl WHERE username = %s", (f['username'].value, ))
        realpassword = cursor.fetchone()
        realpassword = realpassword[0]
        ...
        return realpassword

The password appears correctly in the text file that downloads, but how do I display the password as text on the webpage?

Upvotes: 0

Views: 52

Answers (1)

pbuck
pbuck

Reputation: 4551

Python string.printable includes both vertical-tab \x0b and form-feed \x0c, neither of which are friends to browsers. Browsers assume they're receiving a file and offer to download it.

(string.printable isn't the same as ASCII.)

Instead of returning the raw realpassword, return repr(realpassword). Built-in repr() returns a "string containing a printable representation...", escaping control characters.

>>> import string
>>> print string.printable[-20:]
=>?@[\]^_`{|}~  



>>> print repr(string.printable[-20:])
'=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

Upvotes: 1

Related Questions