parser.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. from gunicorn.http.message import Request
  6. from gunicorn.http.unreader import SocketUnreader, IterUnreader
  7. class Parser(object):
  8. mesg_class = None
  9. def __init__(self, cfg, source, source_addr):
  10. self.cfg = cfg
  11. if hasattr(source, "recv"):
  12. self.unreader = SocketUnreader(source)
  13. else:
  14. self.unreader = IterUnreader(source)
  15. self.mesg = None
  16. self.source_addr = source_addr
  17. # request counter (for keepalive connetions)
  18. self.req_count = 0
  19. def __iter__(self):
  20. return self
  21. def __next__(self):
  22. # Stop if HTTP dictates a stop.
  23. if self.mesg and self.mesg.should_close():
  24. raise StopIteration()
  25. # Discard any unread body of the previous message
  26. if self.mesg:
  27. data = self.mesg.body.read(8192)
  28. while data:
  29. data = self.mesg.body.read(8192)
  30. # Parse the next request
  31. self.req_count += 1
  32. self.mesg = self.mesg_class(self.cfg, self.unreader, self.source_addr, self.req_count)
  33. if not self.mesg:
  34. raise StopIteration()
  35. return self.mesg
  36. next = __next__
  37. class RequestParser(Parser):
  38. mesg_class = Request