为什么 Python 请求库没有得到响应? [英] Why Python requests library failing to get response?

查看:32
本文介绍了为什么 Python 请求库没有得到响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图方法:

# This view method is to register a new user through api call
def register(request):
    if request.method == 'GET':
        registrationForm = RegistrationForm(request.GET)

        if registrationForm.is_valid():

            r = requests.get('http://localhost:8000/api/create-user/', timeout=10)
            print r.content
            return HttpResponseRedirect('/')
    else:
        registrationForm = RegistrationForm()

    return render(request, 'frontend/index.html', {'registrationForm': registrationForm})

在上面提到的视图方法中,请求库只是继续加载,只是没有得到响应,最终在 10 秒后由于超时而失败.

Here in the above mentioned view method, the requests library just keeps on loading and just doesnt get the response and ultimately fails after 10 secs as timedout.

'api/create-user/' url 映射到的另一个应用程序在同一个项目中,这可能是原因吗?

The other app where 'api/create-user/' url maps to is in the same project, could this be the reason?

该应用 urls.py(不是主 urls.py)中该映射的 url 是:

The url for that mapping in that app urls.py (not main urls.py) is :

from django.conf.urls import include, url
from django.contrib import admin

from . import views

urlpatterns = [
    url(r'^create-user/', views.create_user),
]

我也在使用 Django rest 框架,上面提到的 url 匹配的视图是:

I am also using Django rest framework and the view which the above mentioned url matches to is:

from django.shortcuts import render

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response


# Create your views here.
@api_view(['GET'])
def create_user(request):
    print 'coming....'
    # print request.GET.get('username')
    # print request.POST.get('password')
    data = {}

    data.update({'result': 'good'})

    return Response(data)

通过单元测试它工作正常,这是我写的单元测试:

With the unit testing it works fine, here is the unit test which I wrote:

from django.test import TestCase

import requests

# Create your tests here.
# This class is for unit testing the request/response for api module.
# Here we can test if the REST api call we are making are working perfect or not.
class FrontEndTests(TestCase):

    def test_user_creation(self):
        r = requests.get('http://localhost:8000/api/create-user/')
        print r.content
        self.assertIsNotNone(r, "Not none")

我还在 settings.py 和 django rest 框架中添加了一些设置,例如 ALLOWED_HOSTS 等:

I have also added few settings such as ALLOWED_HOSTS etc. in settings.py and for django rest framework I added:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

SESSION_SAVE_EVERY_REQUEST = True

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

我在这里做错了什么?谢谢

What am I doing wrong here? Thanks

我也尝试使用来自 manage.py shell 的请求,它似乎在那里工作正常.是因为我在 form.is_valid() 块中使用它而导致它不起作用还是我怀疑 django-rest-framework 是罪魁祸首.有什么我需要添加的设置吗?

I also tried using requests from manage.py shell, and it seems to work fine there. Is it because I am using it inside a form.is_valid() block that it is not working or I also suspect django-rest-framework to be the culprit. Is there any settings which I need to add more?

---------- 回答

---------- Answer

我使用的是不是多线程的 runserver_plus,为了解决这个问题,我使用的是 runserver 并且它工作正常,否则你必须在两个不同的端口上启动同一个项目!

I was using runserver_plus which is not multithreaded, to solve this problem I am using runserver and it works fine, otherwise you have to start same project on two different ports!

推荐答案

我相信这是因为您使用的是非多线程的 Django runserver(如果我错了,请纠正我)

I believe this is because you are using the Django runserver (correct me if I am wrong) which is not multi-threaded

https://code.djangoproject.com/ticket/3357

因此,您对 localhost:8000 的请求已排队等待发出请求的请求完成!不理想.

So you request to localhost:8000 is queued waiting for the request that made the request to finish! Not ideal.

在生产环境中,当您使用 wsgi 应用程序(如 uwsgi)运行服务器时,这没问题,因为它 是多线程的.

In production, where you are running your server with a wsgi app (like uwsgi) this would be OK because it is multithreaded.

它在这个测试用例中工作的原因是因为您正在从测试线程向测试服务器发出请求,在不同的线程中运行.

The reason it works in this test case is because you are making the request from the test thread to the test server that is being run in a different thread.

编辑 #1:需要考虑的几件事

EDIT #1: A few things to think about

1) 为什么您在 GET 请求而不是 POST 请求中接受您的注册表?这是对 GET 动词的滥用,因为您实际上是在服务器上创建一些东西

1) Why are your accepting your registration form in a GET request and not a POST request? This is an abuse of the GET verb because you are actually creating something on the server

2) 为什么要从应用程序内部调用自己的 API,而不是将此功能放入可以从所有需要它的端点调用的方法中?

2) Why are you calling your own API from inside your application and not putting this functionality into a method that can be called from all endpoints that need it?

编辑#2:

如评论中所述,开发服务器是多线程的

As stated in the comments, the dev server is multithreaded

https://github.com/django/django/commit/ce165f7bbf

这篇关于为什么 Python 请求库没有得到响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