如何使用Django将MySQL数据可视化到D3.js中?

4

我有一些数据存储在MySQL数据库中,希望使用d3.js来将数据可视化为一个气泡图。请问我能否在Django框架中实现这个需求?如果可以,具体怎么做呢?

2个回答

8

是的,您可以使用Django实现这一点。您需要做的就是创建一个Django PyDev(Python)应用程序。在settings.py文件中将数据库设置为:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'myDB',  # your mysql database name    
        'USER': '123', # your mysql user for the database
        'PASSWORD': '123', # password for user
        'HOST': '127.0.0.1', 
        'PORT': '3306', 
        } 

views.py 中的函数定义中,将 MySQL 连接设置为:
    conn = MySQLdb.connect (host = "127.0.0.1",
                        user = "root", # mysql root
                        passwd = "root", # mysql root password
                        db = "myDB")

使用游标从表中检索数据,然后将其转换为JSON。
cursor.execute ("select <column> from <table>")

rows=dictfetchall(cursor)


object_list = []
for row in rows:
    d = collections.defaultdict()
    d['name'] = row['name']       
    object_list.append(d)

j = json.dumps(object_list)
objects_file = 'path of json file to be created'
m = open(objects_file,'w')
print >> m,j    #to write to file
conn.close() 

def dictfetchall(cursor):
    "Returns all rows from a cursor as a dictionary"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]

现在,您可以使用此JSON文件创建任何类型的D3js。

dictfetchall()是Python函数吗? - Sreejith
不,我现在已经在代码中给出了定义,请检查。 - subina mohanan
在settings.py中设置数据库参数是必要的吗?似乎你可以直接在views.py中连接到你的数据库表。 - nlr25

1

你可以从views.py连接到MySQL数据库并查询数据,然后以所需格式(可能是JSON、CSV或XML)将其传递给HTML页面。从页面调用d3js脚本,并使用传递的对象作为数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接