Allow POST and PUT requests to take both querystring params and request body
Before adoption: this commit came in with the history the project adopted, so no landing records it.
data.
authored by Richard Boulton · committed by Richard Boulton · parent f31ade3 · Browse files · 3 files·+102 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+102 added−27 removed
- other:+102 added−27 removed
Provenance
- Commit
80d860d- Tree
755a34f- Author
Richard Boulton <richard@tartarus.org>- Committer
Richard Boulton <richard@tartarus.org>- Parent
f31ade3
3 files changed+102 added−27 removed
modified:requests/api.py+14 added-10 removed
32 unmodified lines33 :param timeout: (optional) Float describing the timeout of the request.34 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.35 """36 37- if params and data:38- raise StandardError('You may provide either params or data to a request, but not both.')39-37 r = Request(38 method = method,39 url = url,43- data = params or data,40+ data = data,41+ params = params,42 headers = headers,43 cookiejar = cookies,44 files = files,45 auth = auth or auth_manager.get_auth(url),32 unmodified lines78 79 return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, timeout=timeout)80 81 84-def post(url, data='', headers=None, files=None, cookies=None, auth=None, timeout=None, allow_redirects=False):82+def post(url, data='', headers=None, files=None, cookies=None, auth=None,83+ timeout=None, allow_redirects=False, params=None):84 """Sends a POST request. Returns :class:`Response` object.85 86 :param url: URL for the new :class:`Request` object.87 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.2 unmodified lines90 :param cookies: (optional) CookieJar object to send with the :class:`Request`.91 :param auth: (optional) AuthObject to enable Basic HTTP Auth.92 :param timeout: (optional) Float describing the timeout of the request.93 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.94+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.95 """96 97- return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth,98- timeout=timeout, allow_redirects=allow_redirects)97+ return request('POST', url, params=params, data=data, headers=headers,98+ files=files, cookies=cookies, auth=auth, timeout=timeout,99+ allow_redirects=allow_redirects)100 101 101-def put(url, data='', headers=None, files=None, cookies=None, auth=None, timeout=None, allow_redirects=False):102+def put(url, data='', headers=None, files=None, cookies=None, auth=None,103+ timeout=None, allow_redirects=False, params=None):104 """Sends a PUT request. Returns :class:`Response` object.105 106 :param url: URL for the new :class:`Request` object.107 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.2 unmodified lines110 :param cookies: (optional) CookieJar object to send with the :class:`Request`.111 :param auth: (optional) AuthObject to enable Basic HTTP Auth.112 :param timeout: (optional) Float describing the timeout of the request.113 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.114+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.115 """116 114- return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth,115- timeout=timeout, allow_redirects=allow_redirects)117+ return request('PUT', url, params=params, data=data, headers=headers,118+ files=files, cookies=cookies, auth=auth, timeout=timeout,119+ allow_redirects=allow_redirects)120 121 122 def delete(url, params=None, headers=None, cookies=None, auth=None, timeout=None, allow_redirects=False):123 """Sends a DELETE request. Returns :class:`Response` object.12 unmodified linesmodified:requests/models.py+24 added-17 removed
29 unmodified lines30 31 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')32 33 def __init__(self, url=None, headers=dict(), files=None, method=None,34- data=dict(), auth=None, cookiejar=None, timeout=None,35- redirect=False, allow_redirects=False):34+ data=dict(), params=dict(), auth=None, cookiejar=None,35+ timeout=None, redirect=False, allow_redirects=False):36 37 socket.setdefaulttimeout(timeout)38 39 #: Request URL.3 unmodified lines43 #: Dictionary of files to multipart upload (``{filename: content}``).44 self.files = files45 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.46 self.method = method47+ #: Dictionary or byte of request body data to attach to the47- #: Form or Byte data to attach to the :class:`Request <models.Request>`.48- self.data = dict()48+ #: :class:`Request <models.Request>`.49+ self.data = None50+ #: Dictionary or byte of querystring data to attach to the51+ #: :class:`Request <models.Request>`.52+ self.params = None53 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history54 #: and HTTPError storage).55 self.redirect = redirect56 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)57 self.allow_redirects = allow_redirects58 59 self.data, self._enc_data = self._encode_params(data)60+ self.params, self._enc_params = self._encode_params(params)61+62 #: :class:`Response <models.Response>` instance, containing63 #: content and metadata of HTTP Response, once :attr:`sent <send>`.64 self.response = Response()65 124 unmodified lines190 method = self.method191 192 request = Request(193 url, self.headers, self.files, method,188- self.data, self.auth, self.cookiejar, redirect=False194+ self.data, self.params, self.auth, self.cookiejar,195+ redirect=False196 )197 request.send()198 r = request.response199 23 unmodified lines223 else:224 return data, data225 226 220- @staticmethod221- def _build_url(url, data=None):222- """Build URLs."""227+ def _build_url(self):228+ """Build the actual URL to use"""229 224- if urlparse(url).query:225- return '%s&%s' % (url, data)226- else:227- if data:228- return '%s?%s' % (url, data)230+ if self._enc_params:231+ if urlparse(self.url).query:232+ return '%s&%s' % (self.url, self._enc_params)233 else:230- return url234+ return '%s?%s' % (self.url, self._enc_params)235+ else:236+ return self.url237 238 239 def send(self, anyway=False):240 """Sends the request. Returns True of successful, false if not.7 unmodified lines248 """249 self._checks()250 success = False251 252+ url = self._build_url()253 if self.method in ('GET', 'HEAD', 'DELETE'):247- req = _Request(self._build_url(self.url, self._enc_data), method=self.method)254+ req = _Request(url, method=self.method)255 else:256 257 if self.files:258 register_openers()1 unmodified line260 if self.data:261 self.files.update(self.data)262 263 datagen, headers = multipart_encode(self.files)257- req = _Request(self.url, data=datagen, headers=headers, method=self.method)264+ req = _Request(url, data=datagen, headers=headers, method=self.method)265 266 else:260- req = _Request(self.url, data=self._enc_data, method=self.method)267+ req = _Request(url, data=self._enc_data, method=self.method)268 269 if self.headers:270 req.headers.update(self.headers)271 258 unmodified linesmodified:test_requests.py+64 added
3 unmodified lines4 from __future__ import with_statement5 6 import unittest7 import cookielib8+try:9+ import simplejson as json10+except ImportError:11+ import json12 13 import requests14 15 216 unmodified lines232 with requests.settings(timeout=100):233 requests.get(httpbin(''))234 235 236+ def test_urlencoded_post_data(self):237+ r = requests.post(httpbin('post'), data=dict(test='fooaowpeuf'))238+ self.assertEquals(r.status_code, 200)239+ self.assertEquals(r.headers['content-type'], 'application/json')240+ self.assertEquals(r.url, httpbin('post'))241+ rbody = json.loads(r.content)242+ self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))243+ self.assertEquals(rbody.get('data'), '')244+245+246 def test_nonurlencoded_post_data(self):247 r = requests.post(httpbin('post'), data='fooaowpeuf')248+ self.assertEquals(r.status_code, 200)249+ self.assertEquals(r.headers['content-type'], 'application/json')250+ self.assertEquals(r.url, httpbin('post'))251+ rbody = json.loads(r.content)252+ # Body wasn't valid url encoded data, so the server returns None as253+ # "form" and the raw body as "data".254+ self.assertEquals(rbody.get('form'), None)255+ self.assertEquals(rbody.get('data'), 'fooaowpeuf')256 257 258+ def test_urlencoded_post_querystring(self):259+ r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'))260+ self.assertEquals(r.status_code, 200)261+ self.assertEquals(r.headers['content-type'], 'application/json')262+ self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))263+ rbody = json.loads(r.content)264+ self.assertEquals(rbody.get('form'), {}) # No form supplied265+ self.assertEquals(rbody.get('data'), '')266 267+268+ def test_nonurlencoded_post_querystring(self):269+ r = requests.post(httpbin('post'), params='fooaowpeuf')270+ self.assertEquals(r.status_code, 200)271+ self.assertEquals(r.headers['content-type'], 'application/json')272+ self.assertEquals(r.url, httpbin('post?fooaowpeuf'))273+ rbody = json.loads(r.content)274+ self.assertEquals(rbody.get('form'), {}) # No form supplied275+ self.assertEquals(rbody.get('data'), '')276+277+278+ def test_urlencoded_post_query_and_data(self):279+ r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'),280+ data=dict(test2="foobar"))281+ self.assertEquals(r.status_code, 200)282+ self.assertEquals(r.headers['content-type'], 'application/json')283+ self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))284+ rbody = json.loads(r.content)285+ self.assertEquals(rbody.get('form'), dict(test2='foobar'))286+ self.assertEquals(rbody.get('data'), '')287+288+289+ def test_nonurlencoded_post_query_and_data(self):290+ r = requests.post(httpbin('post'), params='fooaowpeuf',291+ data="foobar")292+ self.assertEquals(r.status_code, 200)293+ self.assertEquals(r.headers['content-type'], 'application/json')294+ self.assertEquals(r.url, httpbin('post?fooaowpeuf'))295+ rbody = json.loads(r.content)296+ self.assertEquals(rbody.get('form'), None)297+ self.assertEquals(rbody.get('data'), 'foobar')298+299+300+301 if __name__ == '__main__':302 unittest.main()