forked from neo4j-examples/movies-python-bolt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
movies.py
106 lines (89 loc) · 3 KB
/
movies.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/env python
import os
from json import dumps
from flask import Flask, g, Response, request
from neo4j.v1 import GraphDatabase, basic_auth
app = Flask(__name__, static_url_path='/static/')
password = os.getenv("NEO4J_PASSWORD")
driver = GraphDatabase.driver('bolt://localhost',auth=basic_auth("neo4j", password))
def get_db():
if not hasattr(g, 'neo4j_db'):
g.neo4j_db = driver.session()
return g.neo4j_db
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'neo4j_db'):
g.neo4j_db.close()
@app.route("/")
def get_index():
return app.send_static_file('index.html')
def serialize_movie(movie):
return {
'id': movie['id'],
'title': movie['title'],
'summary': movie['summary'],
'released': movie['released'],
'duration': movie['duration'],
'rated': movie['rated'],
'tagline': movie['tagline']
}
def serialize_cast(cast):
return {
'name': cast[0],
'job': cast[1],
'role': cast[2]
}
@app.route("/graph")
def get_graph():
db = get_db()
results = db.run("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) "
"RETURN m.title as movie, collect(a.name) as cast "
"LIMIT {limit}", {"limit": request.args.get("limit", 100)})
nodes = []
rels = []
i = 0
for record in results:
nodes.append({"title": record["movie"], "label": "movie"})
target = i
i += 1
for name in record['cast']:
actor = {"title": name, "label": "actor"}
try:
source = nodes.index(actor)
except ValueError:
nodes.append(actor)
source = i
i += 1
rels.append({"source": source, "target": target})
return Response(dumps({"nodes": nodes, "links": rels}),
mimetype="application/json")
@app.route("/search")
def get_search():
try:
q = request.args["q"]
except KeyError:
return []
else:
db = get_db()
results = db.run("MATCH (movie:Movie) "
"WHERE movie.title =~ {title} "
"RETURN movie", {"title": "(?i).*" + q + ".*"}
)
return Response(dumps([serialize_movie(record['movie']) for record in results]),
mimetype="application/json")
@app.route("/movie/<title>")
def get_movie(title):
db = get_db()
results = db.run("MATCH (movie:Movie {title:{title}}) "
"OPTIONAL MATCH (movie)<-[r]-(person:Person) "
"RETURN movie.title as title,"
"collect([person.name, "
" head(split(lower(type(r)), '_')), r.roles]) as cast "
"LIMIT 1", {"title": title})
result = results.single();
return Response(dumps({"title": result['title'],
"cast": [serialize_cast(member)
for member in result['cast']]}),
mimetype="application/json")
if __name__ == '__main__':
app.run(port=8080)