本文整理汇总了Python中py2neo.authenticate函数的典型用法代码示例。如果您正苦于以下问题:Python authenticate函数的具体用法?Python authenticate怎么用?Python authenticate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了authenticate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect_to_db
def connect_to_db(self, uri, username, password):
if (uri is None) or (username is None) or\
(password is None):
raise ValueError('Null Argument detected')
authenticate(uri, username, password)
return Graph()
示例2: FindSimilarRepositories
def FindSimilarRepositories(InputrepoK):
#Sanitize input
Inputrepo = bleach.clean(InputrepoK).strip()
host = os.environ['LOCALNEO4JIPPORT']
login = os.environ['LOCALNEO4JLOGIN']
password = os.environ['LOCALNEO4JPASSWORD']
authenticate(host,login,password)
graph = Graph(os.environ['neoURLlocal'])
output = ""
path1 = "<a href=\"/?q=repository "
path2 = "&action=Search\" class=\"repositoryinfo\">"
path3 = "</a>"
#Find similar repository > 1 connections
query1="MATCH (a {id:\"" + Inputrepo + "\"})"
query2="-[r1:IS_ACTOR|IN_ORGANIZATION]->(match)<-[r2:IS_ACTOR|IN_ORGANIZATION]-(b) "
query3="with b, collect (distinct match.id) as connections, collect (distinct type(r1)) as rel1 "
query4="where length(connections) >= 1 return b.id,length(connections) as count,length(rel1) as rel "
query5="order by length(connections) desc limit 5"
query = query1 + query2 + query3 + query4 + query5
#print query
a = graph.cypher.execute(query)
for record in a:
if (record['rel'] < 2):
output += "<li>" + path1 + record['b.id'] + path2 + record['b.id'] + path3 + ": " + str(record['count']) + " contributors in common</li>"
else:
output += "<li>" + path1 + record['b.id'] + path2 + record['b.id'] + path3 + ": " + str(record['count']-1) + " contributors in common & belong to same organization</li>"
if (len(output) > 0):
return ("<ul>" + output + "</ul>")
else:
#Nothing found!
return "<span class=\"text-danger\">You got me stumped!</span>"
示例3: createRelationshipWithProperties
def createRelationshipWithProperties():
print("Start - Creating Relationships")
# Authenticate the user using py2neo.authentication
# Ensure that you change the password 'sumit' as per your database configuration.
py2neo.authenticate("localhost:7474", "neo4j", "sumit")
# Connect to Graph and get the instance of Graph
graph = Graph("http://localhost:7474/db/data/")
# Create Node with Properties
amy = Node("FEMALE", name="Amy")
# Create one more Node with Properties
kristine = Node("FEMALE",name="Kristine")
# Create one more Node with Properties
sheryl = Node("FEMALE",name="Sheryl")
#Define an Object of relationship which depicts the relationship between Amy and Kristine
#We have also defined the properties of the relationship - "since=2005"
#By Default the direction of relationships is left to right, i.e. the -->
kristine_amy = Relationship(kristine,"FRIEND",amy,since=2005)
#This relationship is exactly same as the earlier one but here we are using "Rev"
#"py2neo.Rev = It is used to define the reverse relationship (<--) between given nodes
amy_sheryl=Relationship(amy,Rev("FRIEND"),sheryl,since=2001)
#Finally use graph Object and Create Nodes and Relationship
#When we create Relationship between, then Nodes are also created.
resultNodes = graph.create(kristine_amy,amy_sheryl)
#Print the results (relationships)
print("Relationship Created - ",resultNodes)
示例4: following2
def following2(n):
authenticate("localhost:7474", "neo4j", "parola")
graph = Graph("http://localhost:7474/db/data/")
followingResults = graph.cypher.execute("MATCH (a)-[r:FOLLOWS]->(b) WHERE id(a)= "+n+" RETURN b")
followingName = []
for person in followingResults:
cleanName = re.findall('"([^"]*)"', str(person[0]))
cleanName[2] = str (int(cleanName[2]) - 1)
followingName.append(cleanName)
followerResults = graph.cypher.execute("MATCH (a)-[r:FOLLOWS]->(b) WHERE id(b)= "+n+" RETURN a")
followerName = []
for person in followerResults:
cleanName = re.findall('"([^"]*)"', str(person[0]))
cleanName[2] = str (int(cleanName[2]) - 1)
followerName.append(cleanName)
thisUser = graph.cypher.execute("Match (joe) where id(joe)= "+n+" return joe")
thisUserCleanName = re.findall('"([^"]*)"', str(thisUser[0][0]))
userPostResult = graph.cypher.execute("MATCH (a)-[r:POSTED]->(b)<-[t:LIKES]-(q) WHERE id(a)="+n+" RETURN b.Name,b.id ,count(t) ORDER BY count(t) DESC")
userPosts = []
for post in userPostResult:
cleanName = re.findall('"([^"]*)"', str(post[0]))
userPosts.append(userPostResult)
recommendationsResult = graph.cypher.execute("MATCH (joe)-[:FOLLOWS*2..2]->(friend_of_friend) WHERE NOT (joe)-[:FOLLOWS]-(friend_of_friend) and friend_of_friend.id <> joe.id and id(joe) = "+n+" RETURN friend_of_friend.Name,friend_of_friend.Username,friend_of_friend.id,Count(*) ORDER BY COUNT(*) DESC , friend_of_friend.Name LIMIT 10")
return render_template("index.html",
title='Home',
followings=followingName,
followers=followerName,
followingcount = len(followingName),
followercount = len(followerName),
thisUser = thisUserCleanName,
posts=userPosts,
recommendations = recommendationsResult)
示例5: __init__
def __init__(self):
authenticate("localhost:7474", "neo4j", "vai")
global graph
graph = Graph("http://localhost:7474/db/data/")
global minSimilarityScore
minSimilarityScore=0.2
global fileName
示例6: make_sequence
def make_sequence(self):
authenticate(settings.NeoHost, settings.NeoLog, settings.NeoPass)
graph = Graph("{0}/db/data/".format(settings.NeoHost))
query = """MATCH (start:Video)-[:Jaccard*5..10]->(sequence:Video)
WHERE start<>sequence MATCH p=shortestPath((start:Video)-[:Jaccard*]->(sequence:Video))
WHERE NONE (n IN nodes(p) WHERE size(filter(x IN nodes(p) WHERE n = x))> 1)
RETURN EXTRACT(n IN NODES(p)|[n.id, n.rating]) LIMIT 100000"""
r1 = graph.run(query).data()
k = 0
for i in r1:
#print(i.values)
for video in i['EXTRACT(n IN NODES(p)|[n.id, n.rating])']:
#print(video)
self.seq_ids.append(k)
self.video_ids.append(video[0])
self.ratings.append(video[1])
k+=1
data = {'sequence': self.seq_ids, 'video': self.video_ids, 'rating': self.ratings}
df = pd.DataFrame(data)
df = df[pd.notnull(df['video'])]
print(df)
dz = df.groupby('sequence')['rating'].std()
print(dz)
path = '{0}/{1}/'.format(settings.VideosDirPath, self.game)
if not os.path.exists(path):
os.makedirs(path)
file_name = '{0}/sequences.csv'.format(path)
df.to_csv(file_name, encoding='utf-8')
summary_data = '{0}/summary.csv'.format(path)
dz.to_csv(summary_data, encoding='utf-8')
return
示例7: authenticate
def authenticate(self, username, password):
try:
from py2neo import authenticate
authenticate(self.host_port, username, password)
return True
except ImportError:
return False
示例8: connectGraph
def connectGraph(self):
# Authenticate the user using py2neo.authentication
# Ensure that you change the password 'sumit' as per your database configuration.
py2neo.authenticate("localhost:7474", "neo4j", "sumit")
# Connect to Graph and get the instance of Graph
graph = Graph("http://localhost:7474/db/data/")
return graph
示例9: __init__
def __init__(self):
self.logger = open("zalando_logger","a")
self.logger.write("Checking for directory...\n")
self.logger.write("Creating Zalando Object...\nInitializing Object variables...\n")
self.set_directory()
self.BASE_URL = "https://www.zalando.co.uk"
self.initial_page = ['https://www.zalando.co.uk/womens-clothing','https://www.zalando.co.uk/mens-clothing']
self.parameters = ['Women','Men']
self.subcategories = [dict() for x in range(2)]
authenticate("localhost:7474","neo4j","awdr.;/")
self.zalando_graph = Graph()
try:
self.zalando_graph.schema.create_uniqueness_constraint('Zalando', 'article_number')
except Exception as e:
self.logger.write("uniqueness constraint already set\n")
self.count = 0
self.xml_root = Element('Properties')
self.properties = open("clothing_properties.xml","w")
self.logger.write("Zalando Object: " + str(self)+"\n")
for i in range(len(self.initial_page)):
page_html = requests.get(self.initial_page[i]).content
page_soup = BeautifulSoup(page_html,"lxml")
self.get_clothing_attributes(page_soup,i)
self.build_zalando_database(page_soup,self.parameters[i])
self.set_attributes(i)
self.properties.write(tostring(self.xml_root))
示例10: connect
def connect(self):
conf = self.get_config()
authenticate(conf['host'] + ":" + conf['port'],conf['username'],conf["password"])
try:
self.neo = Graph("http://" + conf['host'] + ":" + conf["port"] + "/db/data")
except:
print "Failed to connect!"
示例11: main
def main(project_directory, ignore_files):
authenticate("localhost:7474", "neo4j", "haruspex")
graph_db = Graph()
dossier = os.path.join(project_directory + "/pages")
if os.path.exists(dossier):
# Pour chaque fiche, analyser son contenu
# et créer les noeuds/liens correspondants
files = [f for f in listdir(dossier) if isfile(join(dossier, f))]
for fiche in files:
if (fiche not in ignore_files):
fiche_analysee = analyseFiche(fiche, dossier, graph_db)
ficheDocumentation(fiche_analysee, "references", dossier,
ignore_files[0], graph_db)
ficheDocumentation(fiche_analysee, "images", dossier,
ignore_files[1], graph_db)
else:
files = [f for f in listdir(project_directory) if (isfile(join(project_directory, f)) and f.endswith('.txt'))]
#TODO récupérer les métadonnées d'omeka sur les documents
for document in files:
print(document.strip(project_directory))
fiche = Fiche(document.replace(project_directory,'').replace('.txt', ''), '', '',
'', '', '')
fiche.create_node(graph_db)
示例12: main
def main():
define("host", default="127.0.0.1", help="Host IP")
define("port", default=8080, help="Port")
define("neo4j_host_port", default='127.0.0.1:7474', help="Neo4j Host and Port")
define("neo4j_user_pwd", default='neo4j:neo4j', help="Neo4j User and Password")
tornado.options.parse_command_line()
print('Connecting to Neo4j at {0}...'.format(options.neo4j_host_port))
user = options.neo4j_user_pwd.split(':')[0]
pwd = options.neo4j_user_pwd.split(':')[1]
authenticate(options.neo4j_host_port, user, pwd)
db = Graph('http://{0}/db/data/'.format(options.neo4j_host_port))
template_dir = os.getenv('OPENSHIFT_REPO_DIR', os.path.dirname(__file__))
template_dir = os.path.join(template_dir, 'templates')
static_dir = os.getenv('OPENSHIFT_DATA_DIR', os.path.dirname(__file__))
static_dir = os.path.join(static_dir, 'static')
settings = {
'static_path': static_dir,
'template_path': template_dir
}
application = Application([
(r'/image/([^/]*)', ImageHandler, dict(directory=cache_dir)),
(r'/users/?', MainHandler, dict(db=db)),
(r'/?', HomeHandler)
],
**settings)
print('Listening on {0}:{1}'.format(options.host, options.port))
application.listen(options.port, options.host)
tornado.ioloop.IOLoop.instance().start()
示例13: import_api_data2
def import_api_data2():
authenticate("localhost:7474", "neo4j", "1111")
graph = Graph()
#graph.delete_all()
# Uncomment on the first run!
#graph.schema.create_uniqueness_constraint("Borjnuk", "id")
#graph.schema.create_uniqueness_constraint("Obtaj", "id")
#graph.schema.create_uniqueness_constraint("Property", "id")
obtajenna = get_objects_art('obtaj')
for api_obtaj in obtajenna:
node_obtaj= graph.merge_one("Obtaj", "id", api_obtaj["id"])
node_obtaj["reason_doc"] = api_obtaj["reason_doc"]
node_obtaj["cost_size"] = api_obtaj["cost_size"]
for api_author in api_obtaj["borjnuku"]:
node_borjnuk = graph.merge_one("Borjnuk", "id", api_author["id"])
node_borjnuk["name"] = api_author["name"]
node_borjnuk["tel_number"] = api_author["tel_number"]
node_borjnuk.push()
graph.create_unique(Relationship(node_borjnuk, "obtajuetsa", node_obtaj))
for api_property in api_obtaj["properties"]:
node_property = graph.merge_one("Property", "id", api_property["id"])
node_property["name"] = api_property["name_property"]
node_property["ser_number"] = api_property["ser_number"]
node_property.push()
graph.create_unique(Relationship(node_property, "zakladena", node_obtaj))
node_obtaj.push()
示例14: getTestedNeo4jDB
def getTestedNeo4jDB(graphDBurl, graphDbCredentials):
'''Gets a Neo4j url and returns a GraphDatabaseService to the database
after having performed some trivial tests'''
try:
if graphDbCredentials:
authenticate(*graphDbCredentials)
graphDb = Graph(graphDBurl)
#just fetch a Node to check we are connected
#even in DRY RUN we should check Neo4j connectivity
#but not in OFFLINE MODE
if not OFFLINE_MODE:
_ = iter(graphDb.match(limit=1)).next()
except StopIteration:
pass
except SocketError as ex:
raise DbNotFoundException(ex, "Could not connect to Graph DB %s."
% graphDBurl)
if not DRY_RUN and not OFFLINE_MODE:
try:
test_node = Node("TEST", data="whatever")
graphDb.create(test_node)
graphDb.delete(test_node)
except Exception as ex:
raise DBInsufficientPrivileges(\
"Failed on trivial operations in DB %s." % graphDBurl)
return graphDb
示例15: filter_by_path
def filter_by_path(recommendations, user_interests):
# print len(recommendations),len(user_interests)
authenticate("localhost:7474", "neo4j", "password")
res = []
g = Graph()
min_len = -1
MAX_PATH = 3
for i in xrange(len(recommendations)):
for j in xrange(len(user_interests)):
query = "MATCH (from:Product { pid:'" + recommendations[i] + "' }), (to:Product { pid: '" + user_interests[j] + "'}) , path = shortestPath(from-[:TO*]->to ) RETURN path"
results = g.cypher.execute(query)
path_len = len(str(results).split(":TO")) - 1
# print "PATH LEN",path_len
if path_len == 0:
continue
if path_len < MAX_PATH:
min_len = path_len
break
# if min_len == -1 or path_len < min_len:
# min_len = path_len
# print "MIN LEN",min_len
if min_len < MAX_PATH and min_len != -1:
res.append(recommendations[i])
min_len = -1
return res