about python scripting
I have this code
class HNCS (ThreadingTCPServer):
def verify_request(self, request, client_address):
for key in connec开发者_JAVA技巧tions:
if connections[key].client_address[0] == client_address[0]:
if client_address[0] != '127.0.0.1':
return False
return True
def welcome(self):
return '''______________________________________________________
------------------------------------------------------
%s
______________________________________________________
------------------------------------------------------
* Server started %s
* Waiting for connections on port %i
''' % (gpl, ctime(), PORT)
I only can't figure out the line where it says if connections[key].client_address[0] == client_address[0]
how come we used client_address as an attribute after dictionary???
Perhaps the dictionary is storing values which are objects that happen to have a client_address member property?
In other words, the .client_address
there isn't the same thing as the client_address
passed in as an argument. Instead, it's the name of a field within a class that happens to be stored in connections[key]
.
Because the connections
dictionary may have an object with a client_address
attribute?
Like:
class SomeClass(object):
def __init__( self, address ) :
self.client_address = address
connections = {"oscar":SomeClass(["127.0.0.1","192.60.0.1"])}
for key in connections:
print connections[key].client_address[0]
edit
A dict
is a dictionary where a value may be stored using a key. When you request that key again, you get the value back, is that simple.
So in my previous example, the line:
connections = {"oscar":SomeClass(["127.0.0.1","192.60.0.1"])}
Could have been written as:
connection = []
connections["oscar"] = SomeClass(["1","2"])
s = connections["oscar"]
In your comment test[self.name] = self
your storing the object represented by self
into the test
dictionary using name
as the key.
for key in connections:
if connections[key].client_address[0] == client_address[0]:
This is simply looking at all the values stored in the connections
dictionary, to see if any of their properties named client_address
have the same first item (IP address) as the local variable client_address
. It's not necessary for the variable to have the same name as the property of the value in the dictionary.
What it's saying is: abort the connection if another connection from the same IP address is already being served. (Except for localhost, which is allowed to have as many connections as it likes.)
It could be re-spelled as:
def verify_request(self, request, new_client_addr):
ip= new_client_addr[0]
active_ips= [value.client_address[0] for value in connections.values()]
return ip not in active_ips or ip=='127.0.0.1'
精彩评论