Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

django: Demo app created #63

Merged
merged 1 commit into from
Oct 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,4 @@ deps:
$(MAKE) deps -C ./python/sqlalchemy
$(MAKE) deps -C ./ruby/activerecord
$(MAKE) deps -C ./ruby/ar4
$(MAKE) deps -C ./python/django
8 changes: 8 additions & 0 deletions python/django/Makefile
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.
45 changes: 45 additions & 0 deletions python/django/cockroach_example/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.25 on 2019-10-14 18:21
from __future__ import unicode_literals

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='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.CASCADE, to='cockroach_example.Customers')),
],
),
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.AddField(
model_name='orders',
name='product',
field=models.ManyToManyField(to='cockroach_example.Products'),
),
]
Empty file.
17 changes: 17 additions & 0 deletions python/django/cockroach_example/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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)
customer = models.ForeignKey(Customers, on_delete=models.CASCADE, null=True)
product = models.ManyToManyField(Products)

134 changes: 134 additions & 0 deletions python/django/cockroach_example/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""
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' : '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/'
35 changes: 35 additions & 0 deletions python/django/cockroach_example/urls.py
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'),
]
77 changes: 77 additions & 0 deletions python/django/cockroach_example/views.py
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)
16 changes: 16 additions & 0 deletions python/django/cockroach_example/wsgi.py
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()
21 changes: 21 additions & 0 deletions python/django/manage.py
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()
Loading