Re: [Tutor] urllib

2009-12-07 Thread Jojo Mwebaze
thanks, Senthil

On Mon, Dec 7, 2009 at 11:10 AM, Senthil Kumaran orsent...@gmail.comwrote:

 On Mon, Dec 07, 2009 at 08:38:24AM +0100, Jojo Mwebaze wrote:
  I need help on something very small...
 
  i am using urllib to write a query and what i want returned is
 'FHI=128%2C128
  FLO=1%2C1'
 

 The way to use urllib.encode is like this:

  urllib.urlencode({key:value})
 'key=value'
  urllib.urlencode({key:value,key2:value2})
 'key2=value2key=value'

 For your purpses, you need to construct the dict this way:

  urllib.urlencode({FHI:'128,128',FHO:'1,1'})
 'FHO=1%2C1FHI=128%2C128'
 


 And if you are to use variables, one way to do it would be:

  x1,y1,x2,y2 = 1,1,128,128
  fhi = str(x2) + ',' + str(y2)
  fho = str(x1) + ',' + str(y1)
  urllib.urlencode({FHI:fhi,FHO:fho})
 'FHO=1%2C1FHI=128%2C128'

 --
 Senthil

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] mod_python authentication

2009-12-07 Thread Rayon
How do I Check for an active login session on every page that requires
authentication

 

Been at this for days and it's holding me back can someone  plz help me with
some code examples. 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question : Creating cribbage game

2009-12-07 Thread Christopher schueler

My name is Chris Schueler and i am having some troubles with my Python 
programming

 

Our current project is to create the game of cribbage from scratch.

The only problem is we are not allowed to use classes, only user-defind 
functions and arrays. I was wondering if anybody could give me tips or pointers 
on adding codes or modifying some of my program

 

Here is my Program so far

I will also include a .py file of it incase this doesnt look legible

 

from random import*

 


def DisplayTitle():
print
print Welcome to Tech-Sauve Cribbage
print 
printInsctructions
print 
print 1) Only played with two players (for now)   
print 2) The program starts with a full deck of 52 cards
print 3) Deals out 6 cards to each player with a Suit letter
print 4) Then asks each player what 2 cards they want to discard to the 
crib
print 5) Then the program saves the crib in a temporary deck
print 6) Players start showing cards to get an ammount equal to 31
print 7) Once all the cards have been played, program counts the score
print 8) Then the program will count all possible scores in each hand
printAnd it will add the players points to their total score
print 9) First player to reach a score of 121 wins the game
#Gets players names
def GetPlayer1():
print
Player1 = str(raw_input(Player 1's name ))
return Player1
def GetPlayer2():
print
Player2 = str(raw_input(Player 2's name ))
return Player2
#Building the deck
def Build_Deck():
for R in range (0,52):
cardnumb = numbers[R]
cardsuit = suits[R]
card = str(numbers[R])+str(suits[R])
Deck.append(card)
return Deck,numbers,suits,card,cardnumb,cardsuit


#Variables Needed
numbers = [A,2,3,4,5,6,7,8,9,10,J,Q,K]*4
suits = [H,C,S,D]*13
suits.sort()
Deck = []
P1hand = []
P2hand = []
Crib = []
Cribcard = []
Cribsuit = []
P1_score = 0
P2_score = 0
Winner = 121
ele = 52
Deck,numbers,suits,card,cardnumb,cardsuit = Build_Deck()
for X in range(0,6):
Y = randint(0,ele)
draw = Deck[Y]
P1hand.append(draw)
Deck.pop(Y)
ele -= 1
for X2 in range (0,6):
Y1 = randint(0,ele)
draw2 = Deck[Y1]
P2hand.append(draw2)
Deck.pop(Y1)
ele -= 1
print
Top = randint(0,47)
Topcard = Deck[Top]
print
for count in range(0,2):
print P1hand
print
option = str(raw_input(Player 1,what CARD would you like to add to the 
crib?  CARDS 1 thru 6 ))
if option == 1:
Crib.append(P1hand[0])
P1hand.pop(0)
elif option == 2:
Crib.append(P1hand[1])
P1hand.pop(1)
elif option == 3:
Crib.append(P1hand[2])
P1hand.pop(2)
elif option == 4:
Crib.append(P1hand[3])
P1hand.pop(3)
elif option == 5:
Crib.append(P1hand[4])
P1hand.pop(4)
elif option == 6:
Crib.append(P1hand[5])
P1hand.pop(5)
print
for c2 in range(0,2):
print P2hand
print
option1 = str(raw_input(Player 2, what CARD would you like to add to the 
crib?  CARDS 1 thru 6 ))
if option1 == 1:
Crib.append(P2hand[0])
P2hand.pop(0)
elif option1 == 2:
Crib.append(P2hand[1])
P2hand.pop(1)
elif option1 == 3:
Crib.append(P2hand[2])
P2hand.pop(2)
elif option1 == 4:
Crib.append(P2hand[3])
P2hand.pop(3)
elif option1 == 5:
Crib.append(P2hand[4])
P2hand.pop(4)
elif option1 == 6:
Crib.append(P2hand[5])
P2hand.pop(5)

print Deck
print The TOP CARD is ,Topcard
print Player 1's Hand is ,P1hand
print Player 2's Hand is ,P2hand
print The 4 cards in the Crib are ,Crib
  
_
Ready. Set. Get a great deal on Windows 7. See fantastic deals on Windows 7 now
http://go.microsoft.com/?linkid=9691818from random import*

def DisplayTitle():
print
print Welcome to Tech-Sauve Cribbage
print 
printInsctructions
print 
print 1) Only played with two players (for now)   
print 2) The program starts with a full deck of 52 cards
print 3) Deals out 6 cards to each player with a Suit letter
print 4) Then asks each player what 2 cards they want to discard to the 
crib
print 5) Then the program saves the crib in a temporary deck
print 6) Players start showing cards to get an ammount equal to 31
print 7) Once all the cards have been played, program counts the score
print 8) Then the program will count all possible scores in each hand
printAnd it will add the players points to their total score
print 9) First player to reach a score of 121 wins the game
#Gets players names
def GetPlayer1():
print

