---
title: "Python Cookbook"
description: "Explore Python Cookbook to master Gitana's Python driver with comprehensive guides, code samples, and installation instructions. (Gitana 4.0)"
product: "Gitana"
version: "4.0"
url: "/documentation/gitana/4.0/developers/cookbooks/python"
---

# Python Cookbook

## Getting Started

To get started with the Python driver, visit [Gitana Python Driver Page](https://gitana.io/documentation/gitana/4.0/developers/drivers/python.html "Gitana Python Driver Page") or the [Github Page](https://github.com/gitana/cloudcms-python-driver "Github Page"). It is written with Python 3 and can be used in any compatible project.

You can install the driver via the command line:

```
pip install cloudcms

or

pip3 install cloudcms
```

Or add something like this to your `requirements.txt`:

```
cloudcms==1.1.0
```

## Connecting to Gitana

You can connect to Gitana by providing a config file or the oauth variables directly.

### Using a Gitana JSON file

You can use a `gitana.json` file included in your build. It should look something like:

```
{
    "clientKey": "{your client key}",
    "clientSecret": "{your client secret}",
    "username": "{your username or auth grant key}",
    "password": "{your password or auth grant secret}",
    "baseURL": "{the url to the Cloud CMS API endpoint}"
}
```

You will need to specify the path into upon connecting:

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')
```

### Specify Values Directly

Here is how you specify the connection values directly:

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(baseURL='https://api.cloudcms.com',
                        clientKey='clientKey'
                        clientSecret='clientSecret'
                        username='username',
                        password='password')
```

## Code Samples

Here are some code samples to help you get started. In these scenarios, we assume you're using the most simple connection method (providing the path to `gitana.json`).

In Gitana, you can have as many repositories as you'd like. And each repository can have multiple branches (similar to Git). The first thing you should do is connect and get the branch that you want to work on.

For the purpose of most of these examples, we'll assume the repository ID is `1234567890abcdef1234` and the branch is `master`.

## Get your Repository

Use the `read_repository` method to fetch a specific repository. The user you've logged in as must have `READ` permissions to the repository. If they do not have read rights, a null response is expected.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')
```

## Get the Master Branch

Use the `read_branch` method to fetch a specific branch. The user you've logged in as must have `READ` permissions to the branch. If they do not have read rights, a null response is expected.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')
```

## Node Creation

### Create a Node

```
{
    "title": "Custom Article",
    "_qname": "custom:article",
    "type": "object",
    "properties": {
        "title": {
            "type": "string"
        },
        "body": {
            "type": "string"
        },
        "categories": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "rating": {
            "type": "number"
        }
    }
}
```

Create a content instance of this type like this:

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

obj = {
    '_type': 'custom:article',
    'title': 'Article #1',
    'body': 'A still more glorious dawn awaits',
    'categories': [
        'category1',
        'category2',
        'category3'
    ],
    'rating': 5
}

node = branch.create_node(obj)
```

### Create a Folder

In Gitana, folders are just nodes with the `f:container` feature on them. It must be associated to the root node to be considered part of file folder tree.

```python
from cloudcms import CloudCMS
from cloudcms.support import QName
from cloudcms.association import Directionality

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

obj = {
    'title': 'My Folder',
}

root = branch.root_node()

folder = branch.create_node(obj)
folder.add_feature('f:container', {})

root.associate(node, QName.create(qname='a:child'), directionality=Directionality.DIRECTED)
```

An easier way to do this is to use the following special properties when the node is created:

- `_parentFolderPath` - the path to the parent folder where the created node should be linked. The folder must exist. If it does not exist, the operation will fail.
- `_fileName` - the `f:filename` to be assigned to the node once it is created.

Alternatively, you can use:

- `_filePath` - an absolute path where the file should be created. This allows you to specify the parent folder path and the file name at the same time.

You can also adjust the association type (between the discovered parent folder and your newly created item).

- `_associationTypeString` - the QName for the newly created association. The default is `a:child`.

Thus, you could do:

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

obj = {
    'title': 'My Folder',
    '_parentFolderPath': '/',
    '_fileName': 'my_folder'
}

folder = branch.create_node(obj)
```

or:

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

obj = {
    'title': 'My Folder',
    '_filePath': '/my_folder'
}

folder = branch.create_node(obj)
```

## Associations

In Gitana, any two nodes can be connected via an association. You can use an out-of-the-box association type, such as `a:linked` or `a:owned` or you can create your own.

Let's imagine that we have two articles that look like this:

- Article #1

```
{
    "_doc": "1234567890abcdef1111",
    "_type": "custom:article",
    "title": "Article #1",
    "body": "a mote of dust suspended in a sunbeam",
    "categories": ["category1", "category2"],
    "rating": 1
}
```

- Article #2

```
{
    "_doc": "1234567890abcdef2222",
    "_doc": "",
    "_type": "custom:article",
    "title": "Article #2",
    "body": "harvesting star light",
    "categories": ["category2", "category3"],
    "rating": 2
}
```

Let's create an association that points from the first article (`1234567890abcdef1111`) to the second article (`1234567890abcdef2222`), like this:

```python
from cloudcms import CloudCMS
from cloudcms.support import QName

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

article1 = branch.read_node('1234567890abcdef1111')
article2 = branch.read_node('1234567890abcdef2222')

association_type_qname = QName.create(qname='a:linked')
association = article1.associate(article2, association_type_qname)
```

You can also find all associations around `article1`. This will include associations that are `INCOMING`, `OUTGOING` and `MUTUAL`.

```python
associations = article1.associations()
```

Or find only the `INCOMING` associations:

```python
from cloudcms.support import Direction

associations = article1.associations(direction=Direction.INCOMING)
```

Or find only the `OUTGOING` associations of type `a:linked`:

```python
from cloudcms.support import Direction, QName

associations = article1.associations(direction=Direction.OUTGOING, association_type_qname=QName.create('a:linked'))
```

## Query

Let's now look at querying for content. This makes use of MongoDB's query language to express some pretty powerful queries. We recommend further reading on [Query with Gitana](https://gitana.io/documentation/gitana/4.0/engine/query.html "Query with Gitana").

Let's assume that we have the following:

- Article #1

```
{
    "_type": "custom:article",
    "title": "Article #1",
    "body": "a mote of dust suspended in a sunbeam",
    "categories": ["category1", "category2"],
    "rating": 1
}
```

- Article #2

```
{
    "_type": "custom:article",
    "title": "Article #2",
    "body": "harvesting star light",
    "categories": ["category2", "category3"],
    "rating": 2
}
```

- Article 3

```
{
    "_type": "custom:article",
    "title": "Article #3",
    "body": "we are star stuff",
    "categories": ["category3", "category1"],
    "rating": 3
}
```

### Basic Querying

Find all of the nodes that have a `category` with the value `category1`.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

query = {
    '_type': 'custom:article',
    'category': 'category1'
}

results = branch.query_nodes(query)
print('The size was: ' + len(results))

for node in results.values():
    print('Found a result, title: ' + node.data['title'] + ', rating: ' + node.data['rating'])
```

### Pagination

If you have a lot of potential query hits, you'll want to paginate. Here is an example where we return results starting at index 2 and hand back at most 5 results.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

query = {
    '_type': 'custom:article',
    'category': 'category1'
}

pagination = {
    'skip': 2,
    'limit': 5
}

results = branch.query_nodes(query, pagination=pagination)
print('The size was: ' + len(results))

for node in results.values():
    print('Found a result, title: ' + node.data['title'] + ', rating: ' + node.data['rating'])
```

### Sorting

Use the pagination option to sort the results as you see fit. Here we sort descending on `rating`.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

query = {
    '_type': 'custom:article',
    'category': 'category1'
}

pagination = {
    'sort': {
        'rating': -1
    }
}

results = branch.query_nodes(query, pagination)
print('The size was: ' + len(results))

for node in results.values():
    print('Found a result, title: ' + node.data['title'] + ', rating: ' + node.data['rating'])
```

### Query for values in a range

Find all of the articles where the rating is greater than or equal to 2.  
This demonstrates the power of MongoDB's query language.

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

query = {
    '_type': 'custom:article',
    'rating': {
        '$gte': 2
    }
}

results = branch.query_nodes(query)
```

## Search for Nodes

Let's now look at searching for content. This makes use of ElasticSearch's DSL to express some very powerful full text and structured searches. We recommend further reading on [Search within Gitana](/documentation/gitana/4.0/engine/search.md).

We also suggest reading up on [Query Strings](/documentation/gitana/4.0/engine/query.md) to understand how you can write searches textually (in addition to structuring them as JSON objects):

Let's assume that we have the following:

- Article #1

```
{
    "_type": "custom:article",
    "title": "Article #1",
    "body": "a mote of dust suspended in a sunbeam",
    "categories": ["category1", "category2"],
    "rating": 1
}
```

- Article #2

```
{
    "_type": "custom:article",
    "title": "Article #2",
    "body": "harvesting star light",
    "categories": ["category2", "category3"],
    "rating": 2
}
```

- Article 3

```
{
    "_type": "custom:article",
    "title": "Article #3",
    "body": "we are star stuff",
    "categories": ["category3", "category1"],
    "rating": 3
}
```

### Full Text Search

Find all of the nodes with the word `star`. Simple enough!

```python
from cloudcms import CloudCMS

client = CloudCMS()
platform = client.connect(filename='gitana.json')

repository = platform.read_repository('1234567890abcdef1234')
if repository is None:
    raise RuntimeError('Unable to read repository: 1234567890abcdef1234')

branch = repository.read_branch('master')
if branch is None:
    raise RuntimeError('Unable to read master branch')

results = branch.search_nodes('star')
```

## GraphQL

You can make queries for specific fields or content in related items by using [GraphQL](https://gitana.io/documentation/gitana/4.0/engine/graphql.html "GraphQL"). Here we do a simple query for just the title and body of all instances of our article type:

```python
query = '''query {
            custom_articles {
                title
                body
            }
        }'''
results = branch.graphql_query(query)
```
