I'm complety new on django and python. Now I'mtriying to develop a simple service. This is the idea: I send 3 parameters from JS to Django by POST, (from another domain, CORS) in Django, python process the data and return me JSON, that all.
Why have I do that!? , because I need special functions available on pyhon: Statistics.
This is the code that I begin:
urls.py
from django.conf.urls import url
from django.contrib import admin
from . import controlador #este sisi
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^get_weibull/', controlador.get_data_weibull)]
controlador.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
import numpy as np
import matplotlib.pyplot as plt
def weib(x,n,a):
return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
def get_data_weibull(self):
a = 5. # shape
s= np.random.weibull(a, 1000)
x = np.arange(1,100.)/50.
count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
x = np.arange(1,100.)/50.
scale = count.max()/weib(x, 1., 5.).max()
plt.plot(x, weib(x, 1., 5.)*scale)
ax = plt.gca()
line = ax.lines[0]
return render_to_response(line.get_xydata())
This is very simply on codeigniter or laravel. but I dont know how begin this on django.
How Can I do that?
Thanks! Rosie
render_to_response, which has been superseded/ replaced by by render expects to send variables in a dictionary as a "context" to a template. Your get_data_weibull view should accept one variable, typically called request (self is only used as the name of the first argument to an object's function). Then you can construct a dictionary with your line data and return that as a 'JsonResponse`.
Do this
from django.http import JsonResponse
def get_data_weibull(self):
a = 5. # shape
s= np.random.weibull(a, 1000)
x = np.arange(1,100.)/50.
count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
x = np.arange(1,100.)/50.
scale = count.max()/weib(x, 1., 5.).max()
plt.plot(x, weib(x, 1., 5.)*scale)
ax = plt.gca()
line = ax.lines[0]
return JsonResponse(line.get_xydata())
or if your using an old version of Django, you can return this instead
HttpResponse(json.dumps(line.get_xydata()), content_type="application/json")