Re: [Tutor] mod_python authentication

2009-12-07 Thread Alan Plum
On Mo, 2009-12-07 at 09:35 -0400, Rayon wrote:
 How do I Check for an active login session on every page that requires
 authentication
  
 Been at this for days and it’s holding me back can someone  plz help
 me with some code examples.

To understand sessions you first need to understand that HTTP is a
stateless protocol: you connect, send your request, receive a response
and the connection is closed.

Sessions add a layer of abstraction to create functionality the protocol
doesn't provide: multiple requests are grouped and treated as belonging
together.

There are several ways to accomplish this. The most straightforward way
would be remembering the client's IP and persisting variables as
relative to that IP -- problem is, IPs are unreliable, can be faked, and
do not provide a strong indicator of identity (while an IP only resolves
to one machine at a time, that machine may be acting as a gateway or
proxy for multiple users connected from other machines -- also, many IPs
are dynamically allocated thanks to ISPs).

Another method is putting the session's ID in the URLs you display to
your users. This creates a lot of problems, though: the session is only
maintained as long as the user uses exactly the URLs you provide (they
won't stay logged in, for example, if they bookmark a plain URL without
the session ID) and it may accidentally be shared between different
users by passing the URL verbatim (most users don't know enough about
URLs to clean session IDs out of them before sending them to other
people -- or don't care!).

The fix for this is usually to restrict the session to an IP (which is
why you often see the checkbox Restrict my session to this IP in
log-in forms), but that screws you over if your IP may randomly change
between consecutive requests and thus may break the illusion.

The most common and reliable choice is the good old session cookie: a
cookie (a small data string) is sent to the browser, containing just the
session ID (and, sometimes, non-critical data such as accessibility
settings if the website provides them). Because the browser is normally
restricted to a single user, the session ID is stored in a safe place --
except it isn't really because some people use e.g. internet cafés and
such which may not dispose of session data regularly. Also, a user may
access the same site from different devices or places, therefore
hoarding cookies for different sessions creating consistency problems.

Still, cookies are the easiest and most reliable way to store a session
ID and non-critical data. If you couple them with IP restrictions and a
conservative expiry time (i.e. duration of inactivity until the session
becomes invalid or expired and all associated variables are wiped) and
provide a fallback mechanism for users who disabled (or can't accept)
cookies, you should have most scenarios covered (although some sites
actually just stick to cookies and provide no fallbacks).

So once you've decided on a mechanism to persist the session ID, let's
see what a session actually is. In most cases you want to use them for a
log-in mechanism: the user enters their username and password,
successfully, and is welcomed by a personal greeting and a new
navigation subtree that was previously unavailable.

In this case it may be tempting to simply store the user's ID and log-in
state in a cookie, but that'd be incredibly silly because the user can
easily edit them if he knows about cookies (even worse things can happen
if you provide useful variables like is_admin: False). Instead you
should store those variables in a safe place (persist them) like a
database or special session files.

The session ID acts as a key to the session file or database entry, so
you need to make sure it's not easily guessable: many websites use very
long seemingly-randomly generated strings (a hash of the user's IP and
the millisecond time of the session's creation may yield good results).

Also, if you want to persist something, make sure it's easily
persistable. A string variable is child's play, an open file on the
other hand may cause locking problems and if you deal with large volumes
of data (e.g. binary file uploads kept in memory) you may quickly run
out of space.

If you don't want to have to deal with all of these considerations and
instead prefer something shrinkwrapped and ready for use, Google is your
friend. Depending on what you use there are plenty of CGI-compatible
packages and WSGI frameworks to choose from.


Cheers,

Alan Plum

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python authentication

2009-12-07 Thread aivars
Alan,
I am very impressed! This one goes to my knowledge base.
Thanks a lot.

2009/12/7 Alan Plum alan.p...@uni-koeln.de:
 On Mo, 2009-12-07 at 09:35 -0400, Rayon wrote:
 How do I Check for an active login session on every page that requires
 authentication

 Been at this for days and it’s holding me back can someone  plz help
 me with some code examples.

 To understand sessions you first need to understand that HTTP is a
 stateless protocol: you connect, send your request, receive a response
 and the connection is closed.

 Sessions add a layer of abstraction to create functionality the protocol
 doesn't provide: multiple requests are grouped and treated as belonging
 together.

 There are several ways to accomplish this. The most straightforward way
 would be remembering the client's IP and persisting variables as
 relative to that IP -- problem is, IPs are unreliable, can be faked, and
 do not provide a strong indicator of identity (while an IP only resolves
 to one machine at a time, that machine may be acting as a gateway or
 proxy for multiple users connected from other machines -- also, many IPs
 are dynamically allocated thanks to ISPs).

 Another method is putting the session's ID in the URLs you display to
 your users. This creates a lot of problems, though: the session is only
 maintained as long as the user uses exactly the URLs you provide (they
 won't stay logged in, for example, if they bookmark a plain URL without
 the session ID) and it may accidentally be shared between different
 users by passing the URL verbatim (most users don't know enough about
 URLs to clean session IDs out of them before sending them to other
 people -- or don't care!).

 The fix for this is usually to restrict the session to an IP (which is
 why you often see the checkbox Restrict my session to this IP in
 log-in forms), but that screws you over if your IP may randomly change
 between consecutive requests and thus may break the illusion.

 The most common and reliable choice is the good old session cookie: a
 cookie (a small data string) is sent to the browser, containing just the
 session ID (and, sometimes, non-critical data such as accessibility
 settings if the website provides them). Because the browser is normally
 restricted to a single user, the session ID is stored in a safe place --
 except it isn't really because some people use e.g. internet cafés and
 such which may not dispose of session data regularly. Also, a user may
 access the same site from different devices or places, therefore
 hoarding cookies for different sessions creating consistency problems.

 Still, cookies are the easiest and most reliable way to store a session
 ID and non-critical data. If you couple them with IP restrictions and a
 conservative expiry time (i.e. duration of inactivity until the session
 becomes invalid or expired and all associated variables are wiped) and
 provide a fallback mechanism for users who disabled (or can't accept)
 cookies, you should have most scenarios covered (although some sites
 actually just stick to cookies and provide no fallbacks).

 So once you've decided on a mechanism to persist the session ID, let's
 see what a session actually is. In most cases you want to use them for a
 log-in mechanism: the user enters their username and password,
 successfully, and is welcomed by a personal greeting and a new
 navigation subtree that was previously unavailable.

 In this case it may be tempting to simply store the user's ID and log-in
 state in a cookie, but that'd be incredibly silly because the user can
 easily edit them if he knows about cookies (even worse things can happen
 if you provide useful variables like is_admin: False). Instead you
 should store those variables in a safe place (persist them) like a
 database or special session files.

 The session ID acts as a key to the session file or database entry, so
 you need to make sure it's not easily guessable: many websites use very
 long seemingly-randomly generated strings (a hash of the user's IP and
 the millisecond time of the session's creation may yield good results).

 Also, if you want to persist something, make sure it's easily
 persistable. A string variable is child's play, an open file on the
 other hand may cause locking problems and if you deal with large volumes
 of data (e.g. binary file uploads kept in memory) you may quickly run
 out of space.

 If you don't want to have to deal with all of these considerations and
 instead prefer something shrinkwrapped and ready for use, Google is your
 friend. Depending on what you use there are plenty of CGI-compatible
 packages and WSGI frameworks to choose from.


 Cheers,

 Alan Plum

 ___
 Tutor maillist  -  tu...@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription 

Re: [Tutor] Question : Creating cribbage game

2009-12-07 Thread Tim Goddard
 Message: 2
 Date: Mon, 7 Dec 2009 02:30:30 -0400
 From: Christopher schueler chris_schue...@hotmail.com
 To: tutor@python.org
 Subject: [Tutor] Question : Creating cribbage game
 Message-ID: col115-w23640cb7712629d3a205fee0...@phx.gbl
 Content-Type: text/plain; charset=iso-8859-1


 My name is Chris Schueler and i am having some troubles with my Python 
 programming



 Our current project is to create the game of cribbage from scratch.

 The only problem is we are not allowed to use classes, only user-defind 
 functions and arrays. I was wondering if anybody could give me tips or 
 pointers on adding codes or modifying some of my program



 Here is my Program so far

 I will also include a .py file of it incase this doesnt look legible



 from random import*




 def DisplayTitle():
    print
    print Welcome to Tech-Sauve Cribbage
    print 
    print                Insctructions                
    print 
    print 1) Only played with two players (for now)   
    print 2) The program starts with a full deck of 52 cards
    print 3) Deals out 6 cards to each player with a Suit letter
    print 4) Then asks each player what 2 cards they want to discard to the 
 crib
    print 5) Then the program saves the crib in a temporary deck
    print 6) Players start showing cards to get an ammount equal to 31
    print 7) Once all the cards have been played, program counts the score
    print 8) Then the program will count all possible scores in each hand
    print    And it will add the players points to their total score
    print 9) First player to reach a score of 121 wins the game
 #Gets players names
 def GetPlayer1():
    print
    Player1 = str(raw_input(Player 1's name ))
    return Player1
 def GetPlayer2():
    print
    Player2 = str(raw_input(Player 2's name ))
    return Player2
 #Building the deck
 def Build_Deck():
    for R in range (0,52):
        cardnumb = numbers[R]
        cardsuit = suits[R]
        card = str(numbers[R])+str(suits[R])
        Deck.append(card)
    return Deck,numbers,suits,card,cardnumb,cardsuit


 #Variables Needed
 numbers = [A,2,3,4,5,6,7,8,9,10,J,Q,K]*4
 suits = [H,C,S,D]*13
 suits.sort()
 Deck = []
 P1hand = []
 P2hand = []
 Crib = []
 Cribcard = []
 Cribsuit = []
 P1_score = 0
 P2_score = 0
 Winner = 121
 ele = 52
 Deck,numbers,suits,card,cardnumb,cardsuit = Build_Deck()
 for X in range(0,6):
    Y = randint(0,ele)
    draw = Deck[Y]
    P1hand.append(draw)
    Deck.pop(Y)
    ele -= 1
 for X2 in range (0,6):
    Y1 = randint(0,ele)
    draw2 = Deck[Y1]
    P2hand.append(draw2)
    Deck.pop(Y1)
    ele -= 1
 print
 Top = randint(0,47)
 Topcard = Deck[Top]
 print
 for count in range(0,2):
    print P1hand
    print
    option = str(raw_input(Player 1,what CARD would you like to add to the 
 crib?  CARDS 1 thru 6 ))
    if option == 1:
        Crib.append(P1hand[0])
        P1hand.pop(0)
    elif option == 2:
        Crib.append(P1hand[1])
        P1hand.pop(1)
    elif option == 3:
        Crib.append(P1hand[2])
        P1hand.pop(2)
    elif option == 4:
        Crib.append(P1hand[3])
        P1hand.pop(3)
    elif option == 5:
        Crib.append(P1hand[4])
        P1hand.pop(4)
    elif option == 6:
        Crib.append(P1hand[5])
        P1hand.pop(5)
 print
 for c2 in range(0,2):
    print P2hand
    print
    option1 = str(raw_input(Player 2, what CARD would you like to add to the 
 crib?  CARDS 1 thru 6 ))
    if option1 == 1:
        Crib.append(P2hand[0])
        P2hand.pop(0)
    elif option1 == 2:
        Crib.append(P2hand[1])
        P2hand.pop(1)
    elif option1 == 3:
        Crib.append(P2hand[2])
        P2hand.pop(2)
    elif option1 == 4:
        Crib.append(P2hand[3])
        P2hand.pop(3)
    elif option1 == 5:
        Crib.append(P2hand[4])
        P2hand.pop(4)
    elif option1 == 6:
        Crib.append(P2hand[5])
        P2hand.pop(5)

 print Deck
 print The TOP CARD is ,Topcard
 print Player 1's Hand is ,P1hand
 print Player 2's Hand is ,P2hand
 print The 4 cards in the Crib are ,Crib


Unfortunately I had to read a few wiki pages of cribbage first, so my
understanding of the game is weak.



My suggestions:

Start with an outline of play (more to help us understand cribbage)
From my quick lesson, it sounds like you have so far:

Get player names (two players)
Create deck
Ask player which cards to put in crib

So for what you have now here are some suggestions:

You are creating variables numbers and suits in your global
namespace.  Then you use them in your Build_Deck function which is
fine, but then you are returning them at the end of the function,
overwriting the original variable definition.  I don't think it would
mess up your code but it is messy.  I also don't see where you are
using card, cardnumb, or cardsuit elsewhere.

I see your technique for chooosing cards at random, however the random
module includes a shuffle function so you could create 

Re: [Tutor] Question : Creating cribbage game

2009-12-07 Thread spir
Christopher schueler chris_schue...@hotmail.com dixit:

 
 My name is Chris Schueler and i am having some troubles with my Python 
 programming
 
  
 
 Our current project is to create the game of cribbage from scratch.
 
 The only problem is we are not allowed to use classes, only user-defind 
 functions and arrays. I was wondering if anybody could give me tips or 
 pointers on adding codes or modifying some of my program


From my limited experience in coding games. You have to model several distinct 
aspects:
* Constant data about the game, such as a card set.
* The game logic, mirroring the (real) game rules, ie what players can do, and 
what comes out of their actions.
* The game state, what's the situation at a given point in time, constantly 
modified by the above actions.
* Possibly some AI if the computer plays a role.
Note that first 2 points are predefined aspects (constants in the plain sense 
of the word).

Forbidding OO is a very bad thing because game modelling is precisely a 
programming domain in which this paradigm applies very naturally : every 
element in the game (state) is an object that can be modified through methods 
representing game rules.
Python dicts offer a powerful tool to represent kinds of objects, when used as 
records (lookup in wikipedia if you don't see what I mean). Moreover, python 
functions beeing namable objects, you can even attach relevant funcs to 
records so as to simulate methods. All you miss then is typical OO syntactic 
sugar where 'self' is automagically inserted as first argument of a method 
call. Instead of
   hand.popCard(card)
you need to write
   hand.popCard(hand, card)

Some more comments below in  your code.

 Here is my Program so far
 
 I will also include a .py file of it incase this doesnt look legible
 
  
 
 from random import*
 
  
 
 
 def DisplayTitle():
 print
 print Welcome to Tech-Sauve Cribbage
 print 
 printInsctructions
 print 
 print 1) Only played with two players (for now)   
 print 2) The program starts with a full deck of 52 cards
 print 3) Deals out 6 cards to each player with a Suit letter
 print 4) Then asks each player what 2 cards they want to discard to the 
 crib
 print 5) Then the program saves the crib in a temporary deck
 print 6) Players start showing cards to get an ammount equal to 31
 print 7) Once all the cards have been played, program counts the score
 print 8) Then the program will count all possible scores in each hand
 printAnd it will add the players points to their total score
 print 9) First player to reach a score of 121 wins the game

