buxizhizhoum
buxizhizhoum

Reputation: 1929

Why my Django view return None as HttpResponse?

This is a function I used in Django view to accept post request, however it returns None sometimes, any idea about this problem?

def acceptpost(request):
    try:
        print "request.method:", request.method
        print "content_type:", request.content_type
        print "request.body:",request.body
        time.sleep(0.1)
    except Exception as e:
        log.error(e)
        return HttpResponse("error")
    return HttpResponse("OK")

The function I used to post data is:

def post_data(url, data)
    try:
        req = requests.post(url=url, data=data, verify=False)
        response = req.status_code
        content = req.content
    except RequestException as e:
        response = e.response
        log_debug.error("HttpResponse: %s" % response)
        continue

This function is in While True, url is: url = 'http://127.0.0.1:8000/acceptpost/'.

In most of time, I could get the right HttpResponse, which is "ok" in this case, and some time I could only get None, both of the two function runs on localhost, the web server is the Django web server with the address http://127.0.0.1/acceptpost/. I have not catch any log in function acceptpost, however there are HttpResponse None occasionally, is any idea about this problem?

Upvotes: 0

Views: 3904

Answers (1)

Xatyrian
Xatyrian

Reputation: 1384

Your code in itself doesn't seem to have a problem. The None you get comes from e.response which here equals None. This probably means that your request was not sent, thus there is no response to it.

RequestException is a generic exception covering several kind of exceptions. I suggest you see this manual page (not sure if it is up to date but still gives a pretty good insight of the many exceptions you can get). Differentiating most exceptions in your code will help you debug it I think.

Upvotes: 1

Related Questions