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 思路步骤: 创建一个可以序列化的类 去数据库取数据交给序列化的类处理 把序列化的数据返回前 ...
随机推荐
- hadoop操作权限问题:WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
今天想从Eclipse向hdfs上传文件时遇到了一个权限问题,日志如下: ERROR hive.log: Got exception: org.apache.hadoop.security.Acces ...
- jstl core and jstl fn
jstl标签使用时必须加taglib:<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core&quo ...
- java Smaphore 控制并发线程数
概念: Semaphore(信号量)是用来控制同事访问特定资源的线程数量,它通过协调各个线程,已保证合理的使用公共资源. 应用场景: Semaphore 可以用于做流量控制,特别是共用资源有限的应用场 ...
- smarty基本用法
简介: 1.smarty语法:它是php的一种模板引擎 它的设计特点是:业务逻辑与显示逻辑分离 Smarty的标签都是使用定界符{ }括起来注释:{* 我是Smarty的注释内容 *} <u ...
- <Android 基础(三)> MVP模式
前言 MVP,这里指的并不是篮球比赛中的MVP(最有价值球员),而是一种代码框架和设计思想,它是由MVC演变而来的. MVP模式(Model-View-Presenter) 是MVC模式的一个衍生.主 ...
- IntelliJ IDEA IDEA 2018 激活注册码
K03CHKJCFT-eyJsaWNlbnNlSWQiOiJLMDNDSEtKQ0ZUIiwibGljZW5zZWVOYW1lIjoibnNzIDEwMDEiLCJhc3NpZ25lZU5hbWUiO ...
- newsyslog.conf详解
newsyslog.conf 指出了哪个日志文件要被管理,要保留多少和它们什么时候被创建.日志文件可以在它们达到一定大小或者在特定的日期被重新整理.# configuration file for n ...
- /pentest/cisco/cisco-auditing-tool
/pentest/cisco/cisco-auditing-tool ./CAT -h host 扫描单个主机 -w wordlist 猜测团体名称列表 -a passlist 猜测密码列 ...
- PHP代码规范的一些总结
世界第一语言在手,辅以前人的最佳实践,天下又算什么. 1.代码是写给小白用的 注释,注释,注释,重要的事情说三遍.我们做的虽然不是拿去卖源码的商业产品,不需要把注释写的多么优美.但也不要太过吝啬,到头 ...
- shell实现网站备份
#!/bin/bash ##back web directory scripts #需要备份的目录写入与脚本同级目录test.txt文件中 DIR="/data/server/www&quo ...