This is a single string to write. Use multiline strings inside triple quotes 
... and write in a single instruction. No need for a func.

 #Gets players names
 def GetPlayer1():
 print
 Player1 = str(raw_input(Player 1's name ))
 return Player1
 def GetPlayer2():
 print
 Player2 = str(raw_input(Player 2's name ))
 return Player2

This is twice the same func. Write a single one with a parameter representing a 
player, then call it twice. You'd better use a dict for each player because 
doubt the only relevant info is their name. Why not attach their hand, score, 
or whatever to the structures representing players?
player1 = {name:None, more:foo}
player2 = {name:None, more:foo}
def getPlayerName(player):
   # (raw_input already returns a string)
   player[name] = raw_input(Player 1's name )
getPlayerName(player1)
getPlayerName(player2)

 #Building the deck
 def Build_Deck():
 for R in range (0,52):
 cardnumb = numbers[R]
 cardsuit = suits[R]
 card = str(numbers[R])+str(suits[R])
 Deck.append(card)
 return Deck,numbers,suits,card,cardnumb,cardsuit

This func should only return Deck. Card cardnum, cardsuit are local variables 
used obly in the func, suits and numbers are input instead:

def Build_Deck(suits, number, card_count):
# 52 is also a predefined constant, namely here called card_count
for R in range (0,card_count):
cardnumb = numbers[R]
cardsuit = suits[R]
card = str(numbers[R])+str(suits[R])
Deck.append(card)
return Deck
... define constants about card: card_count, suits and numbers ...
Deck = Build_Deck(suits, number)

You'd better represent each card with a pair {suit:suit, number:number} so 
as to be able to compare their strength (unless this is irrelevant for this 
game).

 #Variables Needed
 numbers = [A,2,3,4,5,6,7,8,9,10,J,Q,K]*4
 suits = [H,C,S,D]*13
 suits.sort()
 Deck = []
 P1hand = []
 P2hand = []
 Crib = []
 Cribcard = []
 Cribsuit = []
 P1_score = 0
 P2_score = 0
 Winner = 121
 ele = 52

All non-null things above are constants that define the game. Empty and zero 
things are variables that will be part of the game state. You'd better separate 
this clearly.
You 

[Tutor] loops

2009-12-07 Thread Richard Hultgren
a = 0
b = 1
count = 0
max_count = 20
while count  max_count:
    count = count + 1
    # we need to keep track of a since we change it
    old_a = a# especially here
    old_b = b
    a = old_b
    b = old_a + old_b
    # Notice that the , at the end of a print statement keeps it
    # from switching to a new line
    print old_a,



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loops

2009-12-07 Thread Kent Johnson
Is there a question here?
Please skip the giant type size.

Kent

On Mon, Dec 7, 2009 at 2:53 PM, Richard Hultgren hultgren1...@yahoo.com wrote:
 a = 0
 b = 1
 count = 0
 max_count = 20
 while count  max_count:
     count = count + 1
     # we need to keep track of a since we change it
     old_a = a# especially here
     old_b = b
     a = old_b
     b = old_a + old_b
     # Notice that the , at the end of a print statement keeps it
     # from switching to a new line
     print old_a,


 ___
 Tutor maillist  -  tu...@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] functions--how long is too long?

2009-12-07 Thread Che M

I have some functions that seem kind of long to me.  One of them, with
white space, comments, print statements, and some commented-out lines,
is 118 lines long.  If I remove all that, it is 57 lines long.  I get the sense
that is inappropriately long for a Python function.  

The length of it is due to a number of if statements--things it needs to
check in terms of the state of the app at the time it is called.  So there
are a number of conditional (and subconditional) parts to it, and what
it does in response to those conditions.  In fact the word if appears in
it 12 times.  

I realize I can and should refactor parts that are used in other places
in the code, but I don't there are that many in some of these.  Is
there a better way to think about organizing this?

Thanks,
Che
  
_
Windows Live Hotmail gives you a free,exclusive  gift.
http://www.microsoft.com/windows/windowslive/hotmail_bl1/hotmail_bl1.aspx?ocid=PID23879::T:WLMTAGL:ON:WL:en-ww:WM_IMHM_7:092009___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions--how long is too long?

2009-12-07 Thread Luke Paireepinart
If your code is not sensitive information, it might help us if you post it
to pastebin or something so we can take a look.
In general though, functions should be as long as they need to be (and no
longer!).  57 lines is not inordinately long.  If it's hard for you to read,
though, you should refactor it.

I'd say my personal hard-limit for functions before I start refactoring is
probably around 150-200 lines.  But it's rare that functions get that long
anyway.
Remember to think of them as reusable units of code that do one specific
procedure.  Once you move into OO your functions will probably end up being
rather small as well, that paradigm encourages many small functions
interacting.

On Mon, Dec 7, 2009 at 7:37 PM, Che M pine...@hotmail.com wrote:

  I have some functions that seem kind of long to me.  One of them, with
 white space, comments, print statements, and some commented-out lines,
 is 118 lines long.  If I remove all that, it is 57 lines long.  I get the
 sense
 that is inappropriately long for a Python function.

 The length of it is due to a number of if statements--things it needs to
 check in terms of the state of the app at the time it is called.  So there
 are a number of conditional (and subconditional) parts to it, and what
 it does in response to those conditions.  In fact the word if appears in
 it 12 times.

 I realize I can and should refactor parts that are used in other places
 in the code, but I don't there are that many in some of these.  Is
 there a better way to think about organizing this?

 Thanks,
 Che

 --
 Windows Live Hotmail gives you a free,exclusive gift. Click here to
 download.http://www.microsoft.com/windows/windowslive/hotmail_bl1/hotmail_bl1.aspx?ocid=PID23879::T:WLMTAGL:ON:WL:en-ww:WM_IMHM_7:092009

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions--how long is too long?

2009-12-07 Thread Kent Johnson
On Mon, Dec 7, 2009 at 8:37 PM, Che M pine...@hotmail.com wrote:
 I have some functions that seem kind of long to me.  One of them, with
 white space, comments, print statements, and some commented-out lines,
 is 118 lines long.  If I remove all that, it is 57 lines long.  I get the
 sense
 that is inappropriately long for a Python function.

 The length of it is due to a number of if statements--things it needs to
 check in terms of the state of the app at the time it is called.  So there
 are a number of conditional (and subconditional) parts to it, and what
 it does in response to those conditions.  In fact the word if appears in
 it 12 times.

Perhaps you can extract some functions from the blocks that make up
the if statements, or move some of the conditionals themselves into
functions. Without seeing some code it is hard to be specific.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python authentication

2009-12-07 Thread Marc
 On Mo, 2009-12-07 at 09:35 -0400, Rayon wrote:
  How do I Check for an active login session on every page that
 requires
  authentication
 
 To understand sessions you first need to understand that HTTP is a
 stateless protocol: you connect, send your request, receive a response
 and the connection is closed.
 
 There are several ways to accomplish this. The most straightforward way
 would be remembering the client's IP 
 Another method is putting the session's ID in the URLs you display to
 your users. 
 The most common and reliable choice is the good old session cookie

While I agree with the cookie (as long as it has a short expiration),
another way to do this is by using expiring tokenization (credentials + some
unique data for the transaction) in the URL header (see section 14.8 at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).  Tokenization
substitutes some random string for confidential data (such as credentials).
The payment card industry uses this in the form of an authorization code for
card transactions.  Add to the data represented by the token some unique
data (maybe a random number or some data from the last transaction - it
doesn't matter as the token does not expose the data in any way) for each
http transaction so you have unique token in each header and you can get an
essentially stateful session with a method of checking authentication that
has some spoof protection built in.  Wrap it all in SSL/TLS and then you've
got something.  Granted, this requires some serious server side work, and is
probably not a good beginner exercise, but if this level is what you
need  I have never coded anything like this in Python, but I can see
abstractly how it could be done (I'm a novice with Python). If you're bored,
you can read http://www.shift4.com/pdf/TokenizationWhitePaper.pdf especially
sec1:7.  Ok, Ok, I'll shut up now - I've got to go play with some XML
anyhow...Thanks for listening.





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor