本文整理汇总了Python中neo4j.v1.basic_auth函数的典型用法代码示例。如果您正苦于以下问题:Python basic_auth函数的具体用法?Python basic_auth怎么用?Python basic_auth使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了basic_auth函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
def connect(self, url=None, user=None, password=None, **kw):
"""
Parse a Neo4J URL and attempt to connect using Bolt
Note: If the user and password arguments are provided, they
will only be used in case no auth information is provided as
part of the connection URL.
"""
if url is None:
url = 'bolt://localhost'
if user is None:
user = 'neo4j'
if password is None:
password = 'neo4j'
try:
protocol, url = url.split('://')
if protocol.lower() != 'bolt':
warnings.warn('Switching protocols. Only Bolt is supported.')
except ValueError:
pass
try:
credentials, url = url.split('@')
except ValueError:
kw['auth'] = basic_auth(user, password)
else:
kw['auth'] = basic_auth(*credentials.split(':', 1))
self.driver = GraphDatabase.driver('bolt://%s' % url, **kw)
示例2: main
def main(argv=None):
"""Import all data in JSON file into Neo4j database."""
parser = argparse.ArgumentParser(description="Load articles into Neo4j")
parser.add_argument("file",
help="File to read",
type=str,
nargs="?",
metavar="FILE")
parser.add_argument("--no-execute",
action="store_true")
parse_result = parser.parse_args(argv or sys.argv[1:])
with open_or_default(parse_result.file, sys.stdin) as fileobj:
data = json.load(fileobj)
commands = list(commands_from_data(data))
if parse_result.no_execute:
sys.stdout.write(json.dumps(commands))
elif len(commands):
if all(var in os.environ for
var in ["DATABASE_URL", "DATABASE_PASS"]):
url = os.environ["DATABASE_URL"]
pwd = os.environ["DATABASE_PASS"]
usr = os.environ.get("DATABASE_USER", "")
else:
raise ValueError("Ensure environment variables DATABASE_URL, "
"DATABASE_PASS and DATABASE_USER set.")
driver = GraphDatabase.driver(url, auth=basic_auth(usr, pwd))
session = driver.session()
for command in commands:
session.run(command)
session.close()
示例3: main
def main():
parser = argparse.ArgumentParser(description="""
Insert a Terraform state file into neo4j
""")
parser.add_argument('-d','--db', required=True, help="Neo4j host")
parser.add_argument('-u','--username', required=True, help="Neo4j user")
parser.add_argument('-p','--password', required=True, help="Neo4j password")
parser.add_argument('state_file', help="Terraform state file")
args = parser.parse_args()
print args
with open(args.state_file, 'r') as f:
state = json.load(f)
driver = GraphDatabase.driver("bolt://{}".format(args.db),
auth=basic_auth(args.username, args.password))
session = driver.session()
# Reduce all the modules and resouces to a single array of objects
resources = reduce( lambda a,b: a+b,
map(lambda m: m['resources'].values(),
state['modules']))
# Run actions for resources and capture hooks
hooks = set()
for resource in resources:
hooks.add(insert_item(resource, session))
# Run hooks
for hook in hooks:
if hook:
hook(session)
示例4: export_to_neo4j
def export_to_neo4j():
driver = GraphDatabase.driver("bolt://localhost:7687",
encrypted=False,
auth=basic_auth("neo4j", "asdzxc"))
session = driver.session()
for article in db.Article.objects.all():
if article['links']:
# session.run("CREATE (a:Article {name: {name}})",
# {"name": article['title']})
for link in article['links']:
to_article = db.Article.objects.get(id=link)
print(to_article['title'])
session.run("CREATE (a:Article {name: {name}})",
{"name": article['title']})
#
# result = session.run("MATCH (a:Person) WHERE a.name = {name} "
# "RETURN a.name AS name, a.title AS title",
# {"name": "Arthur"})
# for record in result:
# print("%s %s" % (record["title"], record["name"]))
#
session.close()
示例5: run_graph
def run_graph(neo4j_conf, args):
opts, args = getopt.getopt(args, "rcsa", ["related", "cluster", "similar", "all"])
if len(args) < 1:
raise getopt.GetoptError("Invalid graph arguments")
query = args[0]
stmt = ''
for o, v in opts:
if o in ["-r", "--related"]:
stmt = ('match (q:Query)<-[r:RELATED]-(a:Query) where q.query={query}'
'return a.query, r.norm_weight order by r.norm_weight desc')
elif o in ["-c", "--cluster"]:
stmt = ('match (q:Query)<-[r:CLUSTER_REP]-(a:Query) where q.query={query}'
'return r.rank, a.query, r.query_terms order by r.rank')
elif o in ["-s", "--similar"]:
stmt = ('match (q:Query)-[r:SIMILAR]-(a:Query) where q.query={query}'
'return a.query, r.score order by r.score desc')
elif o in ["-a", "--all"]:
stmt = ('match (q:Query)<-[r]-() where q.query={query}'
'return q.query, type(r) as rel_type, count(r) as rel_count')
if not stmt:
raise getopt.GetoptError("Invalid graph arguments")
graph = GraphDatabase.driver(neo4j_conf.uri, auth=basic_auth(neo4j_conf.username, neo4j_conf.password))
session = graph.session()
rs = session.run(stmt, parameters={'query': query})
for r in rs:
pprint.pprint(r)
示例6: __new__
def __new__(cls, *args, **kwargs):
"""
Return neo4j-driver ou neo4jrestclient object
"""
_auth = None
if kwargs and ('user' or 'password') in list(kwargs.keys()):
user = kwargs['user']
password = kwargs['password']
if 'bolt://' in cls._default_host:
_auth = basic_auth(user, password)
else:
_url = 'http://{0}:{1}@localhost:7474'.format(user, password)
cls.host = _url
if 'bolt://' in cls._default_host:
driver = Neo4j3.driver(cls._default_host)
if _auth:
driver.auth = _auth
cls._graph = Cypher(driver)
return cls._graph
elif cls.host is not None and type(cls.host) is str:
cls._graph = Neo4j2(cls.host)
return cls._graph
else:
cls._graph = Neo4j2(cls._default_host)
return cls._graph
示例7: __init__
def __init__(self):
config = configparser.ConfigParser()
config.read('config.ini')
user_name = config.get('neo4j credentials', 'user_name')
password = config.get('neo4j credentials', 'password')
bolt_host = config.get('neo4j credentials', 'bolt_host')
self.driver = GraphDatabase.driver(bolt_host,
auth=basic_auth(user_name, password))
示例8: server
def server(ctx, host, port, debug):
from . server import app
config = ctx.obj.config
from neo4j.v1 import GraphDatabase, basic_auth
auth = basic_auth(config.neo4j.user, config.neo4j.password)
driver = GraphDatabase.driver(config.neo4j.address, auth=auth)
from attrdict import AttrDict
app.minos = AttrDict({ 'config': config, 'driver': driver })
app.run(host, port, debug)
示例9: init_neo4j_connection
def init_neo4j_connection(app):
server_url = app.config.get('NEO4J_URL', 'bolt://localhost:7687')
encrypted = app.config.get('NEO4J_ENCRYPTED', True)
user = app.config.get('NEO4J_USER', 'neo4j')
password = app.config.get('NEO4J_PASSWORD')
auth = basic_auth(user, password) if password else None
driver = GraphDatabase.driver(server_url,
encrypted=encrypted,
auth=auth)
app.config['NEO4J_DRIVER'] = driver
示例10: __init__
def __init__(self, **kwargs):
#super(Neo4JConn, self).__init__()
config = {
'host': kwargs['db_addr'],
'port': kwargs['db_port'],
'user': kwargs['username'],
'password': kwargs['password']
}
driver = GraphDatabase.driver(
"bolt://%s:%d" % (config['host'], config['port']),
auth=basic_auth(config['user'], config['password']))
self.__session = driver.session()
示例11: __init__
def __init__(self, host, port, username=None, password=None, ssl=False, timeout=None):
port = "7687" if port is None else port
bolt_uri = "bolt://{host}".format(host=host, port=port)
self.http_uri = "http://{host}:{port}/db/data/".format(host=host, port=port)
if username and password:
driver = GraphDatabase.driver(bolt_uri, auth=basic_auth(username, password), encrypted=False)
else:
driver = GraphDatabase.driver(bolt_uri, encrypted=False)
self.session = driver.session()
示例12: neo4j
def neo4j():
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7474", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
session.run("CREATE (a:Person {name:'Arthur', title:'King'})")
result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
for record in result:
print("%s %s" % (record["title"], record["name"]))
session.close()
示例13: __init__
def __init__(self, adress, user, password):
"""
Creates the session to the database
"""
self.driver = GraphDatabase.driver(adress, \
auth=basic_auth(user, password))
try:
self.session = self.driver.session()
except ProtocolError:
print("Cannot connect to neo4j. Aborting.")
exit()
print("Connected to neo4j.")
示例14: create_app
def create_app():
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = config['auth_secret']
app.config['JWT_BLACKLIST_ENABLED'] = False
app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore()
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=15)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
driver = GraphDatabase.driver(config['database_url'], auth=basic_auth(config['database_user'],config['database_pass']))
db_session = driver.session()
# start jwt service
jwt = JWTManager(app)
# Import blueprints
from auth import auth_blueprint
from banner import banner_blueprint
from people import people_blueprint
from organizations import organizations_blueprint
from repos import repositories_blueprint
from schema import schema_blueprint
from data import data_blueprint
from search import search_blueprint
from upload import upload_blueprint
from export import export_blueprint
from list import list_blueprint
from .sockets import sockets as socket_blueprint
# register API modules
app.register_blueprint(banner_blueprint)
app.register_blueprint(auth_blueprint)
app.register_blueprint(people_blueprint)
app.register_blueprint(organizations_blueprint)
app.register_blueprint(repositories_blueprint)
app.register_blueprint(schema_blueprint)
app.register_blueprint(search_blueprint)
app.register_blueprint(data_blueprint)
app.register_blueprint(upload_blueprint)
app.register_blueprint(socket_blueprint)
app.register_blueprint(export_blueprint)
app.register_blueprint(list_blueprint)
x_socketio.init_app(app)
return app, jwt
示例15: set_connection
def set_connection(self, url):
self.url = url
u = urlparse(url)
if u.netloc.find('@') > -1 and u.scheme == 'bolt':
credentials, hostname = u.netloc.rsplit('@', 1)
username, password, = credentials.split(':')
else:
raise ValueError("Expecting url format: bolt://user:[email protected]:7687"
" got {}".format(url))
self.driver = GraphDatabase.driver('bolt://' + hostname,
auth=basic_auth(username, password),
encrypted=config.ENCRYPTED_CONNECTION,
max_pool_size=config.MAX_POOL_SIZE)
self._pid = os.getpid()
self._active_transaction = None