gpt4 book ai didi

python - requests.exceptions.ConnectionError : HTTPConnectionPool(host ='127.0.0.1' , 端口 = 8000):超过最大重试次数,网址:/api/1/

转载 作者:行者123 更新时间:2023-12-03 23:12:34 25 4
gpt4 key购买 nike

我正在尝试在 Django 之间进行通信和 Python文件,但我收到以下错误:

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'))



我创建了一个名为 test.py 的 Python 文件在 Django应用程序并尝试在它们之间进行通信。我的 Pytho n 文件包含以下代码:
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包含:-
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包含:-
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)

我的 Views.py包含:-
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文件包含:-
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()),
]

得到错误,如:

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'))



请帮我。谢谢各位技术....

最佳答案

我明白了失败背后的真正原因。我只从 1 个终端运行 py test.py 来访问 python 文件。当时服务器没有运行,因此无法进行通信。
然后我打开一个单独的终端并运行 Dev 服务器,现在我的 Python 文件能够与 Django 文件进行通信。
现在它运行良好。

关于python - requests.exceptions.ConnectionError : HTTPConnectionPool(host ='127.0.0.1' , 端口 = 8000):超过最大重试次数,网址:/api/1/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56010271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com