requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/

24,004

Solution 1

I got the real reason behind the failure. I had run only py test.py from only 1 terminal to access the python file. At that time the server was not running so commmunication couldn't happen. I then opened a separate terminal and ran the Dev server and now my Python file is able to communicate with Django file. Now its running fine.

Solution 2

Try this :

import requests

# BASE_URL='http://127.0.0.8000' <<< Url with port malformed
BASE_URL='http://127.0.0.1:8000'
ENDPOINT='api/'
def get_resource():
    # resp=requests.get(BASE_URL+ENDPOINT)  <<< Request url malformed
    resp=requests.get(BASE_URL+"/"+ENDPOINT)
    print(resp.status_code)
    print(resp.json())
get_resource()

Solution 3

You just need to open separate terminal and run your python code and

make sure your server is running at that time

Share:
24,004
Learner
Author by

Learner

Updated on February 07, 2022

Comments

  • Learner
    Learner about 2 years

    I am trying to communicate between Django and Python file but I am getting below error :

    requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

    I have created a Python file named test.py In a Django app and trying to communicate between them. My Python file contains below code :

    import requests
    BASE_URL='http://127.0.0.1:8000/'
    ENDPOINT='api/'
    def get_resource(id):
        resp=requests.get(BASE_URL+ENDPOINT+id+'/')
        print(resp.status_code)
        print(resp.json()) 
    id=input("Enter some ID: ")
    get_resource(id)
    

    Models.py contains:-

    from django.db import models
    
    # Create your models here.
    class Employee(models.Model):
        eno=models.IntegerField()
        ename=models.CharField(max_length=70)
        esal=models.FloatField()
        eaddr=models.CharField(max_length=100)
    

    Admin.py contains:-

    from django.contrib import admin
    from testapp.models import Employee
    # Register your models here.
    class EmployeeAdmin(admin.ModelAdmin):
        list_display=  ['id','eno','ename','esal','eaddr']
    
    admin.site.register(Employee,EmployeeAdmin)
    

    My Views.py contains:-

    from django.shortcuts import render
    from django.views.generic import View
    from testapp.models import Employee
    import json
    from django.http import HttpResponse
    
    
    class EmployeeDetailCBV(View):
    def get(self,request,id,*args,**kwargs):
        emp = Employee.objects.get(id=id)  
        emp_data = {'eno':emp.eno , 'ename':emp.ename , 'esal':emp.esal , 'eaddr':emp.eaddr} 
        json_data=json.dumps(emp_data)
        return HttpResponse(json_data , content_type='application/json')
    

    urls.py file contains:-

    from django.contrib import admin
    from django.urls import path
    from testapp import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/(?P<id>\d+)/$', views.EmployeeDetailCBV.as_view()),
    ]
    

    Getting error like :

    requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

    Please help me. Thank you techies....

  • Learner
    Learner almost 5 years
    Yea I forgot to put / after 8000. Now I've corrected it but again showing the same error
  • Learner
    Learner almost 5 years
    Thanks for identifying that. My bad. Changed it but again getting same error
  • Ugo T.
    Ugo T. almost 5 years
    Oh right, the last thing : http://127.0.0:8000 -> http://127.0.0.1:8000. So obvious, that I couldn't see it !
  • Learner
    Learner almost 5 years
    It seems I'm drunk and trying to code. Sorry for missing that. Changed it but I don't know why it's throwing same error again and again
  • Ugo T.
    Ugo T. almost 5 years
    What happens when you go to http://127.0.0.1:8000/api from your browser ?
  • Learner
    Learner almost 5 years
    Yea now I'm able to get the data I had created in admin page. But when I'm trying to retrieve same information through Python file i.e, test.py I'm still getting requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x04219250>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
  • MwamiTovi
    MwamiTovi over 4 years
    Oops!! Had forgotten to start the dev-server first, too. Thanks @Chandan
  • RicarHincapie
    RicarHincapie over 3 years
    If you are not planning to give an answer, just go to "add a comment"
  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.