### Install cassandra-driver Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/upgrading.md Install the base cassandra-driver package. This is the recommended installation for most users. ```bash pip install cassandra-driver ``` -------------------------------- ### Install from Source Distribution Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Install the driver using the generated source distribution. Replace with the actual version number. ```bash pip install dist/cassandra-driver-.tar.gz ``` -------------------------------- ### Install Snappy Compression Support Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the python-snappy package to enable Snappy compression support for communication between the driver and Cassandra. ```bash pip install python-snappy ``` -------------------------------- ### Install cassandra-driver using pip Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README.rst Use pip to install the cassandra-driver package. This is the recommended method for installation. ```bash $ pip install cassandra-driver ``` -------------------------------- ### Install Metrics Support Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the scales module, which is required for the driver's built-in support for capturing Cluster.metrics. ```bash pip install scales ``` -------------------------------- ### Configure Cluster to Use Libev Event Loop Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Example demonstrating how to configure the Cassandra cluster object to use the LibevConnection for the event loop. This requires the libev extension to be successfully built and installed. ```python >>> from cassandra.io.libevreactor import LibevConnection >>> from cassandra.cluster import Cluster >>> cluster = Cluster() >>> cluster.connection_class = LibevConnection >>> session = cluster.connect() ``` -------------------------------- ### Setup CqlEngine with Astra Cloud Config Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cloud.md Configure CqlEngine using the `setup` function with Astra's cloud configuration. The `hosts` argument is ignored when a cloud config is provided. ```python from cassandra.cqlengine import connection ... connection.setup( None, # or anything else "myastrakeyspace", cloud={ 'secure_connect_bundle':'/path/to/secure-connect-test.zip' }, auth_provider=PlainTextAuthProvider('user', 'pass')) ``` -------------------------------- ### Setup and Register New Connection Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/connections.md Initialize the default connection and register additional connections with specified hosts. Ensure the hosts are accessible. ```python from cassandra.cqlengine import connection connection.setup(['127.0.0.1') connection.register_connection('cluster2', ['127.0.0.2']) ``` -------------------------------- ### Verify Cassandra Driver Installation Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Run this command to check if the driver is installed correctly and to display its version. ```python python -c 'import cassandra; print(cassandra.__version__)' ``` -------------------------------- ### Install libev on Windows using vcpkg Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the libev library on Windows using the vcpkg package manager. This is required for building the libev extension on Windows. ```bash $ vcpkg install libev ``` -------------------------------- ### Install LZ4 Compression Support Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the lz4 package to enable LZ4 compression support for communication between the driver and Cassandra. ```bash pip install lz4 ``` -------------------------------- ### Install libev on Debian/Ubuntu Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the libev event loop library and development files on Debian or Ubuntu systems using the apt-get package manager. ```bash $ sudo apt-get install libev4 libev-dev ``` -------------------------------- ### Install libev on macOS using Homebrew Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the libev event loop library on macOS using the Homebrew package manager. ```bash $ brew install libev ``` -------------------------------- ### Install Cassandra Driver from Source Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the driver directly from a source checkout or tarball after ensuring all Python dependencies are met. This command assumes you are in the root directory of the source code. ```bash pip install . ``` -------------------------------- ### Install DataStax Graph Extra Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the graph extra to enable the optional fluent graph API, which depends on Apache TinkerPop (gremlinpython). ```bash pip install cassandra-driver[graph] ``` -------------------------------- ### Install libev on RHEL/CentOS/Fedora Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the libev event loop library and development files on RHEL, CentOS, or Fedora systems using the yum package manager. ```bash $ sudo yum install libev libev-devel ``` -------------------------------- ### Install GCC and Python Headers on Ubuntu/Debian Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install necessary packages for compiling C extensions, including GCC and Python development headers, on Ubuntu and Debian-based systems. ```bash $ sudo apt-get install gcc python-dev ``` -------------------------------- ### Install Column-Level Encryption (CLE) Support Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install the cryptography module, which is required for client-side encryption and decryption of data. This can be done via the 'cle' extra or directly. ```bash pip install cassandra-driver[cle] ``` ```bash pip install cryptography ``` -------------------------------- ### Per-Query TTL Examples Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Demonstrates setting TTL values on a per-query basis for create, update, and save operations. The default TTL is automatically applied if not overridden. ```python user = User.objects.create(user_id=1) # Default TTL 20 will be set automatically on the server user.ttl(30).update(age=21) # Update the TTL to 30 User.objects.ttl(10).create(user_id=1) # TTL 10 User(user_id=1, age=21).ttl(10).save() # TTL 10 ``` -------------------------------- ### Install GCC and Python Headers on RedHat/CentOS/Fedora Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md Install necessary packages for compiling C extensions, including GCC and Python development headers, on RedHat and its derivatives like CentOS and Fedora. ```bash $ sudo yum install gcc python-devel ``` -------------------------------- ### Immutable QuerySets Example Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Demonstrates that QuerySet methods return new QuerySet objects rather than modifying the original. This ensures that the initial QuerySet remains unchanged. ```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') ``` -------------------------------- ### Setup Connection and Use NamedTable Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Connects to a Cassandra instance and demonstrates querying a table named 'user' without defining a specific model class. Useful for system tables or exploring databases. ```python from cassandra.cqlengine.connection import setup setup("127.0.0.1", "cqlengine_test") from cassandra.cqlengine.named import NamedTable user = NamedTable("cqlengine_test", "user") user.objects() user.objects()[0] # {u'pk': 1, u't': datetime.datetime(2014, 6, 26, 17, 10, 31, 774000)} ``` -------------------------------- ### Configure Traversal Execution Profiles Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph_fluent.md Set up custom execution profiles for graph traversal queries. This example demonstrates creating profiles for Core graphs using GraphSON3 and for Classic graphs. ```python from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT from cassandra.datastax.graph import GraphProtocol from cassandra.datastax.graph.fluent import DseGraph # Using GraphSON3 as graph protocol is a requirement with Core graphs. ep = DseGraph.create_execution_profile( 'graph_name', graph_protocol=GraphProtocol.GRAPHSON_3_0) # For Classic graphs, GraphSON1, GraphSON2 and GraphSON3 (DSE 6.8+) are supported. ep_classic = DseGraph.create_execution_profile('classic_graph_name') # default is GraphSON2 cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep, 'classic': ep_classic}) session = cluster.connect() g = DseGraph.traversal_source(session) # Build the GraphTraversalSource print(g.V().toList()) # Traverse the Graph ``` -------------------------------- ### Two-way SSL verification with Twisted and pyOpenSSL Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/security.md This configuration is for using SSL with the Twisted reactor and pyOpenSSL. It requires pyOpenSSL to be installed and uses its constants for SSL context configuration. Ensure 'check_hostname' is set appropriately for your environment. ```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() ``` -------------------------------- ### Build and Execute Fluent Graph Queries Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph_fluent.md Construct Gremlin traversals using the Python fluent API for better maintainability. This example shows creating an execution profile for GraphSON3 and executing a traversal. ```python from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT from cassandra.datastax.graph import GraphProtocol from cassandra.datastax.graph.fluent import DseGraph # Create an execution profile, using GraphSON3 for Core graphs ep_graphson3 = DseGraph.create_execution_profile( 'my_core_graph_name', graph_protocol=GraphProtocol.GRAPHSON_3_0) cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep_graphson3}) session = cluster.connect() # Execute a fluent graph query g = DseGraph.traversal_source(session=session) g.addV('genre').property('genreId', 1).property('name', 'Action').next() # implicit execution caused by iterating over results for v in g.V().has('genre', 'name', 'Drama').in_('belongsTo').valueMap(): print(v) ``` -------------------------------- ### Create Cassandra Session After Fork in WSGI Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/faq.md In WSGI applications using process forking (like uWSGI), create Cassandra sessions and prepared statements after the fork to avoid connection/IO timeouts. This example uses the `postfork` hook from `uwsgidecorators`. ```python from flask import Flask from uwsgidecorators import postfork from cassandra.cluster import Cluster session = None prepared = None @postfork def connect(): global session, prepared session = Cluster().connect() prepared = session.prepare("SELECT release_version FROM system.local WHERE key=?") app = Flask(__name__) @app.route('/') def server_version(): row = session.execute(prepared, ('local',))[0] return row.release_version ``` -------------------------------- ### Build Documentation Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Build the documentation for the Cassandra Python driver using this command. ```bash python setup.py doc ``` -------------------------------- ### Show Benchmark Script Help Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Display help and available options for a benchmark script. ```bash python benchmarks/future_batches.py --help ``` -------------------------------- ### Create Session and Connect Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Instantiates a Cluster and then creates a Session to establish connections and execute queries. ```python cluster = Cluster() session = cluster.connect() ``` -------------------------------- ### Define Model, Connect, Sync Table, Create and Query Data Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/object_mapper.md This snippet shows the complete workflow from defining a Cassandra model using cqlengine, establishing a connection, synchronizing the table schema, creating multiple records, and performing basic queries with filtering and counting. ```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 https://docs.datastax.com/en/developer/python-driver/latest/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 ``` -------------------------------- ### Clean and Build Source Distribution Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Clean the working directory and build the source distribution for PyPI upload. ```bash python setup.py clean rm dist/* ``` ```bash python setup.py sdist ``` -------------------------------- ### Get a Single Object with get() Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Use the .get() method on a filtered QuerySet to retrieve a single matching object. This is useful when you expect exactly one result. ```python q = Automobile.objects.filter(manufacturer='Tesla') q = q.filter(year=2012) car = q.get() ``` -------------------------------- ### Package Source Distribution (Pre-release) Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Build a source zip archive for a pre-release version, including a commit hash in the archive name. ```bash python setup.py egg_info -b-`git rev-parse --short HEAD` sdist --formats=zip ``` -------------------------------- ### OSX Installation Fix Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/installation.md If encountering a 'clang: error: unknown argument: "-mno-fused-madd"' on OSX with XCode 5.1, re-run the installation with this extra compilation flag. ```bash ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install cassandra-driver ``` -------------------------------- ### Using create_keyspace_simple for Simple Strategy Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/upgrade_guide.md Use `create_keyspace_simple` for creating keyspaces with a simple replication strategy. This replaces the deprecated `create_keyspace` function for this specific strategy. ```python create_keyspace_simple() ``` -------------------------------- ### Define a Model for Rows Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Defines a simple Cassandra model with an integer primary key and a text field. This serves as a base for subsequent query examples. ```python class Row(Model): id = columns.Integer(primary_key=True) name = columns.Text() ``` -------------------------------- ### Initialize DSE Graph Session Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph_fluent.md Sets up the DSE graph execution profile and connects to the cluster. Required for explicit graph execution. ```python from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT from cassandra.datastax.graph import GraphProtocol from cassandra.datastax.graph.fluent import DseGraph from pprint import pprint ep = DseGraph.create_execution_profile( 'graph_name', graph_protocol=GraphProtocol.GRAPHSON_3_0) cluster = Cluster(execution_profiles={EXEC_PROFILE_GRAPH_DEFAULT: ep}) session = cluster.connect() g = DseGraph.traversal_source(session=session) ``` -------------------------------- ### Create Cassandra Benchmark Cluster Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Create a local Cassandra cluster for benchmarking purposes using ccm. ```bash ccm create benchmark_cluster -v 4.0.1 -n 1 -s ``` -------------------------------- ### Package Source Distribution (Release) Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Build a source zip archive for a tagged release version. ```bash python setup.py sdist --formats=zip ``` -------------------------------- ### Find Movies by Actor using Graph Traversal Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph.md Execute a graph traversal query to find all movies an actor has been in. This example uses `session.execute_graph` with a Gremlin query. ```python for r in session.execute_graph(""" g.V().has('person', 'name', 'Mark Wahlberg').in('actor').valueMap();"""): print(r) ``` -------------------------------- ### Execute Async Query and Get Result Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Use execute_async() to run a query asynchronously and block for the result using future.result(). This is useful for executing many queries concurrently. ```python from cassandra import ReadTimeout query = "SELECT * FROM users WHERE user_id=%s" future = session.execute_async(query, [user_id]) # ... do some other work try: rows = future.result() user = rows[0] print(user.name, user.age) except ReadTimeout: log.exception("Query timed out:") ``` ```python # build a list of futures futures = [] query = "SELECT * FROM users WHERE user_id=%s" for user_id in ids_to_fetch: futures.append(session.execute_async(query, [user_id]) # wait for them to complete and use the results for future in futures: rows = future.result() print(rows[0].name) ``` -------------------------------- ### Update dse-graph imports to cassandra.datastax.graph Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/upgrading.md For dse-graph users, update import statements to use the new path within the cassandra-driver. This example shows the change from 'dse_graph' to 'cassandra.datastax.graph.fluent'. ```python from dse_graph import .. from dse_graph.query import .. # becomes from cassandra.datastax.graph.fluent import .. from cassandra.datastax.graph.fluent.query import .. ``` -------------------------------- ### UPDATE IF failure with tuple_factory Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/lwt.md Shows a failed UPDATE operation with an IF clause using tuple_factory. The result is a tuple starting with `False` and including the values that caused the condition to fail. ```python >>> session.execute("UPDATE t SET v = 1, x = 2 WHERE k = 0 IF v =0 AND x = 1") (False, 1, 2) ``` -------------------------------- ### Default Session Execution Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/execution_profiles.md Demonstrates basic session connection and query execution using the default execution profile. This profile matches existing default parameters. ```python from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect() local_query = 'SELECT rpc_address FROM system.local' for _ in cluster.metadata.all_hosts(): print(session.execute(local_query)[0]) ``` ```default Row(rpc_address='127.0.0.2') Row(rpc_address='127.0.0.1') ``` -------------------------------- ### INSERT IF NOT EXISTS failure with tuple_factory Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/lwt.md Illustrates a failed INSERT IF NOT EXISTS operation with tuple_factory. The result is a tuple starting with `False` and followed by the existing row's data. ```python >>> session.execute("INSERT INTO t (k,v) VALUES (0,0) IF NOT EXISTS") (False, 0, 0, None) ``` -------------------------------- ### Run Integration Tests with External Cassandra Cluster Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Run integration tests while using an already running external Cassandra cluster, preventing the test suite from starting its own. ```bash USE_CASS_EXTERNAL=1 CASSANDRA_VERSION=4.0.1 pytest tests/integration/standard ``` -------------------------------- ### Prepare and Execute a Statement Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Use `Session.prepare()` to create a prepared statement, then execute it with bound values. This reduces network traffic and CPU usage in Cassandra. ```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) ``` -------------------------------- ### Iterate Through Query Results Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/upgrading.md Use this method to consume query results of unknown size, allowing automatic paging as data is fetched. No specific setup is required beyond executing the query. ```python results = session.execute("SELECT * FROM system.local") for row in results: process(row) ``` -------------------------------- ### Register UDT with a Dictionary Mapping Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/user_defined_types.md Maps a Python dictionary to a Cassandra UDT. This allows UDT data to be accessed using dictionary key lookups. This example uses protocol_version 3. ```python cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") cluster.register_user_type('mykeyspace', 'address', dict) # insert a row using a prepared statement and a tuple insert_statement = session.prepare("INSERT INTO mykeyspace.users (id, location) VALUES (?, ?)") session.execute(insert_statement, [0, ("123 Main St.", 78723)]) # results will include dict instances results = session.execute("SELECT * FROM users") row = results[0] print(row.id, row.location['street'], row.location['zipcode']) ``` -------------------------------- ### Create a New Graph Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/classic_graph.md Use the system execution profile to create a new graph in the system. Ensure the graph name is provided. ```python from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT cluster = Cluster() session = cluster.connect() graph_name = 'movies' session.execute_graph("system.graph(name).ifNotExists().engine(Classic).create()", {'name': graph_name}, execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) ``` -------------------------------- ### Register UDT with a Class Mapping Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/user_defined_types.md Maps a Python class to a Cassandra UDT for insertion and retrieval. Ensure the class has attributes matching the UDT fields. This example uses protocol_version 3. ```python cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") # create a class to map to the "address" UDT class Address(object): def __init__(self, street, zipcode): self.street = street self.zipcode = zipcode cluster.register_user_type('mykeyspace', 'address', Address) # insert a row using an instance of Address session.execute("INSERT INTO users (id, location) VALUES (%s, %s)", (0, Address("123 Main St.", 78723))) # results will include Address instances results = session.execute("SELECT * FROM users") row = results[0] print(row.id, row.location.street, row.location.zipcode) ``` -------------------------------- ### Connect to Local Cassandra Instance Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Establishes a connection to a Cassandra instance running on the local machine (127.0.0.1). ```python from cassandra.cluster import Cluster cluster = Cluster() ``` -------------------------------- ### Customize Encoder for Non-Prepared Statements Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/upgrading.md Customize how Python types are converted to CQL literals for non-prepared statements by assigning a new encoding function to `session.encoder.mapping`. This example maps the `tuple` type to `cql_encode_tuple`. ```python cluster = Cluster() session = cluster.connect() session.encoder.mapping[tuple] = session.encoder.cql_encode_tuple ``` -------------------------------- ### Proxy Login with Kerberos (DSEGSSAPIAuthProvider) Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/security.md Use this for proxy login with Kerberos. Ensure the server user's Kerberos ticket is set using kinit. The authenticated user must have proxy login permissions for the target user. ```python from cassandra.cluster import Cluster from cassandra.auth import DSEGSSAPIAuthProvider # Ensure the kerberos ticket of the server user is set with the kinit utility. auth_provider = DSEGSSAPIAuthProvider(service='dse', qops=["auth"], principal="server@DATASTAX.COM", authorization_id='user1@DATASTAX.COM') c = Cluster(auth_provider=auth_provider) s = c.connect() s.execute(...) # all requests will be executed as 'user1' ``` -------------------------------- ### Upload to PyPI Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Upload the built distribution files to PyPI using twine. ```bash cp /path/to/wheels/*.whl dist/ twine upload dist/* ``` -------------------------------- ### Access Model Instances as Dictionaries Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/models.md Model instances can be treated like dictionaries for accessing and modifying data. This example shows creating a `Person` instance and then accessing its attributes using dictionary-like syntax. ```python from cassandra.cqlengine import columns from cassandra.cqlengine.models import Model 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 ``` -------------------------------- ### Create a Graph using System API Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph.md Use the system execution profile to create a new graph. Ensure the `cassandra.cluster` module is imported. ```python from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT cluster = Cluster() session = cluster.connect() graph_name = 'movies' session.execute_graph("system.graph(name).create()", {'name': graph_name}, execution_profile=EXEC_PROFILE_GRAPH_SYSTEM_DEFAULT) ``` -------------------------------- ### Query using Prefix Search Predicate Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/graph_fluent.md Performs a graph query using the Search.prefix predicate to find vertices where a text field starts with a specified string. Requires a text match index. ```python from cassandra.datastax.graph.fluent.predicates import Search # ... g = DseGraph.traversal_source() query = DseGraph.query_from_traversal( g.V().has('my_vertex_label','text_field', Search.prefix('Hello')).values('text_field')) session.execute_graph(query) ``` -------------------------------- ### Configure Driver for Server Verifying Client Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/security.md Use this configuration when the Cassandra server requires client authentication. Load the client's certificate and key into the SSL context. ```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() ``` -------------------------------- ### Get the First Object with first() Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/queryset.md Use the .first() method to retrieve the first object in a QuerySet. This is efficient if you only need one record and don't care about specific filtering beyond what's already applied. ```python q = Automobile.objects.filter(manufacturer='Tesla') q = q.filter(year=2012) car = q.first() ``` -------------------------------- ### Using create_keyspace_network_topology for Network Topology Strategy Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/upgrade_guide.md Use `create_keyspace_network_topology` for creating keyspaces with a network topology replication strategy. This replaces the deprecated `create_keyspace` function for this strategy. ```python create_keyspace_network_topology() ``` -------------------------------- ### Update Python imports from dse to cassandra Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/upgrading.md When migrating from dse-driver to cassandra-driver, update import statements to reference the 'cassandra' module instead of 'dse'. This example shows common import changes for Cluster, Auth, and Policies. ```python from dse.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT from dse.auth import PlainTextAuthProvider from dse.policies import WhiteListRoundRobinPolicy # becomes from cassandra.cluster import Cluster, EXEC_PROFILE_GRAPH_DEFAULT from cassandra.auth import PlainTextAuthProvider from cassandra.policies import WhiteListRoundRobinPolicy ``` -------------------------------- ### Connect to Session with Default Keyspace Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Connects to a Cassandra cluster and sets a default keyspace for all queries made through the session. ```python cluster = Cluster() session = cluster.connect('mykeyspace') ``` -------------------------------- ### Delete individual column values with None Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/faq.md Setting a column's value to `None` during an update is equivalent to issuing a CQL `DELETE` for that specific column. This example shows how to delete the 'text' column's value. ```python class MyModel(Model): id = columns.Integer(primary_key=True) text = columns.Text() m = MyModel.create(id=1, text='We can delete this with None') assert MyModel.objects(id=1).first().text is not None m.update(text=None) assert MyModel.objects(id=1).first().text is None ``` -------------------------------- ### Change Session Keyspace Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/getting_started.md Demonstrates how to change the default keyspace for an existing session using `set_keyspace()` or executing a `USE` query. ```python session.set_keyspace('users') # or you can do this instead session.execute('USE users') ``` -------------------------------- ### Create new rows with BatchQuery Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/faq.md Use the `.create` method within a `BatchQuery` context manager to create new rows. This example demonstrates how Cassandra resolves conflicts when the same column is updated multiple times within a batch, prioritizing the largest value. ```python class MyMode(Model): id = columns.Integer(primary_key=True) count = columns.Integer() text = columns.Text() with BatchQuery() as b: MyModel.batch(b).create(id=1, count=2, text='123') MyModel.batch(b).create(id=1, count=3, text='111') assert MyModel.objects(id=1).first().count == 3 assert MyModel.objects(id=1).first().text == '123' ``` -------------------------------- ### Run Benchmark Script Source: https://github.com/apache/cassandra-python-driver/blob/trunk/README-dev.rst Execute a specific benchmark script. ```bash python benchmarks/future_batches.py ``` -------------------------------- ### Insert UDT Data with Prepared Statements Without Registration Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/user_defined_types.md Inserts data into a UDT column using a prepared statement without prior UDT registration. The object must have attributes matching the UDT field names. This example uses protocol_version 3. ```python cluster = Cluster(protocol_version=3) session = cluster.connect() session.set_keyspace('mykeyspace') session.execute("CREATE TYPE address (street text, zipcode int)") session.execute("CREATE TABLE users (id int PRIMARY KEY, location frozen
)") class Foo(object): def __init__(self, street, zipcode, otherstuff): self.street = street self.zipcode = zipcode self.otherstuff = otherstuff insert_statement = session.prepare("INSERT INTO users (id, location) VALUES (?, ?)") # since we're using a prepared statement, we don't *have* to register # a class to map to the UDT to insert data. The object just needs to have # "street" and "zipcode" attributes (which Foo does): session.execute(insert_statement, [0, Foo("123 Main St.", 78723, "some other stuff")]) # when we query data, UDT columns that don't have a class registered # will be returned as namedtuples: results = session.execute("SELECT * FROM users") first_row = results[0] address = first_row.location print(address) # prints "Address(street='123 Main St.', zipcode=78723)" street = address.street zipcode = address.street ``` -------------------------------- ### uWSGI Integration for Cassandra Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/third_party.md Ensures a new Cassandra session is returned for every new request in a uWSGI-run application. This is achieved by hooking Cassandra session initialization to the postfork event. ```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() ``` -------------------------------- ### QuerySet Connection Selection Source: https://github.com/apache/cassandra-python-driver/blob/trunk/docs/cqlengine/connections.md Select a connection or keyspace for specific queries using the `using()` method on QuerySets. This allows for fine-grained control over query execution. ```python Automobile.objects.using(connection='cluster1').create(manufacturer='honda', year=2010, model='civic') q = Automobile.objects.filter(manufacturer='Tesla') autos = q.using(keyspace='ks2', connection='cluster2').all() for auto in autos: auto.using(connection='cluster1').save() ```