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
3. # Create the cluster connection.
4. cluster = Cluster(['127.0.0.1'])
5. session = cluster.connect()
7. # Create the keyspace.
8. session.execute('CREATE KEYSPACE IF NOT EXISTS ybdemo;')
9. print "Created keyspace ybdemo"
11. # Create the table.
12. session.execute(
13. """
14. CREATE TABLE IF NOT EXISTS ybdemo.employee (id int PRIMARY KEY,
15. name varchar,
16. age int,
17. language varchar);
18. """)
19. print "Created table employee"
21. # Insert a row.
22. session.execute(
23. """
24. INSERT INTO ybdemo.employee (id, name, age, language)
25. VALUES (1, 'John', 35, 'NodeJS');
26. """)
27. print "Inserted (id, name, age, language) = (1, 'John', 35, 'Python')"
29. # Query the row.
30. rows = session.execute('SELECT name, age, language FROM ybdemo.employee WHERE id = 1;')
31. for row in rows:
32. print row.name, row.age, row.language
34. # Close the connection.
35. 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
3. # Create the cluster connection.
4. r = redis.Redis(host='localhost', port=6379)
6. # Insert the user profile.
7. userid = 1
8. user_profile = {"name": "John", "age": "35", "language": "Python"}
9. r.hmset(userid, user_profile)
10. print "Inserted userid=1, profile=%s" % user_profile
12. # Query the user profile.
13. 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'}
