| 1 |
"""Integration with Python standard library module urllib2: Request class. |
| 2 |
|
| 3 |
Copyright 2004-2006 John J Lee <[email protected]> |
| 4 |
|
| 5 |
This code is free software; you can redistribute it and/or modify it |
| 6 |
under the terms of the BSD or ZPL 2.1 licenses (see the file |
| 7 |
LICENSE included with the distribution). |
| 8 |
|
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import absolute_import |
| 12 |
import logging |
| 13 |
|
| 14 |
from . import _rfc3986 |
| 15 |
from . import _sockettimeout |
| 16 |
from . import _urllib2_fork |
| 17 |
from .polyglot import urlencode, is_string, unicode_type, iteritems |
| 18 |
|
| 19 |
warn = logging.getLogger("mechanize").warning |
| 20 |
|
| 21 |
|
| 22 |
def as_utf8(x): |
| 23 |
if isinstance(x, bytes): |
| 24 |
return x |
| 25 |
if not is_string(x): |
| 26 |
x = unicode_type(x) |
| 27 |
if isinstance(x, unicode_type): |
| 28 |
x = x.encode('utf-8') |
| 29 |
return x |
| 30 |
|
| 31 |
|
| 32 |
class Request(_urllib2_fork.Request): |
| 33 |
|
| 34 |
''' |
| 35 |
A request for some network resource. Note that if you specify the method as |
| 36 |
'GET' and the data as a dict, then it will be automatically appended to the |
| 37 |
URL. If you leave method as None, then the method will be auto-set to |
| 38 |
POST and the data will become part of the POST request. |
| 39 |
|
| 40 |
:arg str url: The URL to request |
| 41 |
:arg data: Data to send with this request. Can be either a dictionary |
| 42 |
which will be encoded and sent as application/x-www-form-urlencoded |
| 43 |
data or a bytestring which will be sent as is. If you use a bytestring |
| 44 |
you should also set the Content-Type header appropriately. |
| 45 |
:arg dict headers: Headers to send with this request |
| 46 |
:arg str method: Method to use for HTTP requests. If not specified |
| 47 |
mechanize will choose GET or POST automatically as appropriate. |
| 48 |
:arg float timeout: Timeout in seconds |
| 49 |
|
| 50 |
The remaining arguments are for internal use. |
| 51 |
''' |
| 52 |
|
| 53 |
def __init__(self, url, data=None, headers={}, |
| 54 |
origin_req_host=None, unverifiable=False, visit=None, |
| 55 |
timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT, |
| 56 |
method=None): |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
if not _rfc3986.is_clean_uri(url): |
| 65 |
warn("url argument is not a URI " |
| 66 |
"(contains illegal characters) %r" % url) |
| 67 |
if isinstance(data, dict): |
| 68 |
data = {as_utf8(k): as_utf8(v) for k, v in iteritems(data)} |
| 69 |
data = urlencode(data) |
| 70 |
data = data or None |
| 71 |
if data and method == 'GET': |
| 72 |
url += ('&' if '?' in url else '?') + data |
| 73 |
data = None |
| 74 |
_urllib2_fork.Request.__init__(self, url, data, headers, method=method) |
| 75 |
self.selector = None |
| 76 |
self.visit = visit |
| 77 |
self.timeout = timeout |
| 78 |
|
| 79 |
def __str__(self): |
| 80 |
return "<Request for %s>" % self.get_full_url() |