[FAQTS] Python Knowledge Base Update -- May 11th, 2000

Fiona Czuczman fiona at sitegnome.com
Thu May 11 16:38:30 CEST 2000


Hello All,

Below are the entries from the newsgroup that I've entered into 
http://python.faqts.com today.

cheers, Fiona Czuczman


## New Entries #################################################


-------------------------------------------------------------
Where can I find documentation for TKinter?
http://www.faqts.com/knowledge-base/view.phtml/aid/2717
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh, Ivan Van Laningham

You could start by looking here ->

http://www.python.org/topics/tkinter/doc.html

While /F's documentation is invaluable, online and free, there are two
other books which may help clarify the situation.

1)  If you're at a beginning level, try the final 8 chapters of my 
_Teach Yourself Python in 24 Hours_.

2)  If you're at a more advanced level take a look at John
Grayson's _Python and Tkinter Programming_.  John's writing style is
appealing, he covers the topics in admirable depth, and he gives clever
and entertaining examples.


-------------------------------------------------------------
Is there a progress bar given by Tkinter?
http://www.faqts.com/knowledge-base/view.phtml/aid/2718
-------------------------------------------------------------
Fiona Czuczman
Robert Hicks, John Grayson

This comes from John Grayson's book "Python and Tkinter
programming".

"""
A  basic widget for showing the progress
being made in a task.

"""

from Tkinter import *

class ProgressBar:
    def __init__(self, master=None, orientation="horizontal",
                 min=0, max=100, width=100, height=18,
                 doLabel=1, appearance="sunken",
   fillColor="blue", background="gray",
                 labelColor="yellow", labelFont="Verdana",
                 labelText="", labelFormat="%d%%",
                 value=50, bd=2):
 # preserve various values
 self.master=master
 self.orientation=orientation
 self.min=min
 self.max=max
 self.width=width
 self.height=height
 self.doLabel=doLabel
 self.fillColor=fillColor
        self.labelFont= labelFont
 self.labelColor=labelColor
 self.background=background
 self.labelText=labelText
 self.labelFormat=labelFormat
 self.value=value
 self.frame=Frame(master, relief=appearance, bd=bd)
 self.canvas=Canvas(self.frame, height=height, width=width, bd=0,
                           highlightthickness=0, background=background)
 self.scale=self.canvas.create_rectangle(0, 0, width, height,
      fill=fillColor)
 self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2,
        height / 2, text=labelText,
        anchor="c", fill=labelColor,
        font=self.labelFont)
 self.update()
 self.canvas.pack(side='top', fill='x', expand='no')

    def updateProgress(self, newValue, newMax=None):
        if newMax:
            self.max = newMax
        self.value = newValue
        self.update()

    def update(self):
 # Trim the values to be between min and max
 value=self.value
 if value > self.max:
     value = self.max
 if value < self.min:
     value = self.min
 # Adjust the rectangle
 if self.orientation == "horizontal":
     self.canvas.coords(self.scale, 0, 0,
       float(value) / self.max * self.width, self.height)
 else:
     self.canvas.coords(self.scale, 0,
                     self.height - (float(value) / 
self.max*self.height),
       self.width, self.height)
 # Now update the colors
 self.canvas.itemconfig(self.scale, fill=self.fillColor)
 self.canvas.itemconfig(self.label, fill=self.labelColor)
 # And update the label
 if self.doLabel:
            if value:
                if value >= 0:
                    pvalue = int((float(value) / float(self.max)) * 
100.0)
                else:
                    pvalue = 0
                self.canvas.itemconfig(self.label, text=self.labelFormat 
%
pvalue)
            else:
                self.canvas.itemconfig(self.label, text='')
 else:
     self.canvas.itemconfig(self.label, text=self.labelFormat %
self.labelText)
 self.canvas.update_idletasks()


-------------------------------------------------------------
Is there a simple cgi module for Python that can do redirect?
http://www.faqts.com/knowledge-base/view.phtml/aid/2741
-------------------------------------------------------------
Fiona Czuczman
Jarkko Torppa, Teemu Keskinarkaus, Apache FAQ, Fredrik Lundh

Using:

print "Status: 302 Moved"
print "Location: http://url.to.somewhere"

Results in:

'Premature end of script headers' errors in apache error_log whenever 
the script is used.  However, the browser is redirected to url.

Solution:

There might be a module somewhere, but it is so simple that it is not 
necessary.

Headerterminator (empty line) and body is missing from your cgi
script, add something like. Dunno if the body is necessary.

print
print '<html><head><title>302 go away</title></head>'
print '<body><p>go away</p></body>'

Documentation:

Here's what the apache FAQ has to say about this message:

http://www.apache.org/docs/misc/FAQ.html#premature-script-headers

"What does it mean when my CGIs fail with "Premature
end of script headers"? 

"It means just what it says: the server was expecting a complete
set of HTTP headers (one or more followed by a blank line), and
didn't get them."


-------------------------------------------------------------
Is there a way to escape special characters when inserting a string into a database?
http://www.faqts.com/knowledge-base/view.phtml/aid/2742
-------------------------------------------------------------
Fiona Czuczman
Lars Hoeyrup Jensen, Paul Boddie

You can use:

>>> import MySQLdb
>>> MySQLdb.escape_string("""some '"' quotes""")
'some \\\'\\"\\\' quotes'

Alternate:

Rather than using Python's value substitution in strings as suggested, 
it should be possible to use "bind variables" in MySQLdb like this:

  cursor.execute("SELECT * FROM MY_TABLE WHERE MY_COLUMN = %s", 
(my_column,))

Note the use of the Python/C style "%s", but note also that we aren't 
using such "placeholders" with Python's % operator - an additional tuple 
parameter is required. As a result, the database module should process 
the values in the tuple and hopefully get the database to bind the 
values to the query (or action) accordingly.

This is all just speculation on my part, however, as I have never really 
done any work with MySQL, but I do remember something about this in the 
MySQLdb documentation. Other database modules use different syntax for 
the placeholders; for example, Sybase products prefer "?", and replacing 
the placeholders in the above example would indeed make it work on 
Sybase products.

I would discourage the use of simple string substitution when building 
queries. After all, the database modules are there to make the handling 
of all kinds of values, and the issues surrounding them (such as quote 
escaping) transparent. If your database module doesn't support this kind 
of functionality then I would recommend either improving it so that it 
does, or finding another which does; I wouldn't consider modules which 
are deficient in this respect as being suitable for serious work.


-------------------------------------------------------------
How can I create an object at runtime, giving its module and class name?
http://www.faqts.com/knowledge-base/view.phtml/aid/2743
-------------------------------------------------------------
Fiona Czuczman
Fred Gansevles, Courageous, Martin Valiente

The simpelest way, without having to figure out which part of the 
"stringWithFullNameOfTheClass" is the module and which part is the class 
is to pass them both to a function, i.e.

    def classFromModule (module, className):
        mod = __import__ (module)
        return getattr (mod, className)

You can use this as follows:

    c = classFromModule (ModuleOfTheClass, NameOfTheClass)
    o = c ()

or, even:

    o = classFromModule (ModuleOfTheClass, NameOfTheClass)()

-- Instructive Comment -- (Courageous wrote)

A partial answer, without the module capability, using a different 
solution than above:

o=eval(className)()

In the other language that I'm familiar with, "eval" is expensive, so
I'm pretty sure the other poster's answer is better.  This is here for 
instructive purposes. Python eval() can be used to interpret any valid 
python expression which is currently in the form of a string. You 
probably should only make very judicious use of this function, but 
still...







More information about the Python-list mailing list