3

I am new to programming.. I used python to create code that gets data from an API using requests package and the request uses HTTPBasicAuth. Below is the request which works fine in genral python.

response = requests.get(url,auth=HTTPBasicAuth('username','password'),stream=True

Can some please advise how can I implement this in django. when I use the same code as below, it gives me an error as "name HTTPBasicAuth is not defined"

def index(request):
   if request.method == "POST":
      url = urlname
      response = requests.get(url,auth=HTTPBasicAuth('username','password'),stream=True
      data = response.json()
7
  • At the moment HTTPBasicAuth is outside the scope of the function. How are you importing HTTPBasicAuth? You might need to apply the blueprint by doing something like HTTPBasicAuth(app) in your config, then it'll be accessible by the function. Commented Jun 14, 2020 at 11:01
  • 1
    Hi Jack, in my general python code I did pip install requests and then used import requests however not sure how it works on the django side.. Commented Jun 14, 2020 at 11:03
  • Try adding: from requests import HTTPBasicAuth Commented Jun 14, 2020 at 11:07
  • 1
    tried that.. it says - cannot import name HTTPBasicAuth from requests.. Commented Jun 14, 2020 at 11:09
  • 1
    awesome.. that did the trick.. its working now.. Thank you Jack :) Commented Jun 14, 2020 at 11:14

2 Answers 2

2

Change your import statement to:

from requests.auth import HTTPBasicAuth 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you.. I marked it as an answer.. Quick question - Once I get the response in json dictionary.. any advise on how I can save all the records to the django model tables in the database? I am generating a large dataset of around 300k records. Please advise..
I'm not sure in Django but it could be something like: for record in records: db.session.add(record) db.session.commit()
0

you can also use: HTTPDigestAuth

import requests
from requests.auth import HTTPDigestAuth

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.