python - Bind different ip addresses to urllib2 object in seperate threads -


The following code binds the socket specified in IP address to the main program globally.

  import socket truth_socket = socket.socket def bound_socket (* a, ** k): sock = true_socket (* a, ** k) sock.bind (sourceIP, 0)) back Sock socket.socket = bound_socket  

Suppose the main program has 10 threads, each running with a urllib2 example thread inside. How to bind 10 different IP addresses in each urllib2 object?

You can define a dictionary mapping thread identifier for the IP address or threading Use local () to define the thread in the global object:

  socket_data = threading.local () socket_data = bind_ip = any true_socket = socket socket def bound_socket ( * A, ** k): sock = true_socket (* a, ** k) if socket_data.bind_ip is not: sock.bind ((socket_data.bind_ip, 0)) return sock.socket = bound_socket def thread_target (bind_ip): Rest code for socket_data.bind_ip = bind_ip # bind_ip [...]: thread = thread (target = thread_ target, However, note that it is rather dirty hack  connect to the sub class of  HTTPConnection   

/ Code> Extending the method and redefining the method in http_open () HTTPHandler sub-category is a good way .


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

jquery - SimpleModal Confirm fails to submit form -

php - Multiple Select with Explode: only returns the word "Array" -