-
Notifications
You must be signed in to change notification settings - Fork 36
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This PR updates the testing infrastructure to have the underlying tables be a bit more flexibly named for the ORM, along with adding the example code for Django.
- Loading branch information
Rohan Yadav
committed
Oct 7, 2019
1 parent
3415c55
commit 5b03c5b
Showing
15 changed files
with
454 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
.PHONY: start | ||
start: | ||
./manage.py migrate cockroach_example && ./manage.py runserver 6543 | ||
|
||
deps: | ||
git clone https://github.com/cockroachlabs/cockroach-django || true | ||
cd cockroach-django && pip install . | ||
python -m pip install "django<2" |
Empty file.
39 changes: 39 additions & 0 deletions
39
python/django/cockroach_example/migrations/0001_initial.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Generated by Django 2.2.6 on 2019-10-02 18:35 | ||
|
||
from django.db import migrations, models | ||
import django.db.models.deletion | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
initial = True | ||
|
||
dependencies = [ | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='Customers', | ||
fields=[ | ||
('id', models.AutoField(primary_key=True, serialize=False)), | ||
('name', models.CharField(max_length=250)), | ||
], | ||
), | ||
migrations.CreateModel( | ||
name='Products', | ||
fields=[ | ||
('id', models.AutoField(primary_key=True, serialize=False)), | ||
('name', models.CharField(max_length=250)), | ||
('price', models.DecimalField(decimal_places=2, max_digits=18)), | ||
], | ||
), | ||
migrations.CreateModel( | ||
name='Orders', | ||
fields=[ | ||
('id', models.AutoField(primary_key=True, serialize=False)), | ||
('subtotal', models.DecimalField(decimal_places=2, max_digits=18)), | ||
('customer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cockroach_example.Customers')), | ||
('product', models.ManyToManyField(to='cockroach_example.Products')), | ||
], | ||
), | ||
] |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from django.db import models | ||
|
||
class Customers(models.Model): | ||
id = models.AutoField(primary_key=True) | ||
name = models.CharField(max_length=250) | ||
|
||
class Products(models.Model): | ||
id = models.AutoField(primary_key=True) | ||
name = models.CharField(max_length=250) | ||
price = models.DecimalField(max_digits=18, decimal_places=2) | ||
|
||
class Orders(models.Model): | ||
id = models.AutoField(primary_key=True) | ||
subtotal = models.DecimalField(max_digits=18, decimal_places=2) | ||
# TODO (rohany): is setting null the right thing here? The schema doesn't say what to do. | ||
customer = models.ForeignKey(Customers, on_delete=models.SET_NULL, null=True) | ||
product = models.ManyToManyField(Products) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
""" | ||
Django settings for cockroach_example project. | ||
Generated by 'django-admin startproject' using Django 2.2.6. | ||
For more information on this file, see | ||
https://docs.djangoproject.com/en/2.2/topics/settings/ | ||
For the full list of settings and their values, see | ||
https://docs.djangoproject.com/en/2.2/ref/settings/ | ||
""" | ||
|
||
import os | ||
|
||
|
||
from urlparse import urlparse | ||
|
||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) | ||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
|
||
|
||
# Quick-start development settings - unsuitable for production | ||
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ | ||
|
||
# SECURITY WARNING: keep the secret key used in production secret! | ||
SECRET_KEY = '0pld^66i)iv4df8km5vc%1^sskuqjf16jk&z=c^rk--oh6i0i^' | ||
|
||
# SECURITY WARNING: don't run with debug turned on in production! | ||
DEBUG = True | ||
|
||
ALLOWED_HOSTS = [] | ||
|
||
|
||
# Application definition | ||
|
||
INSTALLED_APPS = [ | ||
'django.contrib.admin', | ||
'django.contrib.auth', | ||
'django.contrib.contenttypes', | ||
'django.contrib.sessions', | ||
'django.contrib.messages', | ||
'django.contrib.staticfiles', | ||
'cockroach_example', | ||
] | ||
|
||
MIDDLEWARE = [ | ||
'django.middleware.security.SecurityMiddleware', | ||
'django.contrib.sessions.middleware.SessionMiddleware', | ||
'django.middleware.common.CommonMiddleware', | ||
'django.middleware.csrf.CsrfViewMiddleware', | ||
'django.contrib.auth.middleware.AuthenticationMiddleware', | ||
'django.contrib.messages.middleware.MessageMiddleware', | ||
'django.middleware.clickjacking.XFrameOptionsMiddleware', | ||
] | ||
|
||
ROOT_URLCONF = 'cockroach_example.urls' | ||
|
||
TEMPLATES = [ | ||
{ | ||
'BACKEND': 'django.template.backends.django.DjangoTemplates', | ||
'DIRS': [], | ||
'APP_DIRS': True, | ||
'OPTIONS': { | ||
'context_processors': [ | ||
'django.template.context_processors.debug', | ||
'django.template.context_processors.request', | ||
'django.contrib.auth.context_processors.auth', | ||
'django.contrib.messages.context_processors.messages', | ||
], | ||
}, | ||
}, | ||
] | ||
|
||
WSGI_APPLICATION = 'cockroach_example.wsgi.application' | ||
|
||
|
||
# Database | ||
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases | ||
|
||
port = 26257 | ||
addr = os.getenv('ADDR') | ||
if addr is not None: | ||
url = urlparse(addr) | ||
port = url.port | ||
|
||
DATABASES = { | ||
'default': { | ||
# 'ENGINE' : 'django.db.backends.postgresql', | ||
'ENGINE' : 'cockroach.django', | ||
'NAME' : 'company_django', | ||
'USER' : 'root', | ||
'PASSWORD': '', | ||
'HOST' : 'localhost', | ||
'PORT' : port, | ||
} | ||
} | ||
|
||
|
||
# Password validation | ||
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators | ||
|
||
AUTH_PASSWORD_VALIDATORS = [ | ||
{ | ||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', | ||
}, | ||
{ | ||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', | ||
}, | ||
{ | ||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', | ||
}, | ||
{ | ||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', | ||
}, | ||
] | ||
|
||
|
||
# Internationalization | ||
# https://docs.djangoproject.com/en/2.2/topics/i18n/ | ||
|
||
LANGUAGE_CODE = 'en-us' | ||
|
||
TIME_ZONE = 'UTC' | ||
|
||
USE_I18N = True | ||
|
||
USE_L10N = True | ||
|
||
USE_TZ = True | ||
|
||
|
||
# Static files (CSS, JavaScript, Images) | ||
# https://docs.djangoproject.com/en/2.2/howto/static-files/ | ||
|
||
STATIC_URL = '/static/' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
"""cockroach_example URL Configuration | ||
The `urlpatterns` list routes URLs to views. For more information please see: | ||
https://docs.djangoproject.com/en/2.2/topics/http/urls/ | ||
Examples: | ||
Function views | ||
1. Add an import: from my_app import views | ||
2. Add a URL to urlpatterns: path('', views.home, name='home') | ||
Class-based views | ||
1. Add an import: from other_app.views import Home | ||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') | ||
Including another URLconf | ||
1. Import the include() function: from django.urls import include, path | ||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) | ||
""" | ||
from django.contrib import admin | ||
from django.conf.urls import url | ||
|
||
from .views import CustomersView, OrdersView, PingView, ProductView | ||
|
||
urlpatterns = [ | ||
url('admin/', admin.site.urls), | ||
|
||
url('ping/', PingView.as_view()), | ||
|
||
# Endpoints for customers URL. | ||
url('customer/', CustomersView.as_view(), name='customers'), | ||
url('customer/<int:id>/', CustomersView.as_view(), name='customers'), | ||
|
||
# Endpoints for customers URL. | ||
url('product/', ProductView.as_view(), name='product'), | ||
url('product/<int:id>/', ProductView.as_view(), name='product'), | ||
|
||
url('order/', OrdersView.as_view(), name='order'), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
from django.http import JsonResponse, HttpResponse | ||
from django.utils.decorators import method_decorator | ||
from django.views.generic import View | ||
from django.views.decorators.csrf import csrf_exempt | ||
|
||
import json | ||
import sys | ||
|
||
from .models import * | ||
|
||
class PingView(View): | ||
def get(self, request, *args, **kwargs): | ||
return HttpResponse("python/django", status=200) | ||
|
||
@method_decorator(csrf_exempt, name='dispatch') | ||
class CustomersView(View): | ||
def get(self, request, id=None, *args, **kwargs): | ||
if id is None: | ||
customers = list(Customers.objects.values()) | ||
else: | ||
customers = list(Customers.objects.filter(id=id).values()) | ||
return JsonResponse(customers, safe=False) | ||
|
||
def post(self, request, *args, **kwargs): | ||
form_data = json.loads(request.body.decode()) | ||
name = form_data['name'] | ||
c = Customers(name=name) | ||
c.save() | ||
return HttpResponse(status=200) | ||
|
||
def delete(self, request, id=None, *args, **kwargs): | ||
if id is None: | ||
return HttpResponse(status=404) | ||
Customers.objects.filter(id=id).delete() | ||
return HttpResponse(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') | ||
class ProductView(View): | ||
def get(self, request, id=None, *args, **kwargs): | ||
if id is None: | ||
products = list(Products.objects.values()) | ||
else: | ||
products = list(Products.objects.filter(id=id).values()) | ||
return JsonResponse(products, safe=False) | ||
|
||
def post(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() | ||
return HttpResponse(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') | ||
class OrdersView(View): | ||
def get(self, request, id=None, *args, **kwargs): | ||
if id is None: | ||
orders = list(Orders.objects.values()) | ||
else: | ||
orders = list(Orders.objects.filter(id=id).values()) | ||
return JsonResponse(orders, safe=False) | ||
|
||
def post(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() | ||
for p in form_data['products']: | ||
p = Products.objects.get(id=p['id']) | ||
o.product.add(p) | ||
o.save() | ||
return HttpResponse(status=200) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
""" | ||
WSGI config for cockroach_example project. | ||
It exposes the WSGI callable as a module-level variable named ``application``. | ||
For more information on this file, see | ||
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ | ||
""" | ||
|
||
import os | ||
|
||
from django.core.wsgi import get_wsgi_application | ||
|
||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cockroach_example.settings') | ||
|
||
application = get_wsgi_application() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
#!/usr/bin/env python | ||
"""Django's command-line utility for administrative tasks.""" | ||
import os | ||
import sys | ||
|
||
|
||
def main(): | ||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cockroach_example.settings') | ||
try: | ||
from django.core.management import execute_from_command_line | ||
except ImportError as exc: | ||
raise ImportError( | ||
"Couldn't import Django. Are you sure it's installed and " | ||
"available on your PYTHONPATH environment variable? Did you " | ||
"forget to activate a virtual environment?" | ||
) | ||
execute_from_command_line(sys.argv) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Oops, something went wrong.