2016-11-23 3 views
1

Ich habe eine Anfrage url http://my_ip:8080 und ich habe meine benutzerdefinierte Header und Körper Körper als {"test":"hello"} und ich kann nicht Körper der POST-Anfrage lesen. und meine Ansichten Modul wielesen Körperformular Anfrage in Django

mein views.py

from django.shortcuts import render 
from django.views.decorators.csrf import csrf_exempt 
from django.http import HttpResponse 
from django.utils.decorators import method_decorator 
from django.db import connection 
import json 
import re 
from hinduja.models import Register 


# Register API for Hinduja 
@method_decorator(csrf_exempt) 
def hinduja_register(req): 
    agent = is_valid_agent(req) 
    if agent["result"] == True: 
     try: 
      body = get_body(req) 
     except Exception as e: 
      print("Exception as " + str(e)) 
      json_data = {"result":"test"} 
    else: 
     json_data = error_message('invalid_client') 
    return response_to_client(json_data) 

def is_valid_agent(req): 
    regex_http_ = re.compile(r'^HTTP_.+$') 
    regex_content_type = re.compile(r'^CONTENT_TYPE$') 
    regex_content_length = re.compile(r'^CONTENT_LENGTH$') 
    request_header = {} 
    agent = {} 
    for header in req.META: 
     if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header): 
      request_header[header] = req.META[header] 
    try: 
     user_agent = request_header['HTTP_USER_AGENT'] 
     if user_agent == 'XXX': 
     agent["result"] = True 
     agent["user_agent"] = user_agent 
    except Exception as e: 
     agent["result"] = False 
    return agent 

# Get the request body 
def get_body(req): 
    body_unicode = req.body.decode('utf-8') 
    body = json.loads(body_unicode) 
    return body; 

# Return error response 
def error_message(message): 
    return {"result":"error", "message": message} 

# Return to success response to client 
def response_to_client(json_data): 
    data = json.dumps(json_data) 
    return HttpResponse(data, content_type='application/json') 

beim Aufruf

body_unicode = req.body.decode('utf-8')

I Timeout-Fehler bekam und bekam

Broken pipe aus ('10 .1.1.120 ', 47496) Dieser Fehler kann nicht behoben werden. Kann mir jemand Vorschlag bezüglich dieses Thema geben

+0

Django nicht den vollen Körper der HTTP-Nachricht zu empfangen. Wenn dieser Fehler konsistent auftritt, liegt wahrscheinlich ein Problem im Client oder in der Serverkonfiguration vor. – knbk

+0

Ich setze die ALLOWED_HOSTS in meiner settings.py –

+0

versuchen, 'req.body' zu drucken und überprüfen, welche Parameter kommen. –

Antwort

0

Sollte es auf diese Weise sein:

def get_body(req): 
    body_unicode = request.body.decode('utf-8') 
    body = json.loads(body_unicode) 
    return body; 
+0

Ich habe den gleichen Code verwendet –