1.修改setting.py文件
将创建的app配置到setting.py文件中去,app需要在settings里的INSTALLED_APPS注册
2.配置路由
一级路由
添加一个app下的路由
创建二级路由
在app下创建一个路由文件urls.py文件
3.创建模型类Model
# Create your models here.
from py2neo import Graph, Node, Relationship, cypher, Path
from django.db import models
class Neo4j(models.Model):
graph = None
def __init__(self):
print("create neo4j class ...")
#self.graph = Graph("http://localhost:7474", username="neo4j", password="chang1978")
def connectDB(self):
self.graph = Graph(
# "http://localhost:7474/db/data" # py2neo 2.0.8写法
host="127.0.0.1", # py2neo 3写法
user="neo4j",
password="neo4j"
)
def buildNodes(self,nodeRecord):
label = str(nodeRecord["n"].labels)[1:]
data = {"id": str(nodeRecord["n"].identity), "label": label, "name": str(nodeRecord["n"]["name"])}
# data = {"name": str(nodeRecord["n"]["name"]),"label": label}
# data = {"id": str(nodeRecord["n"].identity), "label": str(nodeRecord["n"].labels),"name": str(nodeRecord["n"]["name"])}
# data.update(nodeRecord["n"].properties)
# data.update(nodeRecord["n"])
return {"data": data}
def buildEdges(self,relationRecord):
data = {"source": str(relationRecord["r"].start_node.identity),
"target": str(relationRecord["r"].end_node.identity),
"relationship": relationRecord["r"]["name"]}
return {"data": data}
def get_graph(self,a):
str = f'MATCH (n) where n.name="{a}" RETURN n'
nodes1 = list(map(self.buildNodes, self.graph.run(str).data()))
str = f'MATCH (m)-[]->(n) where m.name="{a}" RETURN n'
nodes2 = list(map(self.buildNodes, self.graph.run(str).data()))
nodes = nodes1 + nodes2
str = f'MATCH (n)-[r]->() where n.name="{a}" RETURN r '
edges = list(map(self.buildEdges, self.graph.run(str).data()))
# 保证中文不乱码
datajson = {"nodes": nodes, "edges": edges}
return datajson
4.创建模板
在APP下创建一个模板文件templates,用于存放HTML页面模板,可以根据视图中传递的数据填充值
4.创建视图
在Django中,视图对WEB请求进行回应
视图接收reqeust对象作为第一个参数,包含了请求的信息
视图就是一个Python函数,被定义在views.py中
Django提供了函数Render()简化视图调用模板
from django.shortcuts import render,HttpResponse
from .models import Neo4j
def index(request):
neo = Neo4j()#
neo.connectDB()#调用models.py文件里的connectDB()函数
y=request.POST.get("disease")
Dict = neo.get_graph(y)
#print(Dict.keys())
#print(type(Dict["nodes"]))
#print(Dict["nodes"][0])
return render(request, "index.html", {"Dict":json.dumps(Dict)})