title: Python - Using nonces with multithreading
body: <p>I am using python 2 with requests. This question is more of a curiosity of how I can improve this performance.</p>
  
  <p>The issue now is that I must send a cryptographic signature in the header of the request to a HTTPS server. This signature includes a "nonce" which must be a timestamp, and ALWAYS must increase (on the server side).</p>
  
  <p>Obviously this can wreak havoc on running multiple HTTP sessions on multiple threads. Requests ended up sent out not in order because they get interrupted between generating the headers and sending the HTTPS POST request. </p>
  
  <p>The solution is to lock the thread from before creating the signature till the end of recieving HTTPS data. Ideally, I would like to release the LOCK after the HTTP request was SENT, and not have to wait for the data to be recieved. Is there any way I can release the lock, using requests, after just the HTTP headers are SENT? See code sample:</p>
  
  <p>self.lock is a Threading.Lock. This instance of this class (self) is shared amongst multiple Threads.</p>
  
  <pre><code>def get_nonce(self):
      return int(1000*time.time())
  
  def do_post_request(self, endpoint, parameters):
      with self.lock:
          url = self.base + endpoint
          urlpath = endpoint
          parameters['nonce'] = self.get_nonce()
          postdata = urllib.urlencode(parameters)
          message = urlpath + hashlib.sha256(str(parameters['nonce']) + postdata).digest()
          signature = hmac.new(base64.b64decode(self.secret_key), message, hashlib.sha512)
          headers = {
              'API-Key': self.api_key,
              'API-Sign': base64.b64encode(signature.digest())
          }
          data = urllib.urlencode(parameters)
          response = requests.post(url, data=data, headers=headers, verify=True).json()
  
      return response
  </code></pre>