从Django servi获取JSON数据

2024-04-26 14:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我对django和python完全陌生。现在我想开发一个简单的服务。这就是我的想法:我通过POST将3个参数从JS发送到Django(来自另一个域CORS),在Django中,python处理数据并返回JSON,仅此而已。你知道吗

我为什么要这么做!?,因为我需要pyhon上提供的特殊函数:Statistics。你知道吗

这是我开始的代码:

网址.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)]

控制程序.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())

这是非常简单的codeigniter或laravel。但我不知道如何开始这对django。你知道吗

我该怎么做?你知道吗

谢谢! 罗西


Tags: djangofrompyimporturlgetadminnp
2条回答

做这个

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())

或者,如果您使用的是Django的旧版本,您可以返回这个

HttpResponse(json.dumps(line.get_xydata()), content_type="application/json")

^{}取代/替换的render_to_response期望将字典中的变量作为“上下文”发送到模板。您的get_data_weibull视图应该接受一个变量,通常称为requestself仅用作对象函数的第一个参数的名称)。然后可以用行数据构造一个字典,并将其作为'JsonResponse`返回。你知道吗

相关问题 更多 >