Re: [Tutor] Class vs. Static Methods

2005-06-23 Thread Alan G

> This is a neat trick. But can't this also be done with a static
method
> that accesses a static data attribute the same way?

I don't think so because the static mehod can only see
the attributes of Shape not of Line. It doesn't have
access to the cls value in Kent's code below...

> >>  @classmethod
> >>  def count(cls):
> >>try:
> >>  cls._count += 1
> >>except AttributeError:
> >>  cls._count = 1

So if it tried to incremet count every instance of every
kind of shape would increment the shape counter - which may
be what you want under some circumstances, but it wouldn't
know which of the subclasses was calling it so couldn't
access their counters.

I think thats right!?

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing what you've already printed

2005-06-23 Thread Alan G
> > Curses comes as standard on linux...
> >
>
>  More seriously, I seem to recall that on the contrary, the
> Windows Python distribution does not include the curses module

That's correct.

> have to use msvcrt[?] instead). I wonder why, because I'm pretty
sure
> I saw (C) curses-based applications running on Windows (NetHack is
> one, AFAIK).

There is a DOS implementation but
a) it is not complete and
b) it doesn't always work well.

But the problem for Python is that until someone builds a reliable
and complete C version for windoze the Python wrapper won't work...

I suspect part of the problem is that the DOS terminal, even
with ANSI mode switched on, which is not common nowadays, is
still pretty limited compared to a VT100/200 terminal
in terms of cursor control.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it?

2005-06-23 Thread Shuying Wang
I'm not sure what you're trying to do. But I run cgi scripts and make
xmlrpc requests with xmlrpclib with a connection with
xmlrpclib.Server(server_uri), though I'm only doing this client side.
I'm not running the server as cgi.

On 6/23/05, Ron Phillips <[EMAIL PROTECTED]> wrote:
>  
> I believe I've tried every setting known to man, in every script in every
> little scrap of documentation available. XMLRPC requests using
> SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI
> script, and I get system lock ups and that's all. No error codes; no
> response whatsoever. 
>   
> I am using Python 2.3, Windows XP. I have run other CGI scripts in the same
> directory, so I know that works. 
>   
> Has anyone used this successfully? Can you share demo server and client
> scripts -- just an echo function or something? 
>   
> Ron 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] samples

2005-06-23 Thread Alan G
> What I *am* looking for, if you have it or know of anyone who does,
is
> *simple* source code files (preferrably the entire game's code is in
> one .py file),

Thats unlikely to happen because its very bad practice and
Python tries to make it easy NOT to do that. Breaking code
into modules makes it easier to maintain and easier to reuse.

But the downside is trying to navigate it can be tricky
- especially when you don;t know which one is main...
Try a grep for __main__ to see if you can find the
if "__name__ === " trick. Or try grep for a def main.

In mainstream languages like C/Java you can use a feature
of vim/emacs called tags to navigate code across multiple
files, some IDEs have similar menu options, where you highlight
a function call and say 'go to source' and the IDE finds the
file with the definition... Makes browsing code much easier.

Of course better still is a design document!

> Does anyone have any little "gamelets" like these,

There are several games on Useless Python, including
my guessing games framework (which is from my book) and
the heavily commented code is zipped up on Useless
(hmgui.zip). But most of them don't use the pygame
framework.

HTH,

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-23 Thread Kent Johnson
Alan G wrote:
>>This is a neat trick. But can't this also be done with a static
> 
> method
> 
>>that accesses a static data attribute the same way?
> 
> 
> I don't think so because the static mehod can only see
> the attributes of Shape not of Line. 

Well, it can *see* Point._count and Line._count, it just doesn't know which one 
it should increment.

> It doesn't have
> access to the cls value in Kent's code below...
> 
> 
 @classmethod
 def count(cls):
   try:
 cls._count += 1
   except AttributeError:
 cls._count = 1
> 
> 
> So if it tried to incremet count every instance of every
> kind of shape would increment the shape counter - which may
> be what you want under some circumstances, but it wouldn't
> know which of the subclasses was calling it so couldn't
> access their counters.

Yes. In the absence of inheritance module methods, staticmethods and 
classmethods all have access to pretty much the same information. In the 
presence of inheritance, if you want to know the actual class a method was 
called on you need a classmethod.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGIXMLRPCRequestHandler doesn't actually work, does it?

