python - Plotly.js 连接到 Django Rest Framework API - 这可能吗?如果可能的话,如何实现?

标签 python api django-rest-framework plotly

我正在我们公司的网络应用程序中测试plotly的使用。我知道plotly有它自己的API,但是可以连接到Django Rest框架API,因为它是基于python的?

如果可能的话 - 语法是什么样的?这是我到目前为止所拥有的:

div id="myDiv"></div>
  <script>
  var trace1 = {
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  type: 'scatter'
};

var trace2 = {
  x: [1, 2, 3, 4],
  y: [16, 5, 11, 9],
  type: 'scatter'
};

var data = [trace1, trace2];

Plotly.newPlot('myDiv', data);
  </script>

我不想在“x”和“y”中硬编码数据 - 我想指向 Django Rest 框架中的 json。数据库是MySQL。任何帮助是极大的赞赏!!!

谢谢!

最佳答案

我不确定这是否是您正在寻找的,但就我而言,我需要它连接到 django 中模型的数据。 为了做到这一点,我在我的views.py中有这个

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import MyModel

@api_view(['GET'])
def index(request):
    entries = MyModel.objects
    data = entries.values('x', 'y')
    context = {
        'x': [i['x'] for i in data],
        'y': [i['y'] for i in data]
    }
    print(context)
    return Response(context)

在我的plot.js 文件中

import React from 'react';
import Plot from 'react-plotly.js';

class Plot extends React.Component {
  state = {}

  async reload () {
      let url = '<django server address to view>'
      const res = await fetch(url);
      const info = await res.json();
      console.log(info)
      this.setState({
          x: info.x,
          y: info.y,
      });
  }

  async componentDidMount() {
      this.reload();
  }

  render() {
    return (
      <Plot
        data={[
          {
            x: this.state.x,
            y: this.state.y,
            type: 'scatter',
            mode: 'points-lines',
            marker: {color: 'red'},
          },
        ]}
        layout={ {width: 600, height: 480, title: 'A Fancy Plot'} }
      />
    );
  }
}

export default Plot

从那里您可以在您的 React 应用程序中使用 Plot 组件。

但是,我想知道是否有更有效的方法在 django 中进行查询来处理大量数据..

关于python - Plotly.js 连接到 Django Rest Framework API - 这可能吗?如果可能的话,如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33282447/

相关文章:

ios - 我们如何将具有库的 sdk/Framework 共享给其他项目?

php - Laravel 5.3 在 API 中过滤搜索数据

c++ - 如何检测API Hook?

django - 如何从 Heroku 上的 Django 项目正确地提供我的 Angular 应用程序静态文件?

python - 如何将查询中设置的page_size设置为分页元数据djangorest框架

django - Django Rest 框架的基于 key 的访问

python - 如何从二进制文件中读取除最后 X 字节以外的所有字节?

java - CreateProcess 错误=5,访问被拒绝 - pyspark

python - Spark Python Avro Kafka 解串器

python - 解析 URI 参数和关键字值对