Skip to content

Commit e881867

Browse files
authored
Python Aura Example (#431)
* aura example * aura example * add placeholders * update link * addressing martin's feedback * remove another tag * remove f string * rename to be more generic * add tags
1 parent 29cd422 commit e881867

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
4+
# Copyright (c) 2002-2020 "Neo4j,"
5+
# Neo4j Sweden AB [http://neo4j.com]
6+
#
7+
# This file is part of Neo4j.
8+
#
9+
# Licensed under the Apache License, Version 2.0 (the "License");
10+
# you may not use this file except in compliance with the License.
11+
# You may obtain a copy of the License at
12+
#
13+
# http://www.apache.org/licenses/LICENSE-2.0
14+
#
15+
# Unless required by applicable law or agreed to in writing, software
16+
# distributed under the License is distributed on an "AS IS" BASIS,
17+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18+
# See the License for the specific language governing permissions and
19+
# limitations under the License.
20+
21+
22+
import pytest
23+
24+
from contextlib import redirect_stdout
25+
from io import StringIO
26+
27+
# tag::driver-introduction-example-import[]
28+
from neo4j import GraphDatabase
29+
import logging
30+
from neo4j.exceptions import ServiceUnavailable
31+
# end::driver-introduction-example-import[]
32+
33+
from neo4j._exceptions import BoltHandshakeError
34+
35+
36+
# python -m pytest tests/integration/examples/test_aura_example.py -s -v
37+
38+
# tag::driver-introduction-example[]
39+
class App:
40+
41+
def __init__(self, uri, user, password):
42+
# Aura queries use an encrypted connection
43+
self.driver = GraphDatabase.driver(uri, auth=(user, password), encrypted=True)
44+
45+
def close(self):
46+
# Don't forget to close the driver connection when you are finished with it
47+
self.driver.close()
48+
49+
def create_friendship(self, person1_name, person2_name):
50+
with self.driver.session() as session:
51+
# Write transactions allow the driver to handle retries and transient errors
52+
result = session.write_transaction(
53+
self._create_and_return_friendship, person1_name, person2_name)
54+
for row in result:
55+
print("Created friendship between: {p1}, {p2}".format(p1=row['p1'], p2=row['p2']))
56+
57+
@staticmethod
58+
def _create_and_return_friendship(tx, person1_name, person2_name):
59+
# To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/
60+
# The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/
61+
query = """
62+
CREATE (p1:Person { name: $person1_name })
63+
CREATE (p2:Person { name: $person2_name })
64+
CREATE (p1)-[:KNOWS]->(p2)
65+
RETURN p1, p2
66+
"""
67+
result = tx.run(query, person1_name=person1_name, person2_name=person2_name)
68+
try:
69+
return [{"p1": row["p1"]["name"], "p2": row["p2"]["name"]}
70+
for row in result]
71+
# Capture any errors along with the query and data for traceability
72+
except ServiceUnavailable as exception:
73+
logging.error("{query} raised an error: \n {exception}".format(
74+
query=query, exception=exception))
75+
raise
76+
77+
def find_person(self, person_name):
78+
with self.driver.session() as session:
79+
result = session.read_transaction(self._find_and_return_person, person_name)
80+
for row in result:
81+
print("Found person: {row}".format(row=row))
82+
83+
@staticmethod
84+
def _find_and_return_person(tx, person_name):
85+
query = """
86+
MATCH (p:Person)
87+
WHERE p.name = $person_name
88+
RETURN p.name AS name
89+
"""
90+
result = tx.run(query, person_name=person_name)
91+
return [row["name"] for row in result]
92+
93+
if __name__ == "__main__":
94+
# Aura uses the "bolt+routing" protocol
95+
bolt_url = "%%BOLT_URL_PLACEHOLDER%%"
96+
user = "<Username for Neo4j Aura database>"
97+
password = "<Password for Neo4j Aura database>"
98+
app = App(bolt_url, user, password)
99+
app.create_friendship("Alice", "David")
100+
app.find_person("Alice")
101+
app.close()
102+
# end::driver-introduction-example[]
103+
104+
105+
def test_driver_introduction_example(uri, auth):
106+
try:
107+
s = StringIO()
108+
with redirect_stdout(s):
109+
app = App(uri, auth[0], auth[1])
110+
app.create_friendship("Alice", "David")
111+
app.find_person("Alice")
112+
app.close()
113+
114+
assert s.getvalue().startswith("Found person: Alice")
115+
except ServiceUnavailable as error:
116+
if isinstance(error.__cause__, BoltHandshakeError):
117+
pytest.skip(error.args[0])

0 commit comments

Comments
 (0)