Django API 为 D3 提供数据
在工作中见过有的人即便使用了Django,依然还在采取json或geojson的文件形式为页面提供数据,相当于嵌入数据而非加载。下面是个简单有效的例子:
先从 model.py 开始
# models.py
from django.db import models class Play(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
urls.py 建立一个 API 的数据(JSON格式)输出路径,另一个给图像输出页面。
# urls.py
from django.conf.urls import url from .views import graph, play_count_by_month urlpatterns = [
url(r'^$', graph),
url(r'^api/play_count_by_month', play_count_by_month, name='play_count_by_month'),
]
views.py
# views.py
from django.db import connections
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render from .models import Play def graph(request):
return render(request, 'graph/graph.html') def play_count_by_month(request):
data = Play.objects.all() \
.extra(select={'month': connections[Play.objects.db].ops.date_trunc_sql('month', 'date')}) \
.values('month') \
.annotate(count_items=Count('id'))
return JsonResponse(list(data), safe=False)
下面则是HTML部分
<!DOCTYPE html>
<meta charset="utf-8">
<style> body {
font: 10px sans-serif;
} .axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
} .x.axis path {
display: none;
} .line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
} </style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script> var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom; var parseDate = d3.time.format("%Y-%m-%d").parse; // for dates like "2014-01-01"
//var parseDate = d3.time.format("%Y-%m-%dT00:00:00Z").parse; // for dates like "2014-01-01T00:00:00Z" var x = d3.time.scale()
.range([0, width]); var y = d3.scale.linear()
.range([height, 0]); var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom"); var yAxis = d3.svg.axis()
.scale(y)
.orient("left"); var line = d3.svg.line()
.x(function(d) { return x(d.month); })
.y(function(d) { return y(d.count_items); }); var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("{% url "play_count_by_month" %}", function(error, data) {
data.forEach(function(d) {
d.month = parseDate(d.month);
d.count_items = +d.count_items;
}); x.domain(d3.extent(data, function(d) { return d.month; }));
y.domain(d3.extent(data, function(d) { return d.count_items; })); svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis); svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Play count"); svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
}); </script>
</body>
</html>
输出结果,大家可以在admin里调整数据。
Django API 为 D3 提供数据的更多相关文章
- Django API验证(令牌)
1. 获取接口信息 Client端 import requests import time import hashlib ctime = time.time() key = 'akfljakfjakl ...
- Django API接口FK ManyTo Many 模板
Url from django.contrib import admin from django.urls import path, re_path from django.urls import i ...
- Django API view 登录认证
文件分类 url from django.contrib import admin from django.urls import path, re_path from django.urls imp ...
- 【AMAD】django-formapi -- 一个DJANGO API框架,可使用签名request,可使用form作为API的验证工具
动机 简介 个人评分 动机 如何快速构建API,使用view就行了? 如果快速构建一个可以验证参数的API,使用django-formapi1吧! 简介 class DivisionCall(call ...
- Django api
http://www.cnblogs.com/wulaoer/p/5276050.html
- Django API 自定义状态码
class BaseResponse(object): def __init__(self): self.code = 1000 self.data = None self.error = None ...
- django API返回中文乱码
renturn HttpResponse(json.dumps(data,ensure_ascii=False))
- 初识Django —Python API接口编程入门
初识Django —Python API接口编程入门 一.WEB架构的简单介绍 Django是什么? Django是一个开放源代码的Web应用框架,由Python写成.我们的目标是用Python语言, ...
- 【Django】ESRTful APi
如何利用rest framework搭建Django API框架! 环境:win10 python3.6 思路步骤: 创建一个可以序列化的类 去数据库取数据交给序列化的类处理 把序列化的数据返回前 ...
随机推荐
- 【JavaEE】tomcat部署项目的几种方式 .
一.静态部署1.直接将web项目文件件拷贝到webapps 目录中 Tomcat的Webapps目录是Tomcat默认的应用目录,当服务器启动时,会加载所有这个目录下的应用.所以可以将JSP程 ...
- Mercurial(HG) Windows+Eclipse安装、配置、使用
Mercurial(HG) Windows客户端安装 Mercurial(HG): http://mercurial.selenic.com/ Windows客户端下载:http://mercuria ...
- VS2015配置使用Sqlite以及EF6框架记录
项目中需要使用到Sqlite本地数据库保存数据,以防止离线情况下设备的正常使用. 一.下载vs2015下的sqlite插件,并安装 插件下载页面:http://system.data.sqlite.o ...
- Linux下安装软件遇见的问题汇总
1.安装monodevelop 安装环境Linux Mint17.1 在软件在中心直接安装monodevelop,安装完成后直接启动界面“一闪而过”,解决办法: 软件中心安装 mono-complet ...
- JS实现2048
2048这个游戏是通过对二维数组的操作来实现的,其算法核心如下: (以一行左移为例) c从0开始,遍历当前行中的元素,到<CN-1(CN是一个常量,表示的是游戏格子的列数)结束,每次+1 找到当 ...
- 前端Json数据模拟神器mockJs使用教程
一般项目做法: <html> <head> <script src="http://requirejs.org/docs/release/2.1.16/comm ...
- 报错:'byte' does not name a type
这个错误是因为你在.cpp/.h中使用 byte 这个类型,把他修改成int就ok了
- Linux uart程序
我用的是jetson tx1 开发板 都是linux系统出了串口文件可能不同其他的没有什么不同都能用. 我安装的是qt5 新建一个none qt c工程,用c 语言开发 期间调试了两天结果还是发送和 ...
- [Asp.Net] Form验证中 user.identity为false
这个方法可以是user.identity设置为true FormsAuthentication.SetAuthCookie(Username, true); 但是要开启form验证, 在配置文件中 & ...
- vue+node+mongodb实现的页面
源代码地址:https://github.com/GainLoss/vue-node-mongodb 目前这个项目实现的是: 1.利用vue-cli实现前台页面的编写 (1)页面的跳转利用的是vue- ...