This tutorial shows you how build a simple Python application with CockroachDB and the Django framework.
CockroachDB supports Django versions 3.1+.
Note:
The example code and instructions on this page use Python 3.9 and Django 3.1.
Step 1. Start CockroachDB
Choose your installation method
You can install a CockroachDB Serverless cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or ccloud, a command-line interface (CLI) tool.
Create a free cluster
Note:
Organizations without billing information on file can only create one CockroachDB Basic cluster.
On the Cloud & Regions page, select a cloud provider (GCP or AWS) in the Cloud provider section.
In the Regions section, select a region for the cluster. Refer to CockroachDB Cloud Regions for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click Add region and select additional regions.
Click Next: Capacity.
On the Capacity page, select Start for free. Click Next: Finalize.
On the Finalize page, click Create cluster.
Your cluster will be created in a few seconds and the Create SQL user dialog will display.
Create a SQL user
The Create SQL user dialog allows you to create a new SQL user and password.
Enter a username in the SQL user field or use the one provided by default.
Click Generate & save password.
Copy the generated password and save it in a secure location.
Click Next.
Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see [Manage SQL users on a cluster.
Get the root certificate
The Connect to cluster dialog shows information about how to connect to your cluster.
Select General connection string from the Select option dropdown.
Open a new terminal on your local machine, and run the CA Cert download command provided in the Download CA Cert section. The client driver used in this tutorial requires this certificate to connect to CockroachDB Cloud.
Get the connection information
Select Parameters only from the Select option dropdown.
Copy the connection information for each parameter displayed and save it in a secure location.
Follow these steps to create a CockroachDB Serverless cluster using the ccloud CLI tool.
Note:
The ccloud CLI tool is in Preview.
Install ccloud
Choose your OS:
You can install ccloud using either Homebrew or by downloading the binary.
In a PowerShell window, enter the following command to download and extract the ccloud binary and add it to your PATH:
$ErrorActionPreference="Stop";[Net.ServicePointManager]::SecurityProtocol =[Net.SecurityProtocolType]::Tls12;$ProgressPreference='SilentlyContinue';$null= New-Item -Type Directory -Force$env:appdata/ccloud; Invoke-WebRequest -Uri https://binaries.cockroachdb.com/ccloud/ccloud_windows-amd64_0.6.12.zip -OutFile ccloud.zip; Expand-Archive -Force-Path ccloud.zip; Copy-Item -Force ccloud/ccloud.exe -Destination$env:appdata/ccloud;$Env:PATH +=";$env:appdata/ccloud";# We recommend adding ";$env:appdata/ccloud" to the Path variable for your system environment. See https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_environment_variables#saving-changes-to-environment-variables for more information.
Run ccloud quickstart to create a new cluster, create a SQL user, and retrieve the connection string.
The easiest way of getting started with CockroachDB Cloud is to use ccloud quickstart. The ccloud quickstart command guides you through logging in to CockroachDB Cloud, creating a new CockroachDB Basic cluster, and connecting to the new cluster. Run ccloud quickstart and follow the instructions:
ccloud quickstart
The ccloud quickstart command will open a browser window to log you in to CockroachDB Cloud. If you are new to CockroachDB Cloud, you can register using one of the single sign-on (SSO) options, or create a new account using an email address.
The ccloud quickstart command will prompt you for the cluster name, cloud provider, and cloud provider region, then ask if you want to connect to the cluster. Each prompt has default values that you can select, or change if you want a different option.
Select Parameters only then copy the connection parameters displayed and save them in a secure location.
? How would you like to connect? Parameters only
Looking up cluster ID: succeeded
Creating SQL user: succeeded
Success! Created SQL user
name: maxroach
cluster: 37174250-b944-461f-b1c1-3a99edb6af32
Retrieving cluster info: succeeded
Connection parameters
Database: defaultdb
Host: blue-dog-147.6wr.cockroachlabs.cloud
Password: ThisIsNotAGoodPassword
Port: 26257
Username: maxroach
The major version of django-cockroachdb must correspond to the major version of django. The minor release numbers do not need to match.
The requirements.txt file at the top level of the example-app-python-django project directory contains a list of the requirements needed to run this application:
This tutorial uses virtualenv for dependency management.
Install virtualenv:
$ pip install virtualenv
At the top level of the app's project directory, create and then activate a virtual environment:
$ virtualenv env
$ source env/bin/activate
Install the modules listed in requirements.txt to the virtual environment:
$ pip install-r requirements.txt
Step 4. Build out the application
Configure the database connection
Open cockroach_example/cockroach_example/settings.py, and configure the DATABASES dictionary to connect to your cluster using the connection parameters that you copied earlier.
After you have configured the app's database connection, you can start building out the application.
Models
Start by building some models, defined in a file called models.py. You can copy the sample code below and paste it into a new file, or you can download the file directly.
In this file, we define some simple classes that map to the tables in the cluster.
Views
Next, build out some class-based views for the application in a file called views.py. You can copy the sample code below and paste it into a new file, or you can download the file directly.
fromdjango.httpimportJsonResponse,HttpResponsefromdjango.utils.decoratorsimportmethod_decoratorfromdjango.views.genericimportViewfromdjango.views.decorators.csrfimportcsrf_exemptfromdjango.dbimportError,IntegrityErrorfromdjango.db.transactionimportatomicfrompsycopg2importerrorcodesimportjsonimportsysimporttimefrom.modelsimport*# Warning: Do not use retry_on_exception in an inner nested transaction.
defretry_on_exception(num_retries=3,on_failure=HttpResponse(status=500),delay_=0.5,backoff_=1.5):defretry(view):defwrapper(*args,**kwargs):delay=delay_foriinrange(num_retries):try:returnview(*args,**kwargs)exceptIntegrityErrorasex:ifi==num_retries-1:returnon_failureelifgetattr(ex.__cause__,'pgcode','')==errorcodes.SERIALIZATION_FAILURE:time.sleep(delay)delay*=backoff_exceptErrorasex:returnon_failurereturnwrapperreturnretryclassPingView(View):defget(self,request,*args,**kwargs):returnHttpResponse("python/django",status=200)@method_decorator(csrf_exempt,name='dispatch')classCustomersView(View):defget(self,request,id=None,*args,**kwargs):ifidisNone:customers=list(Customers.objects.values())else:customers=list(Customers.objects.filter(id=id).values())returnJsonResponse(customers,safe=False)@retry_on_exception(3)@atomicdefpost(self,request,*args,**kwargs):form_data=json.loads(request.body.decode())name=form_data['name']c=Customers(name=name)c.save()returnHttpResponse(status=200)@retry_on_exception(3)@atomicdefdelete(self,request,id=None,*args,**kwargs):ifidisNone:returnHttpResponse(status=404)Customers.objects.filter(id=id).delete()returnHttpResponse(status=200)# The PUT method is shadowed by the POST method, so there doesn't seem
# to be a reason to include it.
@method_decorator(csrf_exempt,name='dispatch')classProductView(View):defget(self,request,id=None,*args,**kwargs):ifidisNone:products=list(Products.objects.values())else:products=list(Products.objects.filter(id=id).values())returnJsonResponse(products,safe=False)@retry_on_exception(3)@atomicdefpost(self,request,*args,**kwargs):form_data=json.loads(request.body.decode())name,price=form_data['name'],form_data['price']p=Products(name=name,price=price)p.save()returnHttpResponse(status=200)# The REST API outlined in the github does not say that /product/ needs
# a PUT and DELETE method
@method_decorator(csrf_exempt,name='dispatch')classOrdersView(View):defget(self,request,id=None,*args,**kwargs):ifidisNone:orders=list(Orders.objects.values())else:orders=list(Orders.objects.filter(id=id).values())returnJsonResponse(orders,safe=False)@retry_on_exception(3)@atomicdefpost(self,request,*args,**kwargs):form_data=json.loads(request.body.decode())c=Customers.objects.get(id=form_data['customer']['id'])o=Orders(subtotal=form_data['subtotal'],customer=c)o.save()forpinform_data['products']:p=Products.objects.get(id=p['id'])o.product.add(p)o.save()returnHttpResponse(status=200)
This file defines the application's views as classes. Each view class corresponds to one of the table classes defined in models.py. The methods of these classes define read and write transactions on the tables in the database.
Importantly, the file defines a transaction retry loop in the decorator function retry_on_exception(). This function decorates each view method, ensuring that transaction ordering guarantees meet the ANSI SERIALIZABLE isolation level. For more information about how transactions (and retries) work, see Transactions.
URL routes
Lastly, define some URL routes in a file called urls.py. You can copy the sample code below and paste it into the existing urls.py file, or you can download the file directly and replace the existing one.
fromdjango.contribimportadminfromdjango.urlsimportpathfrom.viewsimportCustomersView,OrdersView,PingView,ProductViewurlpatterns=[path('admin/',admin.site.urls),path('ping/',PingView.as_view()),# Endpoints for customers URL.
path('customer/',CustomersView.as_view(),name='customers'),path('customer/<uuid:id>/',CustomersView.as_view(),name='customers'),# Endpoints for customers URL.
path('product/',ProductView.as_view(),name='product'),path('product/<uuid:id>/',ProductView.as_view(),name='product'),path('order/',OrdersView.as_view(),name='order'),]
Step 5. Initialize the database
In the top cockroach_example directory, use the manage.py script to create Django migrations that initialize the database for the application:
This initializes the tables defined in models.py, in addition to some other tables for the admin functionality included with Django's starter application.
Step 6. Run the app
In a different terminal, navigate to the top of the cockroach_example directory, and start the app:
$ python manage.py runserver 0.0.0.0:8000
The output should look like this:
...
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
To perform simple reads and writes to the database, you can send HTTP requests to the application server listening at http://0.0.0.0:8000/.
In a new terminal, use curl to send a POST request to the application:
$ curl --header"Content-Type: application/json"\--request POST \--data'{"name":"Carl"}' http://0.0.0.0:8000/customer/
This request inserts a new row into the cockroach_example_customers table.
Send a GET request to read from the cockroach_example_customers table: