user_agent.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import typing as t
  2. class UserAgent:
  3. """Represents a parsed user agent header value.
  4. The default implementation does no parsing, only the :attr:`string`
  5. attribute is set. A subclass may parse the string to set the
  6. common attributes or expose other information. Set
  7. :attr:`werkzeug.wrappers.Request.user_agent_class` to use a
  8. subclass.
  9. :param string: The header value to parse.
  10. .. versionadded:: 2.0
  11. This replaces the previous ``useragents`` module, but does not
  12. provide a built-in parser.
  13. """
  14. platform: t.Optional[str] = None
  15. """The OS name, if it could be parsed from the string."""
  16. browser: t.Optional[str] = None
  17. """The browser name, if it could be parsed from the string."""
  18. version: t.Optional[str] = None
  19. """The browser version, if it could be parsed from the string."""
  20. language: t.Optional[str] = None
  21. """The browser language, if it could be parsed from the string."""
  22. def __init__(self, string: str) -> None:
  23. self.string: str = string
  24. """The original header value."""
  25. def __repr__(self) -> str:
  26. return f"<{type(self).__name__} {self.browser}/{self.version}>"
  27. def __str__(self) -> str:
  28. return self.string
  29. def __bool__(self) -> bool:
  30. return bool(self.browser)
  31. def to_header(self) -> str:
  32. """Convert to a header value."""
  33. return self.string