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 思路步骤: 创建一个可以序列化的类 去数据库取数据交给序列化的类处理 把序列化的数据返回前 ...
随机推荐
- 【Java】Java与数字证书
Java与数字证书 Java与数字证书 证书的签发和应用 证书的内容和意义 其它 证书(Certificate,也称public-key certificate)是用某种签名算法对某些内容(比如公钥) ...
- 【JavaEE】怎么设置tomcat管理员的用户名和密码
如果我们输入错误的Tomcat管理员密码,那么就有提示如下: 2 从它的提示信息中,我们就能找到解决方法,请留意上图中标出的位置! 我们首先打开Tomcat的配置文件,具体如下: 我们进入To ...
- SpringBoot | 第三十七章:集成Jasypt实现配置项加密
前言 近期在进行项目安全方面评审时,质量管理部门有提出需要对配置文件中的敏高文件进行加密处理,避免了信息泄露问题.想想前段时间某公司上传github时,把相应的生产数据库明文密码也一并上传了,导致了相 ...
- WPF OnApplyTemplate 不执行 或者执行滞后的疑惑
OnApplyTemplate 不执行 平时如何开发自定义控件的 在WPF自定义控件开发的过程中遇到了这样一个问题,属性更改事件在OnApplyTemplate之前执行.我在写自定义控件的时候,喜欢通 ...
- Oracle SQL Developer-3.2.20.09.87 Windows 10启动问题处理&配置
用了好多年的工具,准备在笔记本上使用时启动不了,但在办公室PC上可以正常使用.两者电脑OS都一样,一个是全新安装.一个是从Windows 7升级而来.下载了最新版发现版本到17了,Oracle刷版本号 ...
- ArcGIS API for JavaScript开发初探——HelloMap
1.前言 在开始ArcGIS API for JavaScript开发之前我们需要了解一些基本的知识: 1.开发工具选什么? 前端技术的开发工具选择是一个仁者见仁智者见智的问题,有人喜欢Hbuilde ...
- SpringBoot的启动报错
1.
- android-上下文菜单的创建 - 随心
//Menu设置//覆盖两个方法onCreateOptionsMenu(Menu menu).onOptionsItemSelected(MenuItem Item)//onCreateOptions ...
- DBA的做法
防止有人删除数据库,创建一个触发器当数据库被删除是发送一份邮件给管理员并撤销这个命令. Create trigger [tridbsafe]ON ALL SERVERFOR DROP_DATABASE ...
- 在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务
我的前一篇文章 使用Java+SAP云平台+SAP Cloud Connector调用ABAP On-Premise系统里的函数介绍了在SAP云平台的Neo环境下如何通过SAP Cloud Conne ...