Simple URL GET/POST function in Python

前端 未结 5 1643
旧时难觅i
旧时难觅i 2020-11-28 18:52

I can\'t seem to Google it, but I want a function that does this:

Accept 3 arguments (or more, whatever):

  • URL
  • a dictionary of params
5条回答
  •  隐瞒了意图╮
    2020-11-28 19:38

    requests

    https://github.com/kennethreitz/requests/

    Here's a few common ways to use it:

    import requests
    url = 'https://...'
    payload = {'key1': 'value1', 'key2': 'value2'}
    
    # GET
    r = requests.get(url)
    
    # GET with params in URL
    r = requests.get(url, params=payload)
    
    # POST with form-encoded data
    r = requests.post(url, data=payload)
    
    # POST with JSON 
    import json
    r = requests.post(url, data=json.dumps(payload))
    
    # Response, status etc
    r.text
    r.status_code
    

    httplib2

    https://github.com/jcgregorio/httplib2

    >>> from httplib2 import Http
    >>> from urllib import urlencode
    >>> h = Http()
    >>> data = dict(name="Joe", comment="A test comment")
    >>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
    >>> resp
    {'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
     'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
     'content-type': 'text/html'}
    

提交回复
热议问题