### Getting Started with cqlengine Object Mapper Source: https://python-driver.docs.scylladb.com/stable/object-mapper.html Defines a model, sets up a connection to Cassandra, synchronizes the table, creates rows, and performs basic queries. Ensure you have a Cassandra instance running and accessible at '127.0.0.1'. ```python import uuid from cassandra.cqlengine import columns from cassandra.cqlengine import connection from datetime import datetime from cassandra.cqlengine.management import sync_table from cassandra.cqlengine.models import Model #first, define a model class ExampleModel(Model): example_id = columns.UUID(primary_key=True, default=uuid.uuid4) example_type = columns.Integer(index=True) created_at = columns.DateTime() description = columns.Text(required=False) #next, setup the connection to your cassandra server(s)... # see http://datastax.github.io/python-driver/api/cassandra/cluster.html for options # the list of hosts will be passed to create a Cluster() instance connection.setup(['127.0.0.1'], "cqlengine", protocol_version=3) #...and create your CQL table >>> sync_table(ExampleModel) #now we can create some rows: >>> em1 = ExampleModel.create(example_type=0, description="example1", created_at=datetime.now()) >>> em2 = ExampleModel.create(example_type=0, description="example2", created_at=datetime.now()) >>> em3 = ExampleModel.create(example_type=0, description="example3", created_at=datetime.now()) >>> em4 = ExampleModel.create(example_type=0, description="example4", created_at=datetime.now()) >>> em5 = ExampleModel.create(example_type=1, description="example5", created_at=datetime.now()) >>> em6 = ExampleModel.create(example_type=1, description="example6", created_at=datetime.now()) >>> em7 = ExampleModel.create(example_type=1, description="example7", created_at=datetime.now()) >>> em8 = ExampleModel.create(example_type=1, description="example8", created_at=datetime.now()) #and now we can run some queries against our table >>> ExampleModel.objects.count() 8 >>> q = ExampleModel.objects(example_type=1) >>> q.count() 4 >>> for instance in q: >>> print(instance.description) example5 example6 example7 example8 #here we are applying additional filtering to an existing query #query objects are immutable, so calling filter returns a new #query object >>> q2 = q.filter(example_id=em5.example_id) >>> q2.count() 1 >>> for instance in q2: >>> print(instance.description) example5 ``` -------------------------------- ### Manual Installation from Source Source: https://python-driver.docs.scylladb.com/stable/installation.html Install the driver directly from a source checkout or tarball after ensuring all Python dependencies are met. ```bash python setup.py install ``` -------------------------------- ### Install Snappy Compression Support Source: https://python-driver.docs.scylladb.com/stable/installation.html Install the python-snappy package to enable Snappy compression for communication between the driver and Cassandra. ```bash pip install python-snappy ``` -------------------------------- ### Install Libev on Windows using vcpkg Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the libev library on Windows using the vcpkg package manager. ```bash > $ vcpkg install libev ``` -------------------------------- ### Install Dependencies and then Driver with Install-Option Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs driver dependencies first, then installs the driver using pip's install-option to disable Cython, avoiding issues with dependency flags. ```bash sudo pip install futures sudo pip install --install-option="--no-cython" ``` -------------------------------- ### Execute Async Query and Get Result Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Demonstrates how to execute a query asynchronously and retrieve its results. This example shows how to handle potential exceptions during query execution and processing. ```python >>> future = session.execute_async("SELECT * FROM mycf") >>> # do other stuff... >>> try: ... rows = future.result() ... for row in rows: ... ... # process results ... except Exception: ... log.exception("Operation failed:") ``` -------------------------------- ### cassandra.cqlengine.connection.setup(_hosts_, _default_keyspace_, _consistency_=None, _lazy_connect_=False, _retry_connect_=False, _**kwargs_) Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/connection.html Setup the driver connection used by the mapper. ```APIDOC ## setup(_hosts_, _default_keyspace_, _consistency_=None, _lazy_connect_=False, _retry_connect_=False, _**kwargs_) ### Description Sets up the driver connection used by the mapper. ### Method N/A (Function call) ### Endpoint N/A ### Parameters * **hosts** (_list_) - List of hosts, (`contact_points` for `cassandra.cluster.Cluster`). * **default_keyspace** (_str_) - The default keyspace to use. * **consistency** (_int_) - The global default `ConsistencyLevel` - default is the same as `Session.default_consistency_level`. * **lazy_connect** (_bool_) - True if should not connect until first use. * **retry_connect** (_bool_) - True if we should retry to connect even if there was a connection failure initially. * **kwargs** - Pass-through keyword arguments for `cassandra.cluster.Cluster`. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Install Libev on RHEL/CentOS/Fedora Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the libev library and development headers on RHEL, CentOS, or Fedora systems. ```bash $ sudo yum install libev libev-devel ``` -------------------------------- ### Install Libev on Debian/Ubuntu Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the libev library and development headers on Debian or Ubuntu systems. ```bash $ sudo apt-get install libev4 libev-dev ``` -------------------------------- ### Session Execution Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Example usage of connecting to a Cassandra cluster and executing a query using the Session object. ```python session = cluster.connect() ``` -------------------------------- ### Install LZ4 Compression Support Source: https://python-driver.docs.scylladb.com/stable/installation.html Install the lz4 package to enable LZ4 compression for communication between the driver and Cassandra. ```bash pip install lz4 ``` -------------------------------- ### Disable All C Extensions during Manual Installation Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the driver manually while skipping all C extensions. ```bash python setup.py install --no-extensions ``` -------------------------------- ### Cloud Configuration Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Configure cloud-specific settings, including the path to a secure connect bundle. The bundle will be temporarily extracted to load configuration and certificates. ```python cloud = { # path to the secure connect bundle 'secure_connect_bundle': '/path/to/secure-connect-dbname.zip', # optional config options 'use_default_tempdir': True # use the system temp dir for the zip extraction } ``` -------------------------------- ### Install GCC and Python Headers on RedHat/CentOS/Fedora Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs necessary build tools for compiling C extensions on RedHat and related systems. ```bash $ sudo yum install gcc python-devel ``` -------------------------------- ### Install ScyllaDB Python Driver with pip Source: https://python-driver.docs.scylladb.com/stable/installation.html Use pip to install the ScyllaDB Python driver and its dependencies. Consider using `--pre` for beta versions. ```bash pip install scylla-driver ``` ```bash pip install --pre scylla-driver ``` -------------------------------- ### Install Libev on macOS using Homebrew Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the libev library on macOS using the Homebrew package manager. ```bash $ brew install libev ``` -------------------------------- ### Install GCC and Python Headers on Ubuntu/Debian Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs necessary build tools for compiling C extensions on Ubuntu and Debian-based systems. ```bash $ sudo apt-get install gcc python-dev ``` -------------------------------- ### Disable Cython Extensions during Manual Installation Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the driver manually while skipping the Cython-based C extensions. ```bash python setup.py install --no-cython ``` -------------------------------- ### Speed Up Driver Installation with Concurrency Source: https://python-driver.docs.scylladb.com/stable/installation.html Use CASS_DRIVER_BUILD_CONCURRENCY to specify the number of threads for building the driver and C extensions, potentially speeding up installation. ```bash $ # installing from source $ CASS_DRIVER_BUILD_CONCURRENCY=8 python setup.py install ``` ```bash $ # installing from pip $ CASS_DRIVER_BUILD_CONCURRENCY=8 pip install scylla-driver ``` -------------------------------- ### Verify ScyllaDB Python Driver Installation Source: https://python-driver.docs.scylladb.com/stable/installation.html Run this command to check if the ScyllaDB Python driver has been installed successfully and to display its version. ```python python -c 'import cassandra; print(cassandra.__version__)' ``` -------------------------------- ### Disable Libev C Extension during Manual Installation Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the driver manually while skipping only the libev C extension. ```bash python setup.py install --no-libev ``` -------------------------------- ### Disable Murmur3 C Extension during Manual Installation Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the driver manually while skipping only the Murmur3 C extension. ```bash python setup.py install --no-murmur3 ``` -------------------------------- ### PlainTextAuthProvider Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/auth.html Use PlainTextAuthProvider for Cassandra's PasswordAuthenticator. Instantiate it with username and password, then pass it to the Cluster constructor. ```python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider auth_provider = PlainTextAuthProvider( username='cassandra', password='cassandra') cluster = Cluster(auth_provider=auth_provider) ``` -------------------------------- ### Install ScyllaDB Driver from Local Source with Cython Disabled via Pip Source: https://python-driver.docs.scylladb.com/stable/installation.html Installs the ScyllaDB Python driver from a local source directory using pip, with Cython extensions disabled. ```bash CASS_DRIVER_NO_CYTHON=1 sudo -E pip install ~/python-driver ``` -------------------------------- ### AsyncioConnection.initialize_reactor() Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/io/asyncioreactor.html This class method is intended to be called once by `Cluster.connect()`. It serves as a setup point for any resources that will be shared across multiple connections within the asyncio event loop. ```APIDOC ## AsyncioConnection.initialize_reactor() ### Description Called once by Cluster.connect(). This should be used by implementations to set up any resources that will be shared across connections. ### Method classmethod ### Parameters This method does not take any explicit parameters. ``` -------------------------------- ### SimpleStatement Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/query.html Represents a simple, un-prepared CQL query. Use this for queries that do not require parameter binding or prepared statement benefits. ```python from cassandra.query import SimpleStatement # query_string should be a literal CQL statement # Example: SimpleStatement("SELECT * FROM users WHERE name = 'Bob'") ``` -------------------------------- ### SaslAuthProvider Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/auth.html Use SaslAuthProvider for general SASL authentication mechanisms like GSSAPI. Configure it with necessary keyword arguments and pass it to the Cluster constructor. ```python from cassandra.cluster import Cluster from cassandra.auth import SaslAuthProvider sasl_kwargs = {'service': 'something', 'mechanism': 'GSSAPI', 'qops': 'auth'.split(',')} auth_provider = SaslAuthProvider(**sasl_kwargs) cluster = Cluster(auth_provider=auth_provider) ``` -------------------------------- ### Immutable QuerySets Example Source: https://python-driver.docs.scylladb.com/stable/cqlengine/queryset.html Demonstrates that cqlengine QuerySets are immutable. Calling methods that modify a queryset returns a new queryset object instead of altering the original. ```python #this produces 3 different querysets #q does not change after it's initial definition q = Automobiles.objects.filter(year=2012) tesla2012 = q.filter(manufacturer='Tesla') honda2012 = q.filter(manufacturer='Honda') ``` -------------------------------- ### Defining a User Defined Type Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/usertype.html This example shows how to define a UserType by inheriting from `cassandra.cqlengine.usertype.UserType` and assigning field types as class attributes. It also demonstrates how to synchronize the type definition with the database using `management.sync_type`. ```APIDOC ## Defining a User Defined Type This class is used to model User Defined Types. To define a type, declare a class inheriting from this, and assign field types as class attributes: ```python # connect with default keyspace ... from cassandra.cqlengine.columns import Text, Integer from cassandra.cqlengine.usertype import UserType class address(UserType): street = Text() zipcode = Integer() from cassandra.cqlengine import management management.sync_type(address) ``` Please see User Defined Types for a complete example and discussion. ``` -------------------------------- ### Create Keyspaces and Sync Models Across Connections Source: https://python-driver.docs.scylladb.com/stable/cqlengine/connections.html Demonstrates how to create keyspaces and synchronize table schemas across multiple specified connections using cqlengine's management utilities. ```python from cassandra.cqlengine import management keyspaces = ['ks1', 'ks2'] conns = ['cluster1', 'cluster2'] # registers your connections # ... # create all keyspaces on all connections for ks in keyspaces: management.create_simple_keyspace(ks, connections=conns) # define your Automobile model # ... # sync your models management.sync_table(Automobile, keyspaces=keyspaces, connections=conns) ``` -------------------------------- ### Register Default and New Connections Source: https://python-driver.docs.scylladb.com/stable/cqlengine/connections.html Sets up the default connection and registers an additional named connection. Use `connection.setup` for the default and `connection.register_connection` for others. ```python from cassandra.cqlengine import connection connection.setup(['127.0.0.1') connection.register_connection('cluster2', ['127.0.0.2']) ``` -------------------------------- ### Setting Keyspace and Executing a Query Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Demonstrates how to set the keyspace for a session and then execute a simple SELECT query. ```python session.set_keyspace("mykeyspace") session.execute("SELECT * FROM mycf") ``` -------------------------------- ### Use Prepared Statements Source: https://python-driver.docs.scylladb.com/stable/getting-started.html Prepare queries using `session.prepare()` for efficiency. The driver sends only parameter values, reducing network traffic and Scylla CPU load. ```python user_lookup_stmt = session.prepare("SELECT * FROM users WHERE user_id=?") users = [] for user_id in user_ids_to_query: user = session.execute(user_lookup_stmt, [user_id]) users.append(user) ``` -------------------------------- ### create_keyspace_simple Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/management.html Creates a keyspace with SimpleStrategy for replica placement. If the keyspace already exists, it will not be modified. Use with caution. ```APIDOC ## create_keyspace_simple ### Description Creates a keyspace with SimpleStrategy for replica placement. If the keyspace already exists, it will not be modified. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** ### Parameters * **name** (str) - name of keyspace to create * **replication_factor** (int) - keyspace replication factor, used with `SimpleStrategy` * **durable_writes** (bool) - Optional - Write log is bypassed if set to False * **connections** (list) - Optional - List of connection names ``` -------------------------------- ### Fetch all users with cqlengine Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/query.html Demonstrates fetching all records from a model. The `limit(None)` ensures no limit is applied. ```python for user in User.objects().limit(None): print(user) ``` -------------------------------- ### Create Cluster and Connect to Session Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Instantiate a Cluster with contact points and establish a session. Remember to shut down the cluster when done. ```python from cassandra.cluster import Cluster cluster = Cluster(['192.168.1.1', '192.168.1.2']) session = cluster.connect() session.execute("CREATE KEYSPACE ...") ... cluster.shutdown() ``` -------------------------------- ### Generate Client Certificate Configuration Source: https://python-driver.docs.scylladb.com/stable/security.html Prepare a configuration file for generating a client certificate. This is used when the server requires client authentication. ```bash cat > gen_client_cert.conf <>> from cassandra.io.libevreactor import LibevConnection >>> from cassandra.cluster import Cluster >>> cluster = Cluster() >>> cluster.connection_class = LibevConnection >>> session = cluster.connect() ``` -------------------------------- ### Get All Model Instances Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/models.html Returns a queryset representing all stored objects. This is a pass-through to the model objects().all(). ```APIDOC ## all() Returns a queryset representing all stored objects. ### Description Retrieves a QuerySet containing all model instances in the table. ### Method `all()` ``` -------------------------------- ### Integrate CQLengine with Celery Source: https://python-driver.docs.scylladb.com/stable/cqlengine/third-party.html Set up CQLengine connection initialization for Celery workers and beat. This ensures a clean Cassandra connection is established in each worker process. ```python from celery import Celery from celery.signals import worker_process_init, beat_init from cassandra.cqlengine import connection from cassandra.cqlengine.connection import ( cluster as cql_cluster, session as cql_session ) def cassandra_init(**kwargs): """ Initialize a clean Cassandra connection. """ if cql_cluster is not None: cql_cluster.shutdown() if cql_session is not None: cql_session.shutdown() connection.setup() # Initialize worker context for both standard and periodic tasks. worker_process_init.connect(cassandra_init) beat_init.connect(cassandra_init) app = Celery() ``` -------------------------------- ### Disable All Extensions using Environment Variable Source: https://python-driver.docs.scylladb.com/stable/installation.html Sets an environment variable to prevent all C extensions from being used during installation. ```bash CASS_DRIVER_NO_EXTENSIONS=1 ``` -------------------------------- ### Manipulate model instances as dictionaries Source: https://python-driver.docs.scylladb.com/stable/cqlengine/models.html Demonstrates how cqlengine model instances can be treated like dictionaries for accessing, modifying, and iterating over their fields. This includes creating an instance and then accessing its data. ```python class Person(Model): first_name = columns.Text() last_name = columns.Text() kevin = Person.create(first_name="Kevin", last_name="Deldycke") dict(kevin) # returns {'first_name': 'Kevin', 'last_name': 'Deldycke'} kevin['first_name'] # returns 'Kevin' kevin.keys() # returns ['first_name', 'last_name'] kevin.values() # returns ['Kevin', 'Deldycke'] kevin.items() # returns [('first_name', 'Kevin'), ('last_name', 'Deldycke')] kevin['first_name'] = 'KEVIN5000' # changes the models first name ``` -------------------------------- ### Filter Objects with Equal To Operator Source: https://python-driver.docs.scylladb.com/stable/cqlengine/queryset.html The default filtering operator is 'Equal To' (=). This example shows filtering by manufacturer and year. ```python q = Automobile.objects.filter(manufacturer='Tesla') q = q.filter(year=2012) #year == 2012 ``` -------------------------------- ### Define a Model for Querying Source: https://python-driver.docs.scylladb.com/stable/cqlengine/queryset.html Define a basic cqlengine Model. This is a prerequisite for most query operations. ```python class Row(Model): id = columns.Integer(primary_key=True) name = columns.Text() ``` -------------------------------- ### Register Connection as Default Source: https://python-driver.docs.scylladb.com/stable/cqlengine/connections.html Registers a new connection and immediately sets it as the default connection for cqlengine. ```python from cassandra.cqlengine import connection connection.register_connection('cluster2', ['127.0.0.2'] default=True) ``` -------------------------------- ### Get Model Instance Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/models.html Returns a single object based on the passed filter constraints. This is a pass-through to the model objects().get(). ```APIDOC ## get(_* args_, _** kwargs_) Returns a single object based on the passed filter constraints. ### Description Retrieves a single model instance matching the specified filter criteria. ### Method `get(**kwargs)` ``` -------------------------------- ### Connect to a Specific Keyspace Source: https://python-driver.docs.scylladb.com/stable/getting-started.html Initialize a Session connected to a specific keyspace by passing the keyspace name to the connect() method. ```python cluster = Cluster() session = cluster.connect('mykeyspace') ``` -------------------------------- ### Filter Objects by Manufacturer Source: https://python-driver.docs.scylladb.com/stable/cqlengine/queryset.html Use the .filter() method to retrieve a subset of records based on specified criteria. This example filters by manufacturer. ```python q = Automobile.objects.filter(manufacturer='Tesla') ``` -------------------------------- ### Batch Operations Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/models.html Sets the batch object to run instance updates and inserts queries with. See Batch Queries for usage examples. ```APIDOC ## batch(_batch_object_) Sets the batch object to run instance updates and inserts queries with. ### Description Associates the model instance with a batch object for batched operations. ### Method `batch(batch_object)` ``` -------------------------------- ### Prepare and Execute a Statement Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Prepare a query string to create a reusable prepared statement. This is more efficient for queries executed multiple times. The prepared statement can then be executed with bound parameters. ```python >>> session = cluster.connect("mykeyspace") >>> query = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)" >>> prepared = session.prepare(query) >>> session.execute(prepared, (user.id, user.name, user.age)) ``` -------------------------------- ### Get Column Family Name Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/models.html Returns the column family name if it’s been defined otherwise, it creates it from the module and class name. ```APIDOC ## column_family_name(_include_keyspace =True_) Returns the column family name if it’s been defined otherwise, it creates it from the module and class name. ### Description Retrieves the name of the underlying Cassandra table (column family). ### Method `column_family_name(include_keyspace=True)` ``` -------------------------------- ### Disable Cython Extensions using Environment Variable Source: https://python-driver.docs.scylladb.com/stable/installation.html Sets an environment variable to prevent Cython from being used during installation, useful when using pip. ```bash CASS_DRIVER_NO_CYTHON=1 ``` -------------------------------- ### Establish a Session Source: https://python-driver.docs.scylladb.com/stable/getting-started.html Create a Session object from a Cluster instance to establish connections and begin executing queries. ```python cluster = Cluster() session = cluster.connect() ``` -------------------------------- ### Integrate CQLengine with uWSGI Source: https://python-driver.docs.scylladb.com/stable/cqlengine/third-party.html Configure CQLengine connection handling for applications running under uWSGI. This uses the `@postfork` decorator to ensure a new Cassandra session is created for each new request. ```python from cassandra.cqlengine import connection from cassandra.cqlengine.connection import ( cluster as cql_cluster, session as cql_session ) try: from uwsgidecorators import postfork except ImportError: # We're not in a uWSGI context, no need to hook Cassandra session # initialization to the postfork event. pass else: @postfork def cassandra_init(**kwargs): """ Initialize a new Cassandra session in the context. Ensures that a new session is returned for every new request. """ if cql_cluster is not None: cql_cluster.shutdown() if cql_session is not None: cql_session.shutdown() connection.setup() ``` -------------------------------- ### Get Control Connection Host Metadata Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Retrieves metadata for the host used by the control connection. This is useful for understanding the driver's connection to the cluster. ```python get_control_connection_host() ``` -------------------------------- ### create_keyspace_network_topology Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/management.html Creates a keyspace with NetworkTopologyStrategy for replica placement. If the keyspace already exists, it will not be modified. Use with caution. ```APIDOC ## create_keyspace_network_topology ### Description Creates a keyspace with NetworkTopologyStrategy for replica placement. If the keyspace already exists, it will not be modified. **This function should be used with caution, especially in production environments. Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).** ### Parameters * **name** (str) - name of keyspace to create * **dc_replication_map** (dict) - map of dc_names: replication_factor * **durable_writes** (bool) - Optional - Write log is bypassed if set to False * **connections** (list) - Optional - List of connection names ``` -------------------------------- ### Get First Object with first() Source: https://python-driver.docs.scylladb.com/stable/cqlengine/queryset.html Use the .first() method on a filtered QuerySet to retrieve the first matching object. Returns None if no objects match. ```python q = Automobile.objects.filter(manufacturer='Tesla') q = q.filter(year=2012) car = q.first() ``` -------------------------------- ### Two-Way SSL with Twisted and pyOpenSSL Source: https://python-driver.docs.scylladb.com/stable/security.html Configure two-way SSL verification using Twisted and pyOpenSSL. This setup is for asynchronous applications using the Twisted reactor. ```python from OpenSSL import SSL, crypto from cassandra.cluster import Cluster from cassandra.io.twistedreactor import TwistedConnection ssl_context = SSL.Context(SSL.TLSv1_2_METHOD) ssl_context.set_verify(SSL.VERIFY_PEER, callback=lambda _1, _2, _3, _4, ok: ok) ssl_context.use_certificate_file('/path/to/client.crt_signed') ssl_context.use_privatekey_file('/path/to/client.key') ssl_context.load_verify_locations('/path/to/rootca.crt') cluster = Cluster( contact_points=['127.0.0.1'], connection_class=TwistedConnection, ssl_context=ssl_context, ssl_options={'check_hostname': True} ) session = cluster.connect() ``` -------------------------------- ### Prepare Statement and Bind Values Ahead of Time Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Prepare a query and then bind values to create a bound statement. This bound statement can then be executed. This is useful for pre-constructing statements with specific values. ```python >>> prepared = session.prepare(query) >>> bound_stmt = prepared.bind((user.id, user.name, user.age)) >>> session.execute(bound_stmt) ``` -------------------------------- ### Resume Paged Results with Paging State Source: https://python-driver.docs.scylladb.com/stable/query-paging.html You can resume pagination for a new query by using the `ResultSet.paging_state`. This allows for stateless pagination, for example, when used with HTTP requests. ```python from cassandra.query import SimpleStatement query = "SELECT * FROM users" statement = SimpleStatement(query, fetch_size=10) results = session.execute(statement) # save the paging_state somewhere and return current results web_session['paging_state'] = results.paging_state # resume the pagination sometime later... statement = SimpleStatement(query, fetch_size=10) ps = web_session['paging_state'] results = session.execute(statement, paging_state=ps) ``` -------------------------------- ### Get Shard Aware Connection Statistics Source: https://python-driver.docs.scylladb.com/stable/scylla-specific.html Retrieve statistics on shard-aware connections to all hosts using the cluster.shard_aware_stats() method. This helps verify successful connections to all shards. ```python from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect() stats = cluster.shard_aware_stats() if all([v["shards_count"] == v["connected"] for v in stats.values()]): print("successfully connected to all shards of all scylla nodes") ``` -------------------------------- ### Reuse Prepared Statements in a Loop Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cluster.html Demonstrates the efficient reuse of a prepared statement within a loop. By preparing the statement once and binding values for each iteration, performance is significantly improved for bulk operations. ```python >>> prepared = session.prepare(query) >>> for user in users: ... bound = prepared.bind((user.id, user.name, user.age)) ... session.execute(bound) ``` -------------------------------- ### Use New Schema Management Functions Source: https://python-driver.docs.scylladb.com/stable/cqlengine/upgrade-guide.html Replace deprecated schema management functions with their modern, strategy-specific counterparts. Use `create_keyspace_simple` or `create_keyspace_network_topology` instead of `create_keyspace`. ```python from cassandra.cqlengine import management # Deprecated: # management.create_keyspace('my_keyspace') # Recommended: management.create_keyspace_simple('my_keyspace', replication_factor=3) ``` -------------------------------- ### Handle Scylla RateLimitReached Error Source: https://python-driver.docs.scylladb.com/stable/scylla-specific.html ScyllaDB 5.1+ may return RateLimitReached errors for per-partition rate limiting. This example demonstrates how to catch and handle this specific exception. ```python from cassandra import RateLimitReached from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect() session.execute(""" CREATE KEYSPACE IF NOT EXISTS keyspace1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} ") session.execute("USE keyspace1") session.execute(""" CREATE TABLE tbl (pk int PRIMARY KEY, v int) WITH per_partition_rate_limit = {'max_writes_per_second': 1} ") prepared = session.prepare(""" INSERT INTO tbl (pk, v) VALUES (?, ?) ") try: for _ in range(1000): self.session.execute(prepared.bind((123, 456))) except RateLimitReached: raise ``` -------------------------------- ### Configure Driver for Server Client Authentication Source: https://python-driver.docs.scylladb.com/stable/security.html Load the client's certificate and private key into the SSL context when the server requires client authentication. The driver will present these credentials to the server. ```python from cassandra.cluster import Cluster, Session from ssl import SSLContext, PROTOCOL_TLS ssl_context = SSLContext(PROTOCOL_TLS) ssl_context.load_cert_chain( certfile='/path/to/client.crt_signed', keyfile='/path/to/client.key') cluster = Cluster(['127.0.0.1'], ssl_context=ssl_context) session = cluster.connect() ``` -------------------------------- ### DateTime Truncate Microseconds Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/columns.html Set `DateTime.truncate_microseconds` to True to truncate microseconds for equality comparison between assigned values and values read from the database. Defaults to False for legacy behavior. ```python DateTime.truncate_microseconds = True assert Model.create(id=0, d=datetime.utcnow()) == Model.objects(id=0).first() ``` -------------------------------- ### HostFilterPolicy Example Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/policies.html Use HostFilterPolicy to create a blacklist or whitelist of hosts. The predicate function determines which hosts are ignored. Note that this can negatively impact the ordering properties of wrapped policies. ```python def address_is_ignored(host): return host.address in [ignored_address0, ignored_address1] blacklist_filter_policy = HostFilterPolicy( child_policy=RoundRobinPolicy(), predicate=address_is_ignored ) cluster = Cluster( primary_host, load_balancing_policy=blacklist_filter_policy, ) ``` -------------------------------- ### cassandra.cqlengine.connection.default() Source: https://python-driver.docs.scylladb.com/stable/api/cassandra/cqlengine/connection.html Configures the default connection to localhost, using the driver defaults (except for row_factory). ```APIDOC ## default() ### Description Configures the default connection to localhost, using the driver defaults (except for row_factory). ### Method N/A (Function call) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```