get Json data from request with Django - python

I'm trying to develop a very simple script in Django, I'd collect a Json data from the request and then store all data in the database.
I developed one python script that I'm using to send the Json data to the Django view, but I'm doing something wrong and I can't understand what, because every time that I run it,I've got "Malformed data!".
Can someone helps me? what am I doing wrong?
Sender.py
import json
import urllib2
data = {
'ids': ["milan", "rome","florence"]
}
req = urllib2.Request('http://127.0.0.1:8000/value/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Django view.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
from models import *
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def value(request):
try:
data = json.loads(request.body)
label = data['label']
url = data ['url']
print label, url
except:
return HttpResponse("Malformed data!")
return HttpResponse("Got json data")

Your dictionary "data" in sender.py contains only one value with key "ids" but in view.py you are trying to access keys "label" and "url" in this parsed dictionary.

Related

connection error while using requests module in my django project

I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py
Following is what my views.py have
from django.http import HttpResponse
from django.shortcuts import render
import re, requests
def codify_data(data_raw):
data = data_raw.json()['data']
if language == 'web':
html_cd = data['sourceCode']
css_cd = data['cssCode']
js_cd = data['jsCode']
def home_page(request):
return render(request,'home/index.html')
def code(request):
link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app')
result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2]
data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result)
codify_data(data_raw)
The error is shown below:

How to convert a Django HttpRequest object with data to a Django Rest Framework Request object?

I'm trying to turn a django.http.HttpRequest object that contains JSON POST data into a rest_framework.request.Request object, but the data ends up empty.
I was asked to create the HttpRequest using the Django Rest Framework's APIRequestFactory. So I create it like this:
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': 'test#example.com'}
request = factory.post('/', data, content_type='application/json')
# also tried using json.dumps(data) instead of just data
And then I try to convert it to a Request object using:
from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser])
I would expect converted_request.data to contain the data from data, i.e. {'email': 'test#example.com'}. However, when in print it, I get <QueryDict: {}>:
>>> print(converted_request.data)
<QueryDict: {}>
The only way I can get the request to contain the data is by setting the _full_data attribute after creating the Request object:
>>> converted_request._full_data = data
>>> print(converted_request.data)
{'email': 'test#example.com'}
I'm looking to see if there is a way of populating the request's data without setting the attribute directly. I don't understand why it's not getting populating currently.
Below is the full snippet for easy copy-and-pasting:
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': 'test#example.com'}
request = factory.post('/', data, content_type='application/json')
from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser])
print(converted_request.data)
# <QueryDict: {}>
converted_request._full_data = data
print(converted_request.data)
# {'email': 'test#example.com'}
Turns out the parsers need to be instances and not just classes and the data needs to be a JSON string:
import json
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': 'test#example.com'}
request = factory.post('/', json.dumps(data), content_type='application/json')
from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser()])
print(converted_request.data)

Parsing JSON incoming to a Webhook

I'm trying to build a webhook that receives JSON being POSTed from a third party service, Messagebird. In their documentation they have an example of an outgoing query:
GET http://your-own.url/script
?id=e8077d803532c0b5937c639b60216938
&recipient=31642500190
&originator=31612345678
&body=This+is+an+incoming+message
&createdDatetime=2016-05-03T14:26:57+00:00
My webhook is being built with Python in Django, and this is what I have in my views.py:
from django.shortcuts import render
from django.views.decorators.http import require_POST
from django.http import HttpResponse
from .models import UserText
#require_POST
def webhookmb(request):
usrtxt = json.loads(request.body.decode("utf-8"))
UserText.objects.create(
id = usrtxt['id']
recipient = usrtxt['recipient']
originator = usrtxt['originator']
body = usrtxt['body']
createdDatetime = usrtxt['createdDatetime']
)
return HttpResponse(200)
My goal is to read the JSON into a file usrtxt and then map those fields to a model. I'm getting this error (deployed on heroku):
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Is this because json.loads is trying to read the file and the first like starts with GET? Do I need to skip this line? Or is there another way to go about this?
This might seem overly simple but try adding #csrf_exempt decorator to your webhook.

Django: send json response from view to a specific template

The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), as a part of response. Also, the json response contains model and pk attribute, I want to remove them and send only the fields json attribute.
When I try as follows :
def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return HttpResponse (serializers.serialize('json', personal_detail_json), content_type='application/json');
I get json in a new page.
And when I try as follows :
def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/output.html", {'personal_detail': personal_detail})
I have to access the data via {{ personal_detail }} in my html, and not from response.
Also, the json response is as follows :
[
{
model: "buglockerApp.personal_details",
pk: "001",
fields: {
name: "Rajiv Gupta",
email: "rajiv#247-inc.com",
doj: "2016-06-22",
dob: "2016-06-22",
address: "Bangalore",
contact: "9909999999"
}
}
]
I don't want the model and pk to be sent as the response. Only fields should be sent as a part of response to webFiles/output.html file.
Thanks in advance!!
you can do the following in python2.7
import json
from django.http import JsonResponse
def view_personal_details (request):
personal_detail = serializers.serialize('json', personal_details.objects.all())
output = [d['fields'] for d in json.loads(personal_detail)]
# return render (request, "webFiles/output.html", {'personal_detail': output})
# for ajax response
return JsonResponse({'personal_detail': output})
or you can read the following for more clarification
https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-of-natural-keys
https://github.com/django/django/blob/master/django/core/serializers/base.py#L53
The default serializers always add the model and pk so that the data can be deserialized back into objects. Either you can write a custom serializer or can simply remove the unwanted data.
personal_details = [pd['fields'] for pd in personal_details]
This should give you a new list of dicts with personal details

Read request.POST with json data (Django)

I'm new on "Django".
I want read json data in "django" view. These data send from http://www.payplug.fr to my website into request.post. Here are my urls.py :
from credits.views import retour_ipn
urlpatterns = patterns('',
('^c/retour_ipn/$', retour_ipn),
)
And credits.views :
#csrf_exempt
def retour_ipn(request):
from base64 import b64decode, b64encode
header = request.META['HTTP_PAYPLUG_SIGNATURE']
signature = b64decode(header)
body = request.raw_post_data
data = json.loads(body)
print data
return HttpResponseRedirect('/')
After, signature will be analyses for save data in "django" models.

Categories