1

I am using this code do get information from my website with python, and this works like a charm, but can i save this output to a variable or at least to a json or txt file

import pycurl
def getUserData():
   c = pycurl.Curl()
   c.setopt(pycurl.URL, 'https://api.github.com/users/braitsch')
   c.setopt(pycurl.HTTPHEADER, ['Accept: application/json'])
   c.setopt(pycurl.VERBOSE, 0)
   c.setopt(pycurl.USERPWD, 'username:userpass')
   c.perform()
getUserData()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shakavkav
  • 151
  • 1
  • 2
  • 11

1 Answers1

9

Don't use curl here; Python comes with batteries included, albeit with an API that is only marginally better than pycurl.

I recommend you install requests rather than try and make urllib2 and passwords work:

import requests

url = 'https://api.github.com/users/braitsch'
headers = {'Accept': 'application/json'}
auth = ('username', 'userpass')
response = requests.get(url, headers=headers, auth=auth)

with open('outputfile.json', 'wb') as outf:
    outf.write(response.content)

If the response is large, you can stream the content to a file, see How to download image using requests, the same techniques would apply here.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    @jpthesolver2 note that this answer also references `urllib2`, so it is *aimed at Python 2*, where `response.content` is a string, not a `bytes` value. Since this is writing out JSON here, using `wb` is not really necessary in that case. Still, it doesn't do harm either and with `wb` the code works in Python 3 as well, so thanks for that. – Martijn Pieters Mar 14 '20 at 21:33