Skip to main content

Managing Projects

Managing Projects

Projects serve as fundamental organizational units, encapsulating related work, resources, and metadata within the system. They provide a logical grouping for various operations and data, enabling efficient management and tracking of distinct initiatives.

Retrieving Individual Projects

To fetch a specific project, use the Project.get() class method. This method allows you to retrieve a project by its unique name.

The get() method is designed to be flexible, supporting both synchronous and asynchronous execution.

Parameters:

  • name (str): The unique name of the project to retrieve.

Example: Synchronous Retrieval

from your_package_name import Project # Assuming Project is imported from 'your_package_name'

# Ensure the client is initialized before making API calls
# (e.g., by calling ensure_client() or similar setup)

try:
project = Project.get(name="my-first-project")
print(f"Project ID: {project.id}")
print(f"Project Name: {project.name}")
print(f"Project State: {project.state}")
except Exception as e:
print(f"Error retrieving project: {e}")

Example: Asynchronous Retrieval

import asyncio
from your_package_name import Project

async def get_project_async():
try:
project = await Project.get(name="my-async-project")
print(f"Async Project ID: {project.id}")
print(f"Async Project Name: {project.name}")
except Exception as e:
print(f"Error retrieving project asynchronously: {e}")

# asyncio.run(get_project_async())

Listing Multiple Projects

The Project.listall() class method provides a way to retrieve a collection of projects. This method returns an iterator, allowing you to efficiently process projects without loading all of them into memory at once. It supports filtering and sorting to refine the results.

The listall() method also supports both synchronous and asynchronous iteration.

Parameters:

  • filters (str, optional): A string representing filter criteria. Filters are applied as key-value pairs, for example: "state=ACTIVE". Multiple filters can be combined using logical operators (specific syntax depends on the backend, but typically key=value AND key2=value2).
  • sort_by (tuple, optional): A tuple specifying the sorting criteria, in the format (field_name, order). order can be "asc" for ascending or "desc" for descending. Defaults to ("created_at", "asc").

Example: Synchronous Listing

from your_package_name import Project

# List all projects
print("All Projects:")
for project in Project.listall():
print(f" - {project.name} (ID: {project.id}, State: {project.state})")

# List active projects, sorted by name descending
print("\nActive Projects (sorted by name descending):")
for project in Project.listall(filters="state=ACTIVE", sort_by=("name", "desc")):
print(f" - {project.name} (ID: {project.id}, State: {project.state})")

# List projects with a specific label
print("\nProjects with label 'environment:production':")
for project in Project.listall(filters="labels.environment=production"):
print(f" - {project.name} (Labels: {project.labels})")

Example: Asynchronous Listing

import asyncio
from your_package_name import Project

async def list_projects_async():
print("All Projects (Async):")
async for project in Project.listall():
print(f" - {project.name} (ID: {project.id}, State: {project.state})")

print("\nProjects created after a specific date (Async):")
# Assuming 'created_at' can be filtered by a timestamp or date string
# The exact filter syntax for dates depends on the backend implementation.
async for project in Project.listall(filters="created_at > '2023-01-01T00:00:00Z'", sort_by=("created_at", "asc")):
print(f" - {project.name} (Created: {project.created_at})")

# asyncio.run(list_projects_async())

Project Attributes

Each Project object exposes several key attributes that provide details about the project:

  • id (str): A unique identifier for the project.
  • name (str): A human-readable name for the project. This is often used for retrieval and display.
  • description (str): An optional, longer text describing the purpose or scope of the project.
  • state (str): The current operational state of the project (e.g., ACTIVE, ARCHIVED, DELETED).
  • labels (dict): A dictionary of key-value pairs used for arbitrary categorization and metadata. Labels are useful for filtering and organizing projects.

These attributes can be accessed directly from a Project object:

from your_package_name import Project

project = Project.get(name="example-project")
print(f"Project Name: {project.name}")
print(f"Project ID: {project.id}")
print(f"Description: {project.description}")
print(f"Current State: {project.state}")
if project.labels:
print(f"Labels: {project.labels}")

Integration and Best Practices

  • Client Initialization: All interactions with projects implicitly rely on an initialized client. Ensure your application sets up the necessary client configuration before attempting to retrieve or list projects.
  • Asynchronous vs. Synchronous: The Project class methods are decorated with @syncify, allowing them to be called either directly (synchronously) or with await (asynchronously). For applications requiring high concurrency or non-blocking I/O, prefer the asynchronous approach. For simpler scripts or blocking contexts, synchronous calls are convenient.
  • Efficient Listing: The listall() method handles pagination internally, fetching projects in batches. This means you can iterate over potentially thousands of projects without worrying about memory exhaustion or manual pagination logic.
  • Filtering Strategy: When listing projects, leverage the filters parameter to narrow down results at the server level. This reduces network traffic and processing overhead compared to fetching all projects and filtering them client-side. Understand the supported filter syntax for optimal performance.
  • Error Handling: Always wrap project retrieval and listing calls in try...except blocks to gracefully handle potential API errors, network issues, or cases where a project might not be found.