栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python+canvasjs+jquery实现数据可视化

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python+canvasjs+jquery实现数据可视化

基于canvasjs实现数据的图表可视化,这个组件非常好用,而且漂亮,简单易集成。啥不多话,贴上最核心的代码先

资源:

 canvasjs下载链接:https://canvasjs.com/download-html5-charting-graphing-library/?f=chart

setting.py增加代码:

STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'common')]

控制器views.py

from django.shortcuts import HttpResponse,redirect,render
from django.http import JsonResponse,HttpRequest
from . import lib as lib

def line(request:HttpRequest):
    return render(request,"line.html")

def spline(request:HttpRequest):
    return render(request,"spline.html")

接口api.py

from django.shortcuts import HttpResponse,redirect,render
from django.http import JsonResponse,HttpRequest
from . import lib as lib

def line(request:HttpRequest):
    points=lib.line_data()
    return JsonResponse({
                "animationEnabled": "true",
                "theme": "light2",
                "title":{
                    "text": "Line"
                },
                "axisY": {
                    "title": "Value",
                    "valueFormatString": "$#"
                },
                "legend": {
                    "cursor": "pointer",
                    "itemclick": "toggleDataSeries"
                },
                "data": [{
                    "name": "DATA1",
                    "showInLegend": "true",
                    "type": "line",
                    "dataPoints": [
                        {"label": p[0],"y":p[1]} for p in points
                    ]
                }]
            })
def spline(request:HttpRequest):
    points=lib.line_data()
    return JsonResponse({
                "animationEnabled": "true",
                "exportEnabled": "true",
                "theme": "light2",
                "title":{
                    "text": "SPLine"
                },
                "axisY": {
                    "title": "Value",
                    "valueFormatString": "$#"
                },
                "legend": {
                    "cursor": "pointer",
                    "itemclick": "toggleDataSeries"
                },
                "data": [{
                    "name": "DATA1",
                    "showInLegend": "true",
                    "type": "spline",
                    "dataPoints": [
                        {"label": p[0],"y":p[1]} for p in points
                    ]
                }]
            })

路由器:

from django.contrib import admin
from django.urls import path
from . import views
from . import api
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/line/',api.line),
    path('api/spline/',api.spline),
    path('line/',views.line),
    path('spline/',views.spline)
]

库lib.py

from sqlite.SQLITE import SQLITE
from charts.settings import BASE_DIR
def line_data():
    sqlite=SQLITE(BASE_DIR / "db.sqlite3")
    dt=sqlite.query("select value,text from data")
    points=[]
    for row in dt:
        points.append((row[1],row[0]))
    return points

SQLITE封装类:

import sqlite3

class SQLITE(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super(SQLITE, cls).__new__(cls)
        return cls._instance

    def __init__(self, db_name):
        self.db_name = db_name
        self.connect = sqlite3.connect(self.db_name,check_same_thread=False)
        self.cursor = self.connect.cursor()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connect.close()

    def execute_sql(self, sql):
        try:
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            self.connect.rollback()
    def query(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as e:
            return False
    def executemany_sql(self, sql, data_list):
        try:
            self.cursor.executemany(sql, data_list)
            self.connect.commit()
        except Exception as e:
            self.connect.rollback()
            raise Exception("executemany failed")

# db=SQLITE("../db.sqlite3")
# import random
# db.cursor.execute("drop table if exists data")
# db.cursor.execute("""create table data (
#     id INTEGER PRIMARY KEY AUTOINCREMENT,
#     value REAL,
#     text TEXT,
#     date TEXT DEFAULT (datetime('now','localtime'))
#     )""")
# data=[]
# for i in range(100):
#     data.append((random.randint(1,100),"date %d" % i))
# db.cursor.executemany("INSERT INTO data (value,text) VALUES (?,?)",data)
# dt=db.query("select value,text from data")
# db.connect.commit()
# print(dt)
# db.cursor.execute("drop table if exists COMPANY")
# db.cursor.execute("create table data (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT, date TEXT)")
# db.cursor.execute("insert into data(text,date) values ('test','2022-02-10')")
# db.cursor.execute("insert into data(text,date) values ('marvelhonor','2022-02-10')")
# db.cursor.execute("""CREATE TABLE COMPANY(
#    ID INTEGER PRIMARY KEY   AUTOINCREMENT,
#    NAME           TEXT      NOT NULL,
#    AGE            INTEGER       NOT NULL,
#    ADDRESS        TEXT,
#    SALARY         REAL,
#    DATETIME       TEXT DEFAULT (datetime('now','localtime'))
# )""")
# db.cursor.executemany("INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?)",
#               [('Paul', 32, 'California', 20000.00),('Allen', 25, 'Texas', 15000.00),
#                ('Teddy', 23, 'Norway', 20000.00),('Mark', 25, 'Rich-Mond ', 65000.00)])
# dt=db.query("select * from COMPANY")
# for row in dt:
#     print(row)
# print()
# db.execute_sql("select * from data")
# dt=db.cursor.fetchall()
# for row in dt:
#     print(row)

模板line.html




    
    CanvasJs Line
    
    





模板spline.html




    
    CanvasJs Line
    
    





启动

 访问示例

 

 自己部署,带动画哦。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/966003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号