Don't initialize the UserAgent object until one is requested

This avoids hitting external servers to get a plausible user agent
string when the module is imported. When the first user agent string is
requested the object is initialized as usual.
This commit is contained in:
Carey Metcalfe
2018-02-28 19:27:41 -05:00
parent b9a7fc3674
commit b0bd978392
+4 -1
View File
@@ -19,7 +19,7 @@ from w3lib.encoding import html_to_unicode
DEFAULT_ENCODING = 'utf-8'
DEFAULT_URL = 'https://example.org/'
useragent = UserAgent()
useragent = None
# Typing.
_Find = Union[List['Element'], 'Element']
@@ -431,6 +431,9 @@ def user_agent(style='chrome') -> _UserAgent:
"""Returns a random user-agent, if not requested one of a specific
style. Defaults to a Chrome-style User-Agent.
"""
global useragent
if not useragent:
useragent = UserAgent()
return useragent[style] if style else useragent.random