Skip to content

Commit

Permalink
Added default User-Agent to the simple http client if not provided.
Browse files Browse the repository at this point in the history
The User-Agent format is "Tornado\{Tornado_Version}".

If self.request.user_agent isn't set and self.request.headers has
no User-Agent in it's keys the default User-Agent is added.

Fixes: tornadoweb#2702
  • Loading branch information
piraz authored and jeyrce committed Aug 25, 2021
1 parent bddd0c2 commit 949055f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
4 changes: 3 additions & 1 deletion tornado/simple_httpclient.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from tornado.escape import _unicode
from tornado import gen
from tornado import gen, version
from tornado.httpclient import (
HTTPResponse,
HTTPError,
Expand Down Expand Up @@ -392,6 +392,8 @@ async def run(self) -> None:
)
if self.request.user_agent:
self.request.headers["User-Agent"] = self.request.user_agent
elif self.request.headers.get("User-Agent") is None:
self.request.headers["User-Agent"] = "Tornado/{}".format(version)
if not self.request.allow_nonstandard_methods:
# Some HTTP methods nearly always have bodies while others
# almost never do. Fail in this case unless the user has
Expand Down
9 changes: 8 additions & 1 deletion tornado/test/simple_httpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import typing # noqa: F401

from tornado.escape import to_unicode, utf8
from tornado import gen
from tornado import gen, version
from tornado.httpclient import AsyncHTTPClient
from tornado.httputil import HTTPHeaders, ResponseStartLine
from tornado.ioloop import IOLoop
Expand All @@ -28,6 +28,7 @@
CountdownHandler,
HelloWorldHandler,
RedirectHandler,
UserAgentHandler,
)
from tornado.test import httpclient_test
from tornado.testing import (
Expand Down Expand Up @@ -171,6 +172,7 @@ def get_app(self: typing.Any):
url("/echo_post", EchoPostHandler),
url("/respond_in_prepare", RespondInPrepareHandler),
url("/redirect", RedirectHandler),
url("/user_agent", UserAgentHandler),
],
gzip=True,
)
Expand Down Expand Up @@ -246,6 +248,11 @@ def test_header_reuse(self: typing.Any):
self.fetch("/hello", headers=headers)
self.assertEqual(list(headers.get_all()), [("User-Agent", "Foo")])

def test_default_user_agent(self: typing.Any):
response = self.fetch("/user_agent", method="GET")
self.assertEqual(200, response.code)
self.assertEqual(response.body.decode(), "Tornado/{}".format(version))

def test_see_other_redirect(self: typing.Any):
for code in (302, 303):
response = self.fetch("/see_other_post", method="POST", body="%d" % code)
Expand Down

0 comments on commit 949055f

Please sign in to comment.