Developer Interface¶
Main Interface¶
For when you want to get things up and running.
Driver¶
-
class
pyrace.Driver[source]¶ Bases:
objectAn interface to create
Threads, provide them with a work, and drive them through their work in a synchronized manner.-
send_event¶ threading.Event – An
Eventindicating that all connections should finish sending aRequest.
-
read_event¶ threading.Event – An
Eventindicating that all connections should begin fetching aResponse.
-
_thread_class¶ pyrace.Thread – Our custom
Threadclass. Exposed for easy injection of other custom classes.
-
create_threads(work_queue, thread_count, extra_args={})[source]¶ Creates
Threads, initializing them with the providedwork_queueand optional extrarace_argskeyword arguments.
-
drive_threads(threads, timeout=10, send_delay=0.1)[source]¶ Drives a list of
Threads through their respectivework_queues.Parameters: - threads (list) – The list of
Threads to drive through theirwork_queues. - timeout (float, optional) – How long to wait, in seconds, before considering a
Threadto have timed out. Timed out threads may continue to run, but are no longer driven directly or waited on. Default is10seconds. - send_delay (float, optional) – How long to wait after syncing before allowing
Threads to finish sending data. Increasing this may improve timing precision by allowing sockets to fully flush. Increasing this value too much may result in connection timeouts. Default is0.10seconds.
- threads (list) – The list of
-
process(work_queue, thread_count=2, timeout=10, send_delay=0.1, **race_args)[source]¶ Creates and drives a collection of
Threads through a list of work items.Parameters: - work_queue (list) – A list of
Requests or callables for the threads to process. Ifwork_queueisn’t a list, it will be converted to a single-item list. SeeThreaddocumentation for additional details. - thread_count (int, optional) – The number of threads to create.
Default is
2. - timeout (float, optional) – How long to wait, in seconds, before considering a
Threadto have timed out. Timed outThreads may continue to run, but are no longer driven directly or waited on. Default is10seconds. - send_delay (float, optional) – How long to wait after synchronizing before allowing
BaseConnections to finish sending data. Increasing this may improve timing precision by allowing sockets to fully flush. Increasing this value too much may result in socket timeouts. Default is0.10seconds. - **race_args (dict) – Keyword arguments to pass to the
ThreadandBaseConnectionconstructors.
Returns: A list of
Threadobjects used. Of particular interest are theresponseandall_responsesattributes.Return type: list
- work_queue (list) – A list of
-
Lower-Level Classes¶
For when you want finer controls over how things work.
Thread¶
-
class
pyrace.Thread(work_queue, race_args)[source]¶ Bases:
threading.ThreadA worker thread that acts as the middleman between
Drivers andHTTPAdapters.Parameters: work_queue (list) – A list of work items for this class to process when
run()is executed. Work items must be arequests.Requestor a callable function:Requests are sent and theirResponses are appended to theall_responseslist.- Functions will be executed with the
Threadinstance as the only parameter (i.e.self). Functions are encouraged inspect theThreadstate, process any responses, and to modifywork_queueto add or change work as necessary.
race_args (dict) – Arguments for this class and its child
BaseConnections. Entries relevant to this class are:- thread_num : int
The thread number associated with this
Threadand its children classes.- shared : dict
A shared dict between this
Thread, itsDriver, and its children classes.- send_kwargs : dict, optional
Dict of extra arguments to pass to
requests.Session.send(). Default is{}.- fake_send : bool, optional
Don’t actually send the
Request, just create a fakeResponsefrom it. ThePreparedRequestis stored inrequests.Response.request. Useful for debugging. Default isFalse.- do_eval : bool, optional
Indicates if embedded statements in
Requests should be evaluated.Requests are evaluated before beingrequests.Session.prepare()d. See_eval_attrs,_eval_pattern, and_eval_actionfor details. Default isFalse.- save_sent_cookies : bool, optional
Cookies manually set in
Requestheadersorcookieattributes should be extracted and saved in ourSession‘s cookie jar. Extraction occurs after embedded statement evaluation is applied. Default isTrue.
-
work_queue¶ list – Local copy of __init__ parameter.
-
race_args¶ dict – Local copy of __init__ parameter.
dict – Unpacked value from
race_args.
bool – Unpacked value from
race_args.
-
_eval_attrs¶ list – The list of
Requestattributes to apply_eval_patternto.
-
_eval_pattern¶ str – The regex pattern that searches for evaluable code in the prepared request attributes. Default pattern matches
<<<statement_goes_here>>>.
-
_eval_flags¶ int – The regex flags to apply to
_eval_pattern. Default isre.VERBOSE | re.DOTALL.
-
_eval_action¶ callable – The action to take with the
re.MatchObjectfound by_eval_pattern. Default is convertingre.MatchObjectgroup 1 to a string, theneval()it.
-
session¶ requests.Session – The session-level storage associated with the most recent
run()call. TheSessionis created whenrun()begins and is closed when it ends.
-
adapter¶ pyrace.HTTPAdapter – The adapter responsible for handling our
Session‘s HTTP requests. See transport adapter documentation for details.
Raises: InvalidWorkItem– A work item inwork_queuewasn’t aRequestor callable.-
run()[source]¶ The work body of a
threading.Thread. Processes work items fromwork_queuein sequential order.
HTTP[S]Connection¶
-
class
pyrace.BaseConnection(*args, **kwargs)[source]¶ Bases:
objectA
HTTPConnectionwrapper that synchronizes the final bytes of a request.Parameters: race_args (dict) – Arguments for this class and its parent
Thread. Entries relevant to this class are:- thread_num : int
The thread number associated with our parent
Thread.- shared : dict
A shared dict between this Connection and its parent classes.
- sync_event : threading.Event
Per-thread state synchronization
Event. We set sync_event just before waiting on send_event and/or read_event. This indicates to the parent Driver that our class is ready to proceed. Once all Threads synchronize, the Driver clears each sync_event.- send_event : threading.Event
Global connection/socket sending
Eventcontrolled by the parentDriver. Until thisEventis set, we withhold the final few bytes of all sent data. When set, it indicates the remaining buffered data may be sent.- read_event : threading.Event
Global connection/socket reading
Eventcontrolled by the parentDriver. When set, it indicates that Connections may read server responses.Note
Due to CPython’s Global Interpreter Lock, only one thread can execute Python bytecode at a time. The lock is only guaranteed to be released during I/O, but that means some threads may begin fetching a
Responsebefore others have finished sending theirRequest. To prevent this, all threads must complete their sends before reading any results.- connect_mode : {‘normal’, ‘same’, ‘random’, ‘different’}, optional
Determines how the hostname’s server IP address is chosen:
- Normal: always call
getaddrinfo()and use what it returns. The results are usually similar but may vary from call to call. - Same: globally cache the
getaddrinfo()result and use it. This ensures that each Connection across allThreads use the same IP address. - Random: randomize which IP address each Connection connects to.
- Different: each Connection should connect to a different IP address.
The
getaddrinfo()result is chosen based on the Connection‘sthread_num. If there are fewer IP addresses than threads, the selection wraps around.
Default is
same.Note
The
connect_modeargument isn’t foolproof. If the connection to the preferred IP address fails, it will try the remaining IP addresses until a successful connection is made (this is the default behavior ofcreate_connection()). This means thatdiffmode can never fully guarantee that each Connection actually connects to a different IP address.- Normal: always call
-
race_args¶ dict – Local copy of __init__ parameter.
dict – Unpacked value from
race_args.
-
logger¶ logging.Logger – A
logging.Loggerinstance for this Connection.
-
_send_buffer¶ str – Whenever
send()is called, the data is appended to this buffer. If this buffer is over_buffer_sizebytes long, all but the final_buffer_sizebytes are sent.
-
_buffer_size¶ int – Defines the maximum length of
_send_bufferbefore flushing occurs.
-
getresponse(**kwargs)[source]¶ Flushes all buffered data and returns the server response after
read_eventis set.
-
class
pyrace.HTTPConnection(*args, **kwargs)[source]¶ Bases:
pyrace.connection.BaseConnection,urllib3.connection.HTTPConnection
-
class
pyrace.HTTPSConnection(*args, **kwargs)[source]¶ Bases:
pyrace.connection.BaseConnection,urllib3.connection.VerifiedHTTPSConnection
Intermediate Classes¶
For when you’re a developer.
HTTPAdapter¶
-
class
pyrace.HTTPAdapter(*args, **kwargs)[source]¶ Bases:
requests.adapters.HTTPAdapter-
init_poolmanager(*args, **pool_kwargs)[source]¶ Creates a
PoolManagerthat thisHTTPAdaptergetsHTTPConnectionPools from.Notes
Every
requests.HTTPAdapteris responsible for maintaining aurllib3.PoolManager. ThePoolManageris responsible for maintaining a ConnectionPool for each scheme. The ConnectionPools are responsible for maintaining Connection objects.To pass
race_argsto ourHTTPConnectioninitialization, the following must take place:- Inject
race_argsintopool_kwargs. - Initialize a
PoolManagerwith**pool_kwargswhich will save any unrecognized keyword arguments inconnection_pool_kw. - Change the
PoolManager‘s ConnectionPool class references to pint to our custom ConnectionPools instead. - When
HTTPConnectionPoolis initialized with**connection_pool_kw, it saves any unrecognized keyword arguments inconn_kw. (ConnectionPools are created the first time a Connection is needed for a scheme.) - When a
urllib3.Connectionis created, it is initialized with**conn_kw(which now contains arace_argskey).
- Inject
-
HTTP[S]ConnectionPool¶
-
class
pyrace.HTTPConnectionPool(host, port=None, strict=False, timeout=<object object>, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, **conn_kw)[source]¶ Bases:
urllib3.connectionpool.HTTPConnectionPool-
ConnectionCls¶ alias of
HTTPConnection
-
-
class
pyrace.HTTPSConnectionPool(host, port=None, strict=False, timeout=<object object>, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, ssl_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, **conn_kw)[source]¶ Bases:
urllib3.connectionpool.HTTPSConnectionPool-
ConnectionCls¶ alias of
HTTPSConnection
-