88import threading
99from contextlib import closing
1010from wsgiref .simple_server import make_server
11+ import base64
1112
1213from . import core
1314try :
@@ -119,8 +120,10 @@ def write_to_textfile(path, registry):
119120
120121
121122def default_handler (url , method , timeout , headers , data ):
123+ '''Default handler that implements HTTP/HTTPS connections.
124+
125+ Used by the push_to_gateway functions. Can be re-used by other handlers.'''
122126 def handle ():
123- '''Default handler that implements HTTP/HTTPS connections.'''
124127 request = Request (url , data = data )
125128 request .get_method = lambda : method
126129 for k , v in headers :
@@ -133,6 +136,23 @@ def handle():
133136 return handle
134137
135138
139+ def basic_auth_handler (url , method , timeout , headers , data , username = None , password = None ):
140+ '''Handler that implements HTTP/HTTPS connections with Basic Auth.
141+
142+ Sets auth headers using supplied 'username' and 'password', if set.
143+ Used by the push_to_gateway functions. Can be re-used by other handlers.'''
144+ def handle ():
145+ '''Handler that implements HTTP Basic Auth.
146+ '''
147+ if username is not None and password is not None :
148+ auth_value = "{0}:{1}" .format (username , password )
149+ auth_header = "Basic {0}" .format (base64 .b64encode (bytes (auth_value )))
150+ headers .append (['Authorization' , auth_header ])
151+ default_handler (url , method , timeout , headers , data )()
152+
153+ return handle
154+
155+
136156def push_to_gateway (gateway , job , registry , grouping_key = None , timeout = None , handler = default_handler ):
137157 '''Push metrics to the given pushgateway.
138158
0 commit comments