2005-06-23 Thread Kent Johnson
Ron Phillips wrote:
> I believe I've tried every setting known to man, in every script in 
> every little scrap of documentation available. XMLRPC requests using 
> SimpleXMLRPCRequestHandler -- no problem. But try to run them as a CGI 
> script, and I get system lock ups and that's all. No error codes; no 
> response whatsoever.
>  
> I am using Python 2.3, Windows XP. I have run other CGI scripts in the 
> same directory, so I know that works.
>  
> Has anyone used this successfully? Can you share demo server and client 
> scripts -- just an echo function or something?

The server example in the docs works for me with one correction:

## cgi-bin/xmlrpc.py

from SimpleXMLRPCServer import CGIXMLRPCRequestHandler

class MyFuncs:
def div(self, x, y) : return x // y


handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()

##
Run a simple CGI server by opening a command line to the parent dir of cgi-bin 
and running
python -c "import CGIHTTPServer; CGIHTTPServer.test()"

## 

>From the command line:

 >>> import xmlrpclib
 >>> server = xmlrpclib.ServerProxy("http://localhost:8000/cgi-bin/xmlrpc.py";)
 >>> server.system.listMethods()
['add', 'div', 'pow', 'system.listMethods', 'system.methodHelp', 
'system.methodSignature']
 >>> server.add(1, 2)
3
 >>> server.pow(2, 10)
1024

Using Python 2.4.1 on Windows 2000

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] samples

2005-06-23 Thread Andrei
D. Hartley  gmail.com> writes:

> code, but it's made up of 46 different .py files, none of which seem
> to be the "main" game (lots of little modules, like an input box, a
> high score list, etc).  It's a lot harder for someone new to
> programming to read. 

Identify the main file (the one that you launch) and go from there. A search for
'main' might turn up something. Having all code in one big file makes it more
difficult to read for advanced users, but also for beginners. Make sure you use
a good editor with code outline support (outline of classes/methods), it makes
it easier to explore the code.

> Also, the reason that I would like to see several examples is that I
> would like to see how different people approach things like keeping
> track of the columns' being filled or not, how they approach timing
> questions, whether or not they give hints, that kind of thing.  I did
> game.  I have donwloaded tetris clones as well, and have made one
> myself (getting toward the falling objects idea, anyway), but they
> havent been on a static board which is filled at all times with
> objects. Nor have I ever, actually, done anything with mouse clicks
> (!!).

Except for tetris, you could also look at othello/reversi, five in a row,
checkers and chess. They deal with sequences of pieces, clicking on pieces to
move them and (depending on the implementation and target audience) hints. It
might be even more instructive to look at differences between the games than to
look at differences within a game.

> at my disposal, and what's more, I want to figure it out on my own.

I'd say you shouldn't be shy about borrowing ideas (and even code, if the
licence allows it) from other people. Usually the best way to learn is not by
starting with the development of the wheel.

> Does anyone have any little "gamelets" like these, or know of

I remember not too long ago there was a discussion on the pygame list about
developing a partygame-like system, with a framework capable of loading all
kinds of simple minigames. I don't know how far it is by now, but if you look in
the pygame mailing list archives you should be able to find it.

Yours,

Andrei


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getting an image out of a postgre database

2005-06-23 Thread Mike Hansen
Well, I've managed to get an image into a postgre database, but now I'm having 
trouble getting it out.

#! /usr/bin/env python

from pyPgSQL import PgSQL

def main():
 connectdb = PgSQL.connect('server:port:database:username:password')
 cur = connectdb.cursor()
 sqlStatement = """SELECT image from images where image_id = 1"""
 cur.execute(sqlStatement)
 rec = cur.fetchone()
 # TODO make temp file name include image_id.
 # TODO use tempfile module
 # TODO clean up old temp files
 tempFileName = "1.jpg"
 tempFile = open(tempFileName, "w")
 tempFile.write(rec[0])
 tempFile.close()
 cur.close()

 print "Content-type: text/html\n\n"
 print 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>

http://www.w3.org/1999/xhtml";>










"""

if __name__ == '__main__':
 main()

Traceback (most recent call last):
   File "./dispimage.py", line 39, in ?
 main()
   File "./dispimage.py", line 16, in main
 tempFile.write(rec[0])
TypeError: argument 1 must be string or read-only character buffer, not instance

So, rec[0] is an instance, but an instance of what? Since I needed to use the 
PgSQL.PgBytea method on the image before inserting it into the database, do I 
need to use a similar method to undo what PgBytea did to it, or am I 
incorrectly 
writing this binary data? I tried PgSQL.PgUnQuoteBytea(rec[0]), but that didn't 
work.

If this is more appropriate for another mail list, let me know.

Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] database app

2005-06-23 Thread Christian Wyglendowski
> -Original Message-
> 
> Hey there,

Hi,
 
> i have used the cgi module and dig it.
> heres the deal,
> my employer wants me to build a dynamic website that will 
> access a 
> database and display customer
> information on web. ok, easy enough.

Looks like some others have pointed you in the right direction as far as
interfacing with Access.

For the "web" part of your application, I'd recommend CherryPy
(http://www.cherrypy.org).  It lets you write web applications in
python.  Example:

from time import ctime
from cherrypy import cpg


header = """

%s

"""

footer = """


"""

class Site:
def index(self):
yield header % ('Index',)

yield "Here is a header\n"
yield "Here is a paragraph.  It is currently is %s.\n" %
(ctime(),)
yield "Here is a list of items\n"
yield "\n"
for num in range(10):
yield "Item %s\n" % (num,)
yield "\n"

yield footer
index.exposed = True

cpg.root = Site()
cpg.server.start()

---

That starts a webserver listening on port 8080 serving up your "index"
method at:
http://yourhost:8080/
or
http://yourhost:8080/index

Anyhow, CherryPy is very easy to get a hold of.

Good luck with your web application.

Christian
http://www.dowski.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Cookies and authorization

2005-06-23 Thread D. Hartley
Hello, everyone!

I am trying to go to a website, collect any and all cookies I receive
by going to that website, and then look at the cookies/print them.

So I did the following, from the cookie examples in the documentation:

import cookielib, urllib2
myjar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar))
x = opener.open("http://www.amazon.com";)

(I just did amazon because I knew it would leave cookies, as a sample). 

I'm not entirely sure how this works yet, because I'm just learning
about cookies now, but I am going to play with it and see what I can
find out.  My question for you is this:

The website I have to access and get the cookies from is, of course,
not amazon, it is:

http://www.pythonchallenge.com/pc/return/__.html

..where  is an actual word, but I'm not typing it so I
don't give away any spoilers to people who are working on the
challenges.

My problem is, when I plug this url into my sample code above, I get
an error ("HTTP Error 401: Authorization Required"), because normally
when you go to this url it makes you enter in a username and a
password.  Does anyone know how to get around this, either with code
commands I can change to embed the password/username, or a way I can
reformat the URL to *include* the password/username?  I remember
seeing something like this but I can't get it formatted right.  Say my
username is "guido" and my password is "python."

Any help would be much appreciated! Thanks :)

~Denise

(Also, there is lots of documentation on the cookie modules, and, to
my own great amusement, even examples(!!), but if anyone has a simple
howto for cookie processing, that would also be a great resource!)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Interesting problem

2005-06-23 Thread Smith, Jeff
Consider a class with a lt of properties.  I would like a member
function which generates a dictionary where the keys are the property
names and the values are the property values?

Is this clear?

How might I go about this?

Jeff
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cookies and authorization

2005-06-23 Thread Christian Wyglendowski
 

> -Original Message-
> 
> Hello, everyone!

Hi,



> My problem is, when I plug this url into my sample code above, I get
> an error ("HTTP Error 401: Authorization Required"), because normally
> when you go to this url it makes you enter in a username and a
> password.  Does anyone know how to get around this, either with code
> commands I can change to embed the password/username, or a way I can
> reformat the URL to *include* the password/username?  I remember
> seeing something like this but I can't get it formatted right.  Say my
> username is "guido" and my password is "python."

Try subclassing urllib.FancyURLopener and overriding the
prompt_user_passwd() method.  That should get you what you need :-)

> Any help would be much appreciated! Thanks :)
> 
> ~Denise

HTH,

Christian
http://www.dowski.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Jeremy Jones
Smith, Jeff wrote:

>Consider a class with a lt of properties.  I would like a member
>function which generates a dictionary where the keys are the property
>names and the values are the property values?
>
>Is this clear?
>
>How might I go about this?
>
>Jeff
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Like .__dict__?

Given this class:

  1 class Foo:
  2 def __init__(self, **kw):
  3 self.__dict__.update(kw)
  4


And creating an instance of it like this:

In [17]: foo = Foo(**{"bar":"b", "foo":"f", "bam":"bm"})


And accessing the properties of it like this:

In [18]: foo.foo
Out[18]: 'f'

In [19]: foo.bar
Out[19]: 'b'

In [20]: foo.bam
Out[20]: 'bm'


You can get all properties of it like this:

In [21]: foo.__dict__
Out[21]: {'bam': 'bm', 'bar': 'b', 'foo': 'f'}


Is this what you're looking for?

JJ
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cookies and authorization

2005-06-23 Thread Kent Johnson
D. Hartley wrote:
> My problem is, when I plug this url into my sample code above, I get
> an error ("HTTP Error 401: Authorization Required"), because normally
> when you go to this url it makes you enter in a username and a
> password.  
> 
> (Also, there is lots of documentation on the cookie modules, and, to
> my own great amusement, even examples(!!), but if anyone has a simple
> howto for cookie processing, that would also be a great resource!)

See http://www.voidspace.org.uk/python/articles.shtml#http for articles about 
authorization and cookies. Make sure you read the auth article to the end, it 
does it the hard way first to show what is going on...

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Christian Wyglendowski
 

> -Original Message-
> 
> Consider a class with a lt of properties.  I would like a member
> function which generates a dictionary where the keys are the property
> names and the values are the property values?
> 
> Is this clear?

I think so :-)

> How might I go about this?

I think you could simply use the special object attribute __dict__.  It
holds a dictionary of all properties and their values.

>>> class Something:
... def __init__(self, item1, item2, item3, item4, item5):
... self.item1 = item1
... self.item2 = item2
... self.item3 = item3
... self.item4 = item4
... self.item5 = item5
... 
>>> s = Something(42,52,55,1,54)
>>> s.__dict__
{'item2': 52, 'item3': 55, 'item1': 42, 'item4': 1, 'item5': 54}


> Jeff

HTH,

Christian
http://www.dowski.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Kent Johnson
Smith, Jeff wrote:
> Consider a class with a lt of properties.  I would like a member
> function which generates a dictionary where the keys are the property
> names and the values are the property values?
> 
> Is this clear?

No, actually :-)

Do you want the properties of the class (which are typically the methods of the 
class) or properties of an instance of the class (which is typically instance 
variables).

I'm guessing you want to see the instance values. These are already available 
in a dictionary, the __dict__ attribute of the instance:

 >>> class T:
 ...   def __init__(self, x, y):
 ... self.x = x
 ... self.y = y
 ...   def show(self):
 ... print 'x =', self.x, 'y =', self.y
 ...

dir(T) shows all the attributes of T, including inherited attributes:

 >>> dir(T)
['__doc__', '__init__', '__module__', 'show']

 >>> t=T(1, 2)

dir works for instances too. Notice it shows all accessible attributes which 
includes attributes of the class:

 >>> dir(t)
['__doc__', '__init__', '__module__', 'show', 'x', 'y']

But I think __dict__ is what you want:

 >>> t.__dict__
{'y': 2, 'x': 1}

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Smith, Jeff
I can see I wasn't clear :-)

Here's the basic framework of what I'm looking for.  Needless to say,
this is just an example and not the real problem which is quite
complicated and includes multiple classes.

What I'm looking for is the actual implementation of get_props_as_dict
which I've written here as pseudo-code

class MyClass:
def __init__(self):
self._var1 = val1
self._var2 = val2

var1 = property(lambda s: s._var1)
var2 = property(lambda s: s._var2)

def _var3(self):
return self._var1 + self._var2

var3 = property(_var3)

def getprops_as_dict(self):
d = dict()
for prop in properties:
d[prop_name] = prop_value
return d

Thanks,
Jeff

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Smith, Jeff
Sent: Thursday, June 23, 2005 2:01 PM
To: tutor@python.org
Subject: [Tutor] Interesting problem


Consider a class with a lt of properties.  I would like a member
function which generates a dictionary where the keys are the property
names and the values are the property values?

Is this clear?

How might I go about this?

Jeff
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Kent Johnson
Smith, Jeff wrote:
> I can see I wasn't clear :-)
> 
> Here's the basic framework of what I'm looking for.  Needless to say,
> this is just an example and not the real problem which is quite
> complicated and includes multiple classes.
> 
> What I'm looking for is the actual implementation of get_props_as_dict
> which I've written here as pseudo-code
> 
> class MyClass:
>   def __init__(self):
>   self._var1 = val1
>   self._var2 = val2
> 
>   var1 = property(lambda s: s._var1)
>   var2 = property(lambda s: s._var2)
> 
>   def _var3(self):
>   return self._var1 + self._var2
> 
>   var3 = property(_var3)
> 
>   def getprops_as_dict(self):
>   d = dict()
>   for prop in properties:
>   d[prop_name] = prop_value
>   return d

Still not that clear. What do you want to see when you call 
MyClass().getprops_as_dict() ?

Maybe this will give you some ideas:

 >>> class MyClass:
 ... def __init__(self, val1, val2):
 ... self._var1 = val1
 ... self._var2 = val2
 ... var1 = property(lambda s: s._var1)
 ... var2 = property(lambda s: s._var2)
 ... def _var3(self):
 ... return self._var1 + self._var2
 ... var3 = property(_var3)
 ... def getprops_as_dict(self):
 ... d = dict(self.__dict__)
 ... return d
 ...
 >>> m=MyClass(1,2)

Using just m.__dict__:

 >>> m.getprops_as_dict()
{'_var2': 2, '_var1': 1}

The inspect module might be some help:

 >>> import inspect
 >>> for k, v in inspect.getmembers(m):
 ...   print k, '=', v
 ...
__doc__ = None
__init__ = >
__module__ = __main__
_var1 = 1
_var2 = 2
_var3 = >
getprops_as_dict = >
var1 = 1
var2 = 2
var3 = 3


This inspects the class for actual properties and shows their values. It won't 
print simple attributes (in m.__dict__) or attributes defined by user-defined 
descriptors though:

 >>> for p in dir(m.__class__):
 ...   pp = getattr(m.__class__, p)
 ...   if isinstance(pp, property):
 ... print p, '=', getattr(m, p)
 ...
var1 = 1
var2 = 2
var3 = 3

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Smith, Jeff
Here would be the usage:

myinst = MyClass()
print myinst.getprops_as_dict()

would print

{'var1': 1, 'var2': 2, 'var3': 3}

Needless to say I want the instance values which might be different for
each instance.  I know that I could code it brute force, but I want to
be able to add properties without having to remember to update
getprops_as_dict().

For those who are interested, the dictionary created by
getprops_as_dict() will be fed to string.Template.substitute

Jeff

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, June 23, 2005 3:17 PM
To: Python Tutor
Subject: Re: [Tutor] Interesting problem

Still not that clear. What do you want to see when you call
MyClass().getprops_as_dict() ?

Maybe this will give you some ideas:

 >>> class MyClass:
 ... def __init__(self, val1, val2):
 ... self._var1 = val1
 ... self._var2 = val2
 ... var1 = property(lambda s: s._var1)
 ... var2 = property(lambda s: s._var2)
 ... def _var3(self):
 ... return self._var1 + self._var2
 ... var3 = property(_var3)
 ... def getprops_as_dict(self):
 ... d = dict(self.__dict__)
 ... return d
 ...
 >>> m=MyClass(1,2)

Using just m.__dict__:

 >>> m.getprops_as_dict()
{'_var2': 2, '_var1': 1}

The inspect module might be some help:

 >>> import inspect
 >>> for k, v in inspect.getmembers(m):
 ...   print k, '=', v
 ...
__doc__ = None
__init__ = > __module__ = __main__ _var1 = 1 _var2 = 2 _var3 = >
getprops_as_dict = > var1 = 1 var2 = 2 var3 = 3


This inspects the class for actual properties and shows their values. It
won't print simple attributes (in m.__dict__) or attributes defined by
user-defined descriptors though:

 >>> for p in dir(m.__class__):
 ...   pp = getattr(m.__class__, p)
 ...   if isinstance(pp, property):
 ... print p, '=', getattr(m, p)
 ...
var1 = 1
var2 = 2
var3 = 3

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cookies and authorization

2005-06-23 Thread Christian Wyglendowski
 

> -Original Message-
> 
> Christian, 
> 
> > Try subclassing urllib.FancyURLopener and overriding the
> > prompt_user_passwd() method.  That should get you what you need :-)
> 
> Well, I used urllib.FancyURLopener, and can open and look at 
> the url, like this:
> 
> import urllib
> opener2 = urllib.FancyURLopener({})
> f = 
> opener2.open("http://www.pythonchallenge.com/pc/return/romance.html";)
> f.read()
> 
> ..but to get at the cookies, I need to use urllib2.build_opener

Ah ha ... I should have been paying more attention :-)

> instead of urllib.FancyURLopener so that I can have access to
> urllib2.HTTPCookieProcessor, which does not seem to be an option in
> the regular urllib module?  Sorry if this seems like a dense question,
> I have little-to-no experience with cookies (and very little with
> urllib itself), so the examples sometimes leave me hanging!

It looks like the link that Kent suggested uses urllib2 and gives some
good examples of how to do authentication.  
 
> I'd appreciate any clarification you could give, or if you meant
> something else by your message?

I don't have much programming experience with cookies, so I don't have
much more to offer.  Good luck!

Christian
http://www.dowski.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Kent Johnson
Smith, Jeff wrote:
> Here would be the usage:
> 
> myinst = MyClass()
> print myinst.getprops_as_dict()
> 
> would print
> 
> {'var1': 1, 'var2': 2, 'var3': 3}
> 
> Needless to say I want the instance values which might be different for
> each instance.  I know that I could code it brute force, but I want to
> be able to add properties without having to remember to update
> getprops_as_dict().

OK, so will a variation on my last recipe work? This looks for property 
attributes of the class and gets the corresponding property on the instance:
  def getprops_as_dict(self):
return dict(pname, getattr(self, pname) 
  for pname in dir(self.__class__) 
if isinstance(getattr(self.__class__, pname), property))
)

Kent

> 
> For those who are interested, the dictionary created by
> getprops_as_dict() will be fed to string.Template.substitute
> 
> Jeff

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Alan G
> Consider a class with a lt of properties.  I would like a member
> function which generates a dictionary where the keys are the
property
> names and the values are the property values?

Use the force... :-)

Since Python uses dictionaries to store all those things
already there must be a suitable bit of black magic that will
serve it up on a plate.

Doing some reading around the innards of classes should shed
light on it.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Smith, Jeff
That's what I was looking for.  Although I couldn't get the below to
work, I went with a different mod of the original you gave:

def get_props_as_dict(self):
d = dict()
for entry in dir(self.__class__):
if isinstance(getattr(self.__class__, entry), property):
d[entry] = getattr(self, entry)
return d

Thanks!
Jeff

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, June 23, 2005 4:39 PM
To: Python Tutor
Subject: Re: [Tutor] Interesting problem


Smith, Jeff wrote:
> Here would be the usage:
> 
> myinst = MyClass()
> print myinst.getprops_as_dict()
> 
> would print
> 
> {'var1': 1, 'var2': 2, 'var3': 3}
> 
> Needless to say I want the instance values which might be different 
> for each instance.  I know that I could code it brute force, but I 
> want to be able to add properties without having to remember to update

> getprops_as_dict().

OK, so will a variation on my last recipe work? This looks for property
attributes of the class and gets the corresponding property on the
instance:
  def getprops_as_dict(self):
return dict(pname, getattr(self, pname) 
  for pname in dir(self.__class__) 
if isinstance(getattr(self.__class__, pname), property))
)

Kent

> 
> For those who are interested, the dictionary created by
> getprops_as_dict() will be fed to string.Template.substitute
> 
> Jeff

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Cookies and authorization - urllib2 vs urllib

2005-06-23 Thread D. Hartley
>From Christian: 

> Try subclassing urllib.FancyURLopener and overriding the
> prompt_user_passwd() method.  That should get you what you need :-)

Well, I used urllib.FancyURLopener, and can open and look at the url, like this:

import urllib
opener2 = urllib.FancyURLopener({})
f = opener2.open("http://www.pythonchallenge.com/pc/return/romance.html";)
f.read()

..but to get at the cookies, I need to use urllib2.build_opener
instead of urllib.FancyURLopener so that I can have access to
urllib2.HTTPCookieProcessor, which does not seem to be an option in
the regular urllib module?  Sorry if this seems like a dense question,
I have little-to-no experience with cookies (and very little with
urllib itself), so the examples sometimes leave me hanging!

Does anyone know a way to use an opener (like that above from urllib2)
that can process cookies AND can pass in a user/pass (like
FancyURLopener from urllib)? I'm not having much luck trying to do
both things at once!

Thanks,
Denise

P.S. Kent - thank you for the helpful tutorials on authentication,
they really cleared up the process a great deal.  The only problem is:

When I create an opener to process the cookies, it looks like this:

opener = 
urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar))

..where myjar is cookielib.CookieJar()

But in the examples for authentication, when I create the opener:

opener = urllib2.build_opener(authhandler)

..where authhandler is urllib2.HTTPBasicAuthHandler(passwordmanager)

So both use build_opener, but the thing I pass in, from what I am
looking at so far, has to be a cookie processor OR an authenticator. 
How can I do both at once?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] strip an email

2005-06-23 Thread Reed L. O'Brien
nephish wrote:
> Does anyone know how to strip everything off of an email?
> i have a little app that i am working on to read an email message and 
> write the
> body of a message to a log file.
> each email this address gets is only about three to five lines long.
> but i cannot seem to get just the body filtered through.
> i get all the headers, the path, what spam-wall it went through, etc...
> 
> any suggestions would be greatly appreciated .
> thanks
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

THis is from the email module. If I remember correctly text is the first
part of the payload in a multipart that has text.  So if you know it
comes in that way you can grab it with the optional i=0.  If it isn't
and you know it's coming in as a string just get the string and write it
to the log.

Then again someone else may have a better answer...


get_payload([i[, decode]])
Return a reference the current payload, which will be a list of
Message objects when is_multipart() is True, or a string when
is_multipart() is False. If the payload is a list and you mutate the
list object, you modify the message's payload in place.

With optional argument i, get_payload() will return the i-th element
of the payload, counting from zero, if is_multipart() is True. An
IndexError will be raised if i is less than 0 or greater than or equal
to the number of items in the payload. If the payload is a string (i.e.
is_multipart() is False) and i is given, a TypeError is raised.

Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding: header. When
True and the message is not a multipart, the payload will be decoded if
this header's value is "quoted-printable" or "base64". If some other
encoding is used, or Content-Transfer-Encoding: header is missing, or if
the payload has bogus base64 data, the payload is returned as-is
(undecoded). If the message is a multipart and the decode flag is True,
then None is returned. The default for decode is False.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Lists in List question

2005-06-23 Thread Phillip Hart
Hello,
 I've been using lists within lists for several
functions, but have been unable, in loop form, to extract data from
them or, in loop for, apply data to them.

Basically, when extracting data, it only runs 1 loop. Likewise, when initially assigning the data, it only runs 1 loop.

In the following example, the loop works once for x, and then a full loop (8 times) for y:

###    
rr1=[0,0,0,0,0,0,0,0]
rr2=[0,0,0,0,0,0,0,0]
rr3=[0,0,0,0,0,0,0,0]
rr4=[0,0,0,0,0,0,0,0]
rr5=[0,0,0,0,0,0,0,0]
rr6=[0,0,0,0,0,0,0,0]
rr7=[0,0,0,0,0,0,0,0]
rr8=[0,0,0,0,0,0,0,0]
results=[rr1,rr2,rr3,rr4,rr5,rr6,rr7,rr8]


x=0
y=0
while x<8:
    while y<8:
    value=x+y
    results[x][y]=value
    y=y+1
    x=x+1

x=0
y=0
while x<8:
  while y<8:
   
print "(",x,", ",y,") is
",results[x][y]   ###results[] is a
list of lists
    y=y+1
  x=x+1

###


The output is simply:
( 0 ,  0 ) is  0
( 0 ,  1 ) is  1
( 0 ,  2 ) is  2
( 0 ,  3 ) is  3
( 0 ,  4 ) is  4
( 0 ,  5 ) is  5
( 0 ,  6 ) is  6
( 0 ,  7 ) is  7


Thanks for the help. I'm sure this is another newbie mistake, but one I'd be greateful to see past.

-Phil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lists in List question

2005-06-23 Thread Danny Yoo


On Thu, 23 Jun 2005, Phillip Hart wrote:
> I've been using lists within lists for several functions, but have been
> unable, in loop form, to extract data from them or, in loop for, apply data
> to them.

[cut]

Hi Phillip,

Can you try checking for indentation?  Your code came out indented all on
the left margin, so it's difficult to see if:


> while x<8:
> while y<8:
> print "(",x,", ",y,") is ",results[x][y] ###results[] is a list of lists
> y=y+1
> x=x+1


represents the code block:

##
while x<8:
while y<8:
print "(",x,", ",y,") is ",results[x][y]
y=y+1
x=x+1
##


or if it represents the code block:

##
while x<8:
while y<8:
print "(",x,", ",y,") is ",results[x][y]
y=y+1
x=x+1
##

I'll assume for the moment that the second interpretation is what you
have, since the first one makes less sense.  *grin*

Also, you may want to see if you really want to use the "while" loop, or
if a "for" loop is more convenient.  The code as written is handling loop
indicies manually, and there may be a bug in the way you're using it.

Let's take the second code block for the moment:

##
while x<8:
while y<8:
print "(",x,", ",y,") is ",results[x][y]
y=y+1
x=x+1
##

The 'y' variable does not automatically reset here back to zero at any
given point, so the loop will only run through the first row of the
results.


Try and see if expressing the iteration with a 'for' loop is easier.
Because it has an explicit range(), 'for' often makes it easier to write
the code without having to deal with incrementing index variables by hand.


Best of wishes to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interesting problem

2005-06-23 Thread Kent Johnson
Smith, Jeff wrote:
> That's what I was looking for.  Although I couldn't get the below to
> work, I went with a different mod of the original you gave:
> 
> def get_props_as_dict(self):
> d = dict()
> for entry in dir(self.__class__):
> if isinstance(getattr(self.__class__, entry), property):
> d[entry] = getattr(self, entry)
> return d
> 

OK good! My code was untested and requires Python 2.4. I'm glad you could turn 
it into something that works for you.

Kent
> Thanks!
> Jeff
> 
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
> Behalf Of Kent Johnson
> OK, so will a variation on my last recipe work? This looks for property
> attributes of the class and gets the corresponding property on the
> instance:
>   def getprops_as_dict(self):
> return dict(pname, getattr(self, pname) 
>   for pname in dir(self.__class__) 
> if isinstance(getattr(self.__class__, pname), property))
> )
> 
> Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cookies and authorization - urllib2 vs urllib

2005-06-23 Thread Kent Johnson
D. Hartley wrote:
> P.S. Kent - thank you for the helpful tutorials on authentication,
> they really cleared up the process a great deal.  The only problem is:
> 
> When I create an opener to process the cookies, it looks like this:
> 
> opener = 
> urllib2.build_opener(urllib2.HTTPCookieProcessor(myjar))
> 
> ..where myjar is cookielib.CookieJar()
> 
> But in the examples for authentication, when I create the opener:
> 
> opener = urllib2.build_opener(authhandler)
> 
> ..where authhandler is urllib2.HTTPBasicAuthHandler(passwordmanager)
> 
> So both use build_opener, but the thing I pass in, from what I am
> looking at so far, has to be a cookie processor OR an authenticator. 
> How can I do both at once?

I think build_opener() can take multiple arguments:
cookieHandler = urllib2.HTTPCookieProcessor(myjar)
authhandler = urllib2.HTTPBasicAuthHandler(passwordmanager)
opener = urllib2.build_opener(cookieHandler, authhandler)

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQL Connection Function (Solution)

2005-06-23 Thread Don Parris
On Wed, 22 Jun 2005 15:06:22 -0400
Python <[EMAIL PROTECTED]> wrote:

> On Wed, 2005-06-22 at 14:20 -0400, Don Parris wrote:
> > On Tue, 21 Jun 2005 19:13:43 -0400
> > Python <[EMAIL PROTECTED]> wrote:
> > 
> > 

Here's my solution, using the code Lloyd provided in a previous post:
The script that contains the MySQL functions that the end-user will use most
imports the file containing the connection code:

def connect( parm_name):
parms = db_parms[parm_name]
return SQLdb.connect( **parms)

The file containing the core db functions uses do_Query to handle the cursor
and results, and return the results back to the functions, which then
continue their job of outputting the results.

def do_Query(sqlCmd):
curs = conn.cursor()
curs.execute(sqlCmd)
results = curs.fetchall()
curs.close()
return results

 

def mbr_Roster(): 
# Make SQL string and execute it.
sqlCmd = "SELECT env_num, lst_name, fst_name FROM person\
where env_num is not null\
order by lst_name"
Results = do_Query(sqlCmd)

The above line calling do_Query can be pasted into each function, and
provides exactly what I need (so far).


 # iterate through resultset.
print 'The Church Membership Roster'
for record in Results:
print '%s . %s, %s' % record
# print record
mbrRoster = open('mbrRoster.txt', 'w')
cPickle.dump(Results, mbrRoster)
mbrRoster.close()
raw_input('Press ENTER to return to the menu.')

Due to the way the menu system is designed, raw_input allows me to hold the
output on the console screen until the user has verified the data that gets
written to the file.  Otherwise, the function returns control of the program
back over to the menu system, and the user is left looking at the menu after
seeing the output from the query flash on the screen for a second.

This may still be somewhat klunky, but it does what I need.  At the moment,
I'll leave well enough alone, but I would appreciate any feedback. 
Meanwhile, I appreciate the help and solutions offered.  Meanwhile, I do
need to go over some good examples of returning values, and passing
variables around.

Don
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://chaddb.sourceforge.net/
"Free software is like God's love - you can share it with anyone anytime
anywhere."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor