• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Python Client

This section provides a step-by-step guide for integrating NCache into your Python applications, covering everything from environment setup to API usage.

Prerequisites

Before proceeding, ensure your environment meets the following requirements:

  • Existing Cache: A running cache (e.g., demoCache) must already be created on an NCache server.
  • Python: Version 3.7 or later. For all supported Python versions, refer to Supported Python Versions.
  • NCache Installation: You must have NCache Enterprise installed on your cache servers. For the client machine, you only need the client libraries.
  • Cache Connectivity: Ensure network access to the cache servers (IP address and port, typically 9800).
  • Data being cached is serializable.
  • Exception handling is in place as described in Handling Failures.

Install Client (Optional)

If your application runs on a machine that does not have a full NCache setup, you can install the NCache Client separately.

NCache provides a Windows Installer (.msi) with which you can install NCache through command line silent mode.

  • Search for Command Prompt on the Windows Start menu. Right-click on the search result Command Prompt, and select Run as Administrator.

  • You can install either Cache Server, Developer/QA, or Remote Client. For instance, for Remote Client mode, set the InstallMode=3 in the following command:

msiexec.exe /I "C:\NCacheSetupPath\ncache.ent.net.x64.msi" INSTALLMODE=3 /qn

Setup Python Client

The NCache Python client is available as a standard package on PyPI. You can install it using pip:

pip install ncache-client

To begin using NCache in your code, import the necessary modules:

from ncache.client.CacheManager import CacheManager
from ncache.client.CacheItem import CacheItem

Code Samples

The following samples demonstrate how to perform core caching operations using the NCache Python API.

Data Caching

Once your environment is set up, you can begin performing caching operations. The following sample demonstrates how to connect to a running cache and add an object.

...
from ncache.client.CacheManager import CacheManager
from ncache.client.CacheItem import CacheItem

# Connect to the cache
cache = CacheManager.get_cache("demoCache")

# Create your data object
product = Product(1005, "Laptop", 1500, "Electronics")

# Wrap the object in a CacheItem
cache_item = CacheItem(product)

# Add to Cache
cache.add("1009", cache_item)
print("Item 1009 successfully added to demoCache.")

cache.close()

# Product class used for caching
class Product:
    def __init__(self, product_id, name, price, category):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.category = category
...

For details on basic cache functionality, refer to the Basic Operations documentation.

Tags

Tags allow you to categorize your data with meaningful keywords, making it easier to retrieve or manage related items in groups. The following code associates searchable keywords (Tags) to a CacheItem as metadata before storing it in the cluster. It then uses the get_search_service() to perform a grouped lookup, retrieving multiple related objects at once without needing their individual keys.

...
from ncache.runtime.caching.Tag import Tag

# Create an item with multiple labels
p = Product(1002, "Phone", 800, "Electronics")
item = CacheItem(p)

# Assign tags
item.set_tags([Tag("Electronics"), Tag("Mobile")])
cache.insert("1002", item)

# Retrieve all objects sharing a specific tag
# Returns a dictionary with key-value pairs
results = cache.get_search_service().get_by_tag(Tag("Mobile"))
print(f"Items found with tag 'Mobile': {len(results)}")
...

For more information on using tags, please see Tags documentation.

SQL

NCache provides an Object-Relational querying mechanism that lets you retrieve cached data based on specified criteria. This allows you to search for objects matching specific attributes (like price and category) rather than just keys.

...
from ncache.client.QueryCommand import QueryCommand

# IMPORTANT: Ensure 'price' and 'category' are indexed in the Management Center
# Use $VALUE$ to return the entire object; __main__.Product specifies the class path
query = "SELECT $VALUE$ FROM __main__.Product WHERE price > ? AND category = ?"
sql_command = QueryCommand(query)

# Use set_parameters to pass values safely
sql_command.set_parameters({"price": 500, "category": "Electronics"})

# Execute the search
reader = cache.get_search_service().execute_reader(sql_command)

print("Search results for Electronics > $500:")
while reader.read():
    # get_value returns the dictionary representation of the Product object
    found_data = reader.get_value(Product, 1)

    # Reconstruct the object from the result
    found = Product(found_data['product_id'], found_data['name'],
                    found_data['price'], found_data['category'])

    print(f" - Found: {found.name} (${found.price})")
...

To learn more about SQL Queries, please see SQL Query documentation.

Events

NCache provides an event-driven model that allows client applications to react to changes within the cache. This sample demonstrates Item-Level Events, which allow you to monitor specific keys for updates or removals. The following sample registers an item-level event listener that triggers a callback when the item is updated.

...
from ncache.runtime.events.CacheDataModificationListener import CacheDataModificationListener
from ncache.runtime.events.EventType import EventType
from ncache.runtime.events.EventDataFilter import EventDataFilter

# Define the Callback Implementation
class CacheDataModificationListenerImpl(CacheDataModificationListener):
    def on_cache_data_modified(self, key, args):
        if args.get_event_type() == EventType.ITEM_UPDATED:
            print(f"Item with key '{key}' updated in cache '{args.get_cache_name()}'.")
            if args.get_item() is not None:
                p_data = args.get_item().get_value(Product)
                print(f" >> Updated product price: {p_data['price']}")

# Add an item first, because the key must already exist
product = Product(1005, "Laptop", 1500, "Electronics")
key = "Product:1005"
cache.add(key, CacheItem(product))

# Register the Listener
data_notification_listener = CacheDataModificationListenerImpl()

# Register item-level notifications for update operation
cache.get_messaging_service().add_cache_notification_listener(
    key,
    data_notification_listener,
    [EventType.ITEM_UPDATED],
    EventDataFilter.DATA_WITH_METADATA
)

print("Item-level event notifications registered successfully.")

# Update the item to trigger the Item Updated event
product.price = 1750
cache.insert(key, CacheItem(product))
...

To learn more about Events, please see Event Notifications in Cache documentation.

Important

After running the application or performing cache operations, NCache generates log files that can be used for monitoring and troubleshooting. By default, the log files are generated at the following location:%NCHOME%\log-files. Log file locations may vary if a custom installation directory was selected during NCache setup.

Note

For more details on using NCache, please refer to the Developer's Guide.

See Also

NCache Installation
NCache Developer's Guide
NCache Command Line Interface

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top