Django: Is it possible create and send Json from a view to another server? - ajax

If i have a link like this one Get User Data who points in a view inside my own server, is there any way to send a json object (maybe just maybe with ajax?) to another external server and retrieve an answer? Something like this:
from django.shortcuts import render
def profile(request):
#send a json object to another server like http://www.myotherserver.com/user
#get the answer and process it
return render(request, 'accounts/profile.html' ,
{'profile_user': data_from_the_external_server})
The above i can implement it of course with jquery-ajax but i just was wondering if i can do it this way...
Thanks in advance.

Of course you can. Why wouldn't it be possible?
Don't code this in AJAX if that's not necessary.
There are 2 things you need, you need to prepare the JSon to send and then you need to send it to the API you want:
Look at "simplejson" to create the json data to send.
Look at "urllib" to send a request to another server in Python (like here: How to send a POST request using django?)
Also do not put it straight in your view. Create a new class for it. So in your view you'll have something like that:
def profile(request):
# instantiate your service here (better with DI)
profile_user = my_service.get_profile_user()
return render(
request,
'accounts/profile.html' ,
{
'profile_user': profile_user
}
)

If you need to send HTTP data (via a POST or GET) to another server and receive a result from within your view, you can use Python's urllib2 library. However there is an easier third party library called Requests which can handle this task for you.

Related

Is it better to retrieve data through AJAX or returning it alongside view from Controller (Laravel)?

So the scenario is getting data we need from controller and using it in our view. But there are two options, you can have either this line in your "show" method:
UserController#show
return view('webpage');
And in the 'webpage' you can send an Ajax request to UserController#fetch and get that data. Or you can get the data from database in UserController#show and then send it alongside view like this:
UserController#show
return view('store', compact('store'));
But which is the more efficient and secure way of doing this?
It really depends on what you're doing, if the data you're requesting and the process you're running takes a lot of time or in a future it would, ajax is the way to go, but if process is short and the requested data from your model is small, then you can request it on the same method that returns your view and send the data to it.

Safely save data to django model using AJAX

I have a model say TestModel as follows:
class TestModel(models.Model):
name = models.CharField()
description = models.TextField()
Now I can use a ModelForm to save data to this model. However, say I want to use Ajax and send a url as follows savethis?name=ABC&desc=SomeRandomDescription to a view that handles it as follows:
def savethis(request):
if request.GET['name'] and request.GET['desc']:
name = request.GET['name']
desc = request.GET['desc']
test = TestModel(name=name, description=desc)
test.save
return HttpResponse('Ok')
else:
return HttpResponse('Fail')
What's to stop someone from running a script that can easily hit this url with valid data and thus save data to my model? How do I ensure that incoming data is sent only from the right source?
One option is sending the data as JSON in a Post request but even that's not too hard to emualte.
Seems that you have stumbled upon the great security flaw that is Cross-site Scripting attacks. They are several ways you can get around it, but going into all of them in one answer would be fruitless. I suggest you Google the term and do some poking around, and you will find several different methods on how to protect your site better.
Django has a security page dedicated to talking about how to protect your site.

Does Parse.Cloud.beforeRead exist is some form?

In Parse there is something called:
Parse.Cloud.beforeSave
I wonder if there is something to play the role of a:
Parse.Cloud.beforeRead
I need a way to control what is going to be returned to the user when a request is made to the DB.
In particular in certain circomstances, depending on information on the server, I want to force blank fields in the result of the DB request made by the user. Any standard way to do this?
There is no Parse.Cloud.beforeRead kind of function supported by Parse.
Instead, you can define a custom cloud function using
Parse.Cloud.define('readObjects', function(request, response) {...} );
that returns array of objects. This function will act as a wrapper over the Parse query.
Then, your client apps should be calling this cloud function to fetch objects rather than direct Parse.Query requests.

What should I name the actions for ajax requests?

Let's say I have an action:
def result = Action { Ok(views.html.home.result()) }
From result view I want to send ajax requests to the server. What's the standard (if any) way to name the actions that receive such the ajax requests? It might be something like:
def getResultAjax(param1: Int) = //....
To my mind, it look clumsy.
Your ideas?
There's no such convention in Play, anyway action's name should rather contain info about returned data i.e. listOfBooks then just getResult.
On the other hand when there's a lot of different methods (some common, other for ajax requests) it can be cleaner if you'll use ajaxListOfBooks or create BooksAjax controller to handle AJAX request only.
BTW: Purists would say that the requests REST's HTTP methods should also be taken into account, and then action names can be simplified, pseudo routes:
GET /ajax/books Books.list
GET /ajax/books/:id Books.get(id)
PUT /ajax/books Books.create
POST /ajax/books/:id Books.update(id)

Ajax views with django

I'm working on a pretty big project right now where every view should be accessible via a normal request and an ajax request via the same url. I'm looking for ideas on how to create a small framework to handle this in a very generic way. Depending on if the view is called via ajax or not it needs to render a different template and return a json instead of a HttpResponse object. I'd like to collect any ideas on this topic - the main goal should be not to avoid the dry principle and make code that is as reusable as possible. I was already considering different options as generic views, decorators on views etc, but I'm open to anything. So please let me hear your suggestions or point me towards any readymade snippets you know!
This article seems to be quite a good tutorial on how to work with both ajax and regular requests. The request object has a method is_ajax() which will look for HTTP_X_REQUESTED_WITH: XMLHttpRequest. This will of course depend on these values being set correctly by the javascript sending the request.
From the article:
from django.http import HttpResponse
from django.core import serializers
from django.shortcuts import render_to_response
from your_app.models import ExampleModel
def xhr_test(request, format):
obj = ExampleModel.objects.all()
if request.is_ajax():
data = serializers.serialize('json', obj)
return HttpResponse(data,'json')
else:
return render_to_response('template.html', {'obj':obj}, context=...)
Or, you could use django-piston which is a RESTful framework for Django. I use this module in my project. You can define resources (sort of like views), and depending on either the mime-type or format passed to your url, it will emit either html, xml, or json. This will probably be the best way to go if every single view (or a large majority) need to be returned in different formats.
I have used a decorator for this. Have the view return the context, the template, and an alternate template.
If the Ajax version wants to return data, the third return value can be the data object to turn into JSON.

Resources