From 949055f6612c7a9b6872fd80ac05aa8bcdbb3e41 Mon Sep 17 00:00:00 2001 From: Flavio Garcia Date: Sun, 26 Apr 2020 16:18:26 -0400 Subject: [PATCH] Added default User-Agent to the simple http client if not provided. 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: #2702 --- tornado/simple_httpclient.py | 4 +++- tornado/test/simple_httpclient_test.py | 9 ++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py index 1e05786510..ec1b84fda4 100644 --- a/tornado/simple_httpclient.py +++ b/tornado/simple_httpclient.py @@ -1,5 +1,5 @@ from tornado.escape import _unicode -from tornado import gen +from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, @@ -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 diff --git a/tornado/test/simple_httpclient_test.py b/tornado/test/simple_httpclient_test.py index 0f2c252fe8..18e0969114 100644 --- a/tornado/test/simple_httpclient_test.py +++ b/tornado/test/simple_httpclient_test.py @@ -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 @@ -28,6 +28,7 @@ CountdownHandler, HelloWorldHandler, RedirectHandler, + UserAgentHandler, ) from tornado.test import httpclient_test from tornado.testing import ( @@ -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, ) @@ -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)