• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python v1.basic_auth函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中neo4j.v1.basic_auth函数的典型用法代码示例。如果您正苦于以下问题:Python basic_auth函数的具体用法?Python basic_auth怎么用?Python basic_auth使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了basic_auth函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:TwoBitAlchemist,项目名称:NeoAlchemy,代码行数:30,代码来源:graph.py


示例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()
开发者ID:DanielMcFall,项目名称:pubmed-retraction-analysis,代码行数:33,代码来源:load.py


示例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)
开发者ID:pegerto,项目名称:t2n4j,代码行数:32,代码来源:insert.py


示例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()
开发者ID:pitcons,项目名称:bme-parser,代码行数:25,代码来源:export_to_neo4j.py


示例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)
开发者ID:xiyangliu,项目名称:pydemo,代码行数:30,代码来源:__main__.py


示例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
开发者ID:RenanPalmeira,项目名称:pyneo4j,代码行数:29,代码来源:graph.py


示例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))
开发者ID:IPStreet,项目名称:Blogs,代码行数:10,代码来源:neo4j_writer.py


示例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)
开发者ID:lambdafu,项目名称:minos,代码行数:11,代码来源:minos.py


示例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
开发者ID:OC-NTNU,项目名称:MVL,代码行数:11,代码来源:mvl.py


示例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()
开发者ID:popart,项目名称:wikipath,代码行数:12,代码来源:neo4jconn.py


示例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()
开发者ID:rlinkul,项目名称:cycli,代码行数:12,代码来源:driver.py


示例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()
开发者ID:duffj,项目名称:neo4j-batch-executor,代码行数:13,代码来源:test_connection.py


示例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.")
开发者ID:L4in,项目名称:AMX_HIVE,代码行数:14,代码来源:neo4j_comm.py


示例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
开发者ID:inquisite,项目名称:Inquisite-Core,代码行数:47,代码来源:__init__.py


示例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
开发者ID:pvanheus,项目名称:neomodel,代码行数:17,代码来源:util.py


示例16: __init__

    def __init__(self, authfile, session_name):
        self._authfile = authfile
        self._session_name = session_name
        self._num_variables = 0
        self._num_landmarks = 50
        self._pose_to_odometry_or_prior = {}
        self._pose_to_measurements = {}
        self._landmark_to_prior = {}
        self._pose_ids = []
        self._max_factor_id = 0

        # initialize Neo4j session
        self.username, self.password, self.DB_address = open(self._authfile).read().splitlines()
        print self.username, self.password, self.DB_address
        self.driver = GraphDatabase.driver(self.DB_address, auth=basic_auth(self.username, self.password))
        self.session = self.driver.session()
        self.session.run("MATCH (n:" + self._session_name + ") DETACH DELETE n")
开发者ID:dehann,项目名称:Caesar.jl,代码行数:17,代码来源:neo4j_interact_segments.py


示例17: __init__

    def __init__(self, settings_file_name = None, working_directory = None):
        super().__init__(settings_file_name, working_directory = working_directory)

        # Read secret data file
        secret_data_file_name = self.get_setting("secret_data_file_name")
        with open(os.path.join(self.working_directory, os.path.normpath(secret_data_file_name)), "r") as file_:
            fileData = file_.read()
        secret_data = json.loads(fileData)

        # Initialize the graph database
        self._db = GraphDatabase.driver("bolt://localhost", auth=basic_auth(secret_data["neo4j_user_name"], secret_data["neo4j_password"]))
        self.orion_ns = "http://www.orion-research.se/ontology#"
        
        # Initialize proxies
        self.authentication_proxy = self.create_proxy(self.get_setting("authentication_service"))
        
        self.ontology = None
开发者ID:orion-research,项目名称:coach,代码行数:17,代码来源:KnowledgeRepositoryService.py


示例18: get_session

def get_session(warehouse_home, server_name, password=None,
                encrypted=DEFAULT_ENCRYPTED,
                silence_loggers=DEFAULT_SILENCE_LOGGERS):
    if silence_loggers:
        logging.getLogger('neo4j.bolt').setLevel(logging.WARNING)

    server = neokit.Warehouse(warehouse_home).get(server_name)
    address = server.config('dbms.connector.bolt.address', 'localhost:7687')
    server_url = 'bolt://' + address

    if password:
        driver = GraphDatabase.driver(server_url, encrypted=encrypted,
                                      auth=basic_auth(DEFAULT_USER, password))
    else:
        driver = GraphDatabase.driver(server_url, encrypted=encrypted)

    session = driver.session()
    return session
开发者ID:OC-NTNU,项目名称:baleen-python,代码行数:18,代码来源:n4j.py


示例19: handle

    def handle(self, *args, **options):
        driver = GraphDatabase.driver(settings.NEO4J_BOLT_URL, auth=basic_auth(
            settings.NEO4J_USER, settings.NEO4J_PASSWORD)
        )
        session = driver.session()

        # TODO: Figure out a way to not delete the whole graph db every time
        # session.run("MATCH (n) DETACH DELETE n")
        # FIXED by using MERGE/SET statements

        user_list = [
            user[0] for user in User.objects.all().values_list('username')
        ]

        # user_list = [
        #     'aprilchomp', 'jsatt', 'mrmakeit', 'jgmize', 'groovecoder'
        # ]

        repo_types = {
            'repositories': 'OWNER',
            'starredRepositories': 'STARRED',
            'contributedRepositories': "CONTRIBUTED"
        }
        for username in user_list:
            if username == u'admin':
                continue

            try:
                gh_user = ghUser.get(login=username)['user']
                neo4j_merge_user(gh_user, session)
                for repo_type in repo_types.keys():
                    repos = RepoList(type=repo_type, login=username)
                    for repo in repos:
                        repo_values = repo['node']
                        neo4j_merge_repo(repo_values, session)
                        neo4j_match_repo_relationship(
                            gh_user['id'], repo_values['id'],
                            repo_types[repo_type], session
                        )
            except Exception as e:
                logger.error("load_user_github_graph, error: %s" % e)

        session.close()
开发者ID:codesy,项目名称:codesy,代码行数:43,代码来源:load_user_github_graph.py


示例20: _get_db_driver

 def _get_db_driver(uri, username=None, password=None, encrypted=True, max_pool_size=50, trust=TRUST_DEFAULT):
     """
     :param uri: Bolt uri
     :type uri: str
     :param username: Neo4j username
     :type username: str
     :param password: Neo4j password
     :type password: str
     :param encrypted: Use TLS
     :type encrypted: Boolean
     :param max_pool_size: Maximum number of idle sessions
     :type max_pool_size: Integer
     :param trust: Trust cert on first use (0) or do not accept unknown cert (1)
     :type trust: Integer
     :return: Neo4j driver
     :rtype: neo4j.v1.session.Driver
     """
     return GraphDatabase.driver(uri, auth=basic_auth(username, password), encrypted=encrypted,
                                 max_pool_size=max_pool_size, trust=trust)
开发者ID:johanlundberg,项目名称:neo4j-django-tutorial,代码行数:19,代码来源:contextmanager.py



注:本文中的neo4j.v1.basic_auth函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python v1.GraphDatabase类代码示例发布时间:2022-05-27
下一篇:
Python neo4j.GraphDatabase类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap