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 思路步骤: 创建一个可以序列化的类 去数据库取数据交给序列化的类处理 把序列化的数据返回前 ...
随机推荐
- HBase基础讲解
HBase定义 HBase 是一个高可靠.高性能.面向列.可伸缩的分布式存储系统,利用Hbase技术可在廉价PC Server上搭建 大规模结构化存储集群. HBase 是 ...
- Android模拟器使用SD卡
在Android的应用开发中经常要用到与SD卡有关的调试,本文就是介绍关于在Android模拟器中SD卡的使用 一. 准备工作 在介绍之前首先做好准备工作,即配好android的应用开发环境 ...
- java简单使用netty
一 整合 由于本人的学过的技术太多太乱了,于是决定一个一个的整合到一个springboot项目里面. 附上自己的github项目地址 https://github.com/247292980/spri ...
- ssm(Spring、Springmvc、Mybatis)实战之淘淘商城-第八天(非原创)
文章大纲 一.课程介绍二.Solr基本介绍三.ssm整合Solr四.项目源码与资料下载五.参考文章 一.课程介绍 一共14天课程(1)第一天:电商行业的背景.淘淘商城的介绍.搭建项目工程.Svn的 ...
- 本地添加Maven管理
Maven下载安装: 1 .Maven下载地址:http://maven.apache.org/ 2 .下载解压到本地指定目录:记住该路径! 3 .新建/修改环境变量-系统变量: 名:M2_HOME ...
- 洛谷P1397 [NOI2013]矩阵游戏(十进制矩阵快速幂)
题意 题目链接 Sol 感觉做这题只要对矩阵乘法理解的稍微一点就能做出来对于每一行构造一个矩阵A = a 1 0 b列与列之间的矩阵为B = c 1 0 d最终答案为$A^{n - ...
- Today is the first day of the rest of your life.
Today is the first day of the rest of your life. 今天是你余下人生的第一天.
- Css文件目录结构
一般一个网站会有这么三个样式: global.css | reset.css(格式化样式) common.css(公共组件样式) layout.css(当前页面样式) global.css | res ...
- SqlServer查询文件组被占用情况
在SqlServer中,删除一个文件组 alter database [xxxxx] remove filegroup FGMonthTurnIntroduceByMonth13 有时候会遇到如下报错 ...
- GC Root总结
为什么80%的码农都做不了架构师?>>> JVM根据GC Roots算法判定一个对象需要被回收,GC Roots一般在JVM的栈区域里产生. GC Roots原理 GC Roots基 ...