Repository: scrapy/scrapy

Issue:
PY3: Fail to download the second or later requests to hosts using secure cookies
## Environment
- Mac OS X 10.10.5
- Python 3.4.2
- Scrapy 1.1.0rc1
- Twisted 15.5.0
## Steps to Reproduce
1. Save the following spider as `secure_cookie_spider.py`.
   
   ``` py
   import scrapy
   
   
   class SecureCookieSpider(scrapy.Spider):
      name = 'secure_cookie_spider'
      start_urls = [
          'https://github.com/',
      ]
   
      def parse(self, response):
          # Request the same url again
          yield scrapy.Request(url=response.url, callback=self.parse_second_request)
   
      def parse_second_request(self, response):
          pass
   ```
2. Run the following command.
   
   ```
   $ scrapy runspider secure_cookie_spider.py
   ```
## Expected Results

No error is reported.
## Actual Results

Fail to download the second request with `AttributeError: 'WrappedRequest' object has no attribute 'type'`.

```
$ scrapy runspider secure_cookie_spider.py
2016-02-07 11:57:11 [scrapy] INFO: Scrapy 1.1.0rc1 started (bot: scrapybot)
2016-02-07 11:57:11 [scrapy] INFO: Overridden settings: {}
2016-02-07 11:57:11 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.logstats.LogStats']
2016-02-07 11:57:11 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-02-07 11:57:11 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-02-07 11:57:11 [scrapy] INFO: Enabled item pipelines:
[]
2016-02-07 11:57:11 [scrapy] INFO: Spider opened
2016-02-07 11:57:11 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-02-07 11:57:12 [scrapy] DEBUG: Crawled (200) <GET https://github.com/> (referer: None)
2016-02-07 11:57:12 [scrapy] ERROR: Error downloading <GET https://github.com/>
Traceback (most recent call last):
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/core/downloader/middleware.py", line 37, in process_request
    response = yield method(request=request, spider=spider)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/downloadermiddlewares/cookies.py", line 39, in process_request
    jar.add_cookie_header(request)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/http/cookies.py", line 42, in add_cookie_header
    cookies += self.jar._cookies_for_domain(host, wreq)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1242, in _cookies_for_domain
    if not self._policy.return_ok(cookie, request):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1077, in return_ok
    if not fn(cookie, request):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1103, in return_ok_secure
    if cookie.secure and request.type != "https":
AttributeError: 'WrappedRequest' object has no attribute 'type'
2016-02-07 11:57:12 [scrapy] INFO: Closing spider (finished)
2016-02-07 11:57:12 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 1,
 'downloader/exception_type_count/builtins.AttributeError': 1,
 'downloader/request_bytes': 211,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 9735,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 2, 7, 2, 57, 12, 757829),
 'log_count/DEBUG': 1,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2016, 2, 7, 2, 57, 11, 384330)}
2016-02-07 11:57:12 [scrapy] INFO: Spider closed (finished)
```

Note that no error is reported in Python 2.

PY3: Fail to download the second or later requests to hosts using secure cookies
## Environment
- Mac OS X 10.10.5
- Python 3.4.2
- Scrapy 1.1.0rc1
- Twisted 15.5.0
## Steps to Reproduce
1. Save the following spider as `secure_cookie_spider.py`.
   
   ``` py
   import scrapy
   
   
   class SecureCookieSpider(scrapy.Spider):
      name = 'secure_cookie_spider'
      start_urls = [
          'https://github.com/',
      ]
   
      def parse(self, response):
          # Request the same url again
          yield scrapy.Request(url=response.url, callback=self.parse_second_request)
   
      def parse_second_request(self, response):
          pass
   ```
2. Run the following command.
   
   ```
   $ scrapy runspider secure_cookie_spider.py
   ```
## Expected Results

No error is reported.
## Actual Results

Fail to download the second request with `AttributeError: 'WrappedRequest' object has no attribute 'type'`.

```
$ scrapy runspider secure_cookie_spider.py
2016-02-07 11:57:11 [scrapy] INFO: Scrapy 1.1.0rc1 started (bot: scrapybot)
2016-02-07 11:57:11 [scrapy] INFO: Overridden settings: {}
2016-02-07 11:57:11 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.logstats.LogStats']
2016-02-07 11:57:11 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-02-07 11:57:11 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-02-07 11:57:11 [scrapy] INFO: Enabled item pipelines:
[]
2016-02-07 11:57:11 [scrapy] INFO: Spider opened
2016-02-07 11:57:11 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-02-07 11:57:12 [scrapy] DEBUG: Crawled (200) <GET https://github.com/> (referer: None)
2016-02-07 11:57:12 [scrapy] ERROR: Error downloading <GET https://github.com/>
Traceback (most recent call last):
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/core/downloader/middleware.py", line 37, in process_request
    response = yield method(request=request, spider=spider)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/downloadermiddlewares/cookies.py", line 39, in process_request
    jar.add_cookie_header(request)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/http/cookies.py", line 42, in add_cookie_header
    cookies += self.jar._cookies_for_domain(host, wreq)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1242, in _cookies_for_domain
    if not self._policy.return_ok(cookie, request):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1077, in return_ok
    if not fn(cookie, request):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/http/cookiejar.py", line 1103, in return_ok_secure
    if cookie.secure and request.type != "https":
AttributeError: 'WrappedRequest' object has no attribute 'type'
2016-02-07 11:57:12 [scrapy] INFO: Closing spider (finished)
2016-02-07 11:57:12 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 1,
 'downloader/exception_type_count/builtins.AttributeError': 1,
 'downloader/request_bytes': 211,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 9735,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 2, 7, 2, 57, 12, 757829),
 'log_count/DEBUG': 1,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'request_depth_max': 1,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2016, 2, 7, 2, 57, 11, 384330)}
2016-02-07 11:57:12 [scrapy] INFO: Spider closed (finished)
```

Note that no error is reported in Python 2.



Discussion:

Resolving patch:
diff --git a/scrapy/http/cookies.py b/scrapy/http/cookies.py
--- a/scrapy/http/cookies.py
+++ b/scrapy/http/cookies.py
@@ -137,13 +137,29 @@ def is_unverifiable(self):
         """
         return self.request.meta.get('is_unverifiable', False)
 
-    # python3 uses request.unverifiable
+    def get_origin_req_host(self):
+        return urlparse_cached(self.request).hostname
+
+    # python3 uses attributes instead of methods
+    @property
+    def full_url(self):
+        return self.get_full_url()
+
+    @property
+    def host(self):
+        return self.get_host()
+
+    @property
+    def type(self):
+        return self.get_type()
+
     @property
     def unverifiable(self):
         return self.is_unverifiable()
 
-    def get_origin_req_host(self):
-        return urlparse_cached(self.request).hostname
+    @property
+    def origin_req_host(self):
+        return self.get_origin_req_host()
 
     def has_header(self, name):
         return name in self.request.headers


Test patch:
diff --git a/tests/test_http_cookies.py b/tests/test_http_cookies.py
--- a/tests/test_http_cookies.py
+++ b/tests/test_http_cookies.py
@@ -14,12 +14,15 @@ def setUp(self):
 
     def test_get_full_url(self):
         self.assertEqual(self.wrapped.get_full_url(), self.request.url)
+        self.assertEqual(self.wrapped.full_url, self.request.url)
 
     def test_get_host(self):
         self.assertEqual(self.wrapped.get_host(), urlparse(self.request.url).netloc)
+        self.assertEqual(self.wrapped.host, urlparse(self.request.url).netloc)
 
     def test_get_type(self):
         self.assertEqual(self.wrapped.get_type(), urlparse(self.request.url).scheme)
+        self.assertEqual(self.wrapped.type, urlparse(self.request.url).scheme)
 
     def test_is_unverifiable(self):
         self.assertFalse(self.wrapped.is_unverifiable())
@@ -32,6 +35,7 @@ def test_is_unverifiable2(self):
 
     def test_get_origin_req_host(self):
         self.assertEqual(self.wrapped.get_origin_req_host(), 'www.example.com')
+        self.assertEqual(self.wrapped.origin_req_host, 'www.example.com')
 
     def test_has_header(self):
         self.assertTrue(self.wrapped.has_header('content-type'))