# Connecting

Use the Aerospike Python client API to connect to the Aerospike database.

## Import the module

To import the Aerospike Python client module into your application:

```python
import aerospike
```

## Configure a client

A client configuration may specify various options, including:

-   `hosts`: An array of (address, port) tuples that describe the cluster. Only one tuple is required.
-   `policies`: A dict of policies to set defaults along with read and write flexibility.
-   User authentication: key-value pairs of `user` and `password` data.

Explore the full [client configuration](https://aerospike-python-client.readthedocs.io/en/latest/aerospike.html#client-configuration).

The following example creates a sample client configuration:

```python
config = {

    'hosts': [

        ( '127.0.0.1', 3000 )

    ],

    'policies': {

        'timeout': 1000 # milliseconds

    }

    # if user authentication is enabled

    'user': user,

    'password': password

}
```

## Create a client

To create a new client:

```python
client = aerospike.client(config)
```

Calling the `aerospike.client` constructor establishes the connection.

A failed connection results in an exception. On success, your application can execute database operations.

It’s not necessary to call `client.connect()` unless `client.close()` has run previously. `connect()` is a no-op function unless an existing connection has already closed.

## TLS secured connection

TLS connections require certificate configuration on both client and server. The TLS connection port is usually set to 4333 instead of the typically unsecured port 3000. See [TLS configuration](https://aerospike.com/docs/database/manage/network/tls/) for more information about setting up TLS on your Aerospike Database server.

In the following example, set the credential options `user` and `password` to the correct values for your database configuration.

```python
import aerospike

import sys

tls_name = tls_ip = "tls-name"

tls_port = 4333

# If tls-name is specified,

# it must match the tls-name in the node's server configuration file

# and match the server's CA certificate.

tls_host_tuple = (tls_ip, tls_port, tls_name)

hosts = [tls_host_tuple]

# Example configuration which will use TLS with the specified cafile

tls_config = {

    "cafile": "/path/to/cacert.pem",

    "enable": True

}

try:

    client = aerospike.client({

        "hosts": hosts,

        "user": "user",

        "password": "password",

        "tls": tls_config

    })

except Exception as e:

    print(e)

    print("Failed to connect")

    sys.exit()
```

### References

Read the following APIs for more information:

-   [aerospike.client()](https://aerospike-python-client.readthedocs.io/en/latest/aerospike.html#aerospike.client)
-   [aerospike.Client.connect()](https://aerospike-python-client.readthedocs.io/en/latest/client.html#aerospike.Client)