Develop Python Apps

AttentionThis page documents an earlier version. Go to the latest (v2.1)version.

Installation

Install the python driver using the following command.

  1. $ pip install cassandra-driver

Working Example

Pre-requisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe and are able to interact with it using the CQL shell. If not, please follow these steps in the quick start guide.

Writing the python code

Create a file yb-cql-helloworld.py and add the following content to it.

  1. from cassandra.cluster import Cluster
  2. # Create the cluster connection.
  3. cluster = Cluster(['127.0.0.1'])
  4. session = cluster.connect()
  5. # Create the keyspace.
  6. session.execute('CREATE KEYSPACE IF NOT EXISTS ybdemo;')
  7. print "Created keyspace ybdemo"
  8. # Create the table.
  9. session.execute(
  10. """
  11. CREATE TABLE IF NOT EXISTS ybdemo.employee (id int PRIMARY KEY,
  12. name varchar,
  13. age int,
  14. language varchar);
  15. """)
  16. print "Created table employee"
  17. # Insert a row.
  18. session.execute(
  19. """
  20. INSERT INTO ybdemo.employee (id, name, age, language)
  21. VALUES (1, 'John', 35, 'NodeJS');
  22. """)
  23. print "Inserted (id, name, age, language) = (1, 'John', 35, 'Python')"
  24. # Query the row.
  25. rows = session.execute('SELECT name, age, language FROM ybdemo.employee WHERE id = 1;')
  26. for row in rows:
  27. print row.name, row.age, row.language
  28. # Close the connection.
  29. cluster.shutdown()

Running the application

To run the application, type the following:

  1. $ python yb-cql-helloworld.py

You should see the following output.

  1. Created keyspace ybdemo
  2. Created table employee
  3. Inserted (id, name, age, language) = (1, 'John', 35, 'Python')
  4. John 35 Python

Installation

Install the python driver using the following command.

  1. $ sudo pip install redis

Working Example

Pre-requisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe and are able to interact with it using the Redis shell. If not, please follow these steps in the quick start guide.

Writing the python code

Create a file yb-redis-helloworld.py and add the following content to it.

  1. import redis
  2. # Create the cluster connection.
  3. r = redis.Redis(host='localhost', port=6379)
  4. # Insert the user profile.
  5. userid = 1
  6. user_profile = {"name": "John", "age": "35", "language": "Python"}
  7. r.hmset(userid, user_profile)
  8. print "Inserted userid=1, profile=%s" % user_profile
  9. # Query the user profile.
  10. print r.hgetall(userid)

Running the application

To run the application, type the following:

  1. $ python yb-redis-helloworld.py

You should see the following output.

  1. Inserted userid=1, profile={'age': '35', 'name': 'John', 'language': 'Python'}
  2. {'age': '35', 'name': 'John', 'language': 'Python'}