Skip to content

Commit

Permalink
Added example with Django ORM
Browse files Browse the repository at this point in the history
  • Loading branch information
Relrin committed Nov 1, 2016
1 parent cecd7c1 commit 379199b
Show file tree
Hide file tree
Showing 13 changed files with 349 additions and 1 deletion.
1 change: 1 addition & 0 deletions examples/django_orm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# -*- coding: utf-8 -*-
111 changes: 111 additions & 0 deletions examples/django_orm/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# -*- coding: utf-8 -*-
import asyncio
import json

from hashlib import sha256
from autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory


def hash_password(password):
return sha256(password.encode('utf-8')).hexdigest()


class HelloClientProtocol(WebSocketClientProtocol):

def onOpen(self):
# Create new manufacturer
request = {
'method': 'POST',
'url': '/manufacturer/',
'event_name': 'create-manufacturer',
'args': {
"name": 'Ford'
}
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Get information about Audi
request = {
'method': 'GET',
'url': '/manufacturer/Audi/',
'event_name': 'get-manufacturer-detail'
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Get cars list
request = {
'method': 'GET',
'url': '/cars/',
'event_name': 'get-cars-list'
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Create new car
request = {
'method': 'POST',
'url': '/cars/',
'event_name': 'create-car',
'args': {
'name': 'M5',
'manufacturer': 2
}
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Trying to create new car with same info, but we have taken an error
self.sendMessage(json.dumps(request).encode('utf8'))

# # Update existing object
request = {
'method': 'PUT',
'url': '/cars/Q5/',
'event_name': 'partial-update-car',
'args': {
'name': 'Q7'
}
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Get the list of manufacturers
request = {
'method': 'GET',
'url': '/manufacturer/',
'event_name': 'get-manufacturer-list',
'args': {}
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Update manufacturer
request = {
'method': 'PUT',
'url': '/manufacturer/Audi/',
'event_name': 'update-manufacturer',
'args': {
'name': 'Not Audi'
}
}
self.sendMessage(json.dumps(request).encode('utf8'))

# Get car by name
request = {
'method': 'GET',
'url': '/cars/TT/',
'event_name': 'get-car-detail',
'args': {}
}
self.sendMessage(json.dumps(request).encode('utf8'))

def onMessage(self, payload, isBinary):
print("Result: {0}".format(payload.decode('utf8')))


if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
factory.protocol = HelloClientProtocol

loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, '127.0.0.1', 8080)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
1 change: 1 addition & 0 deletions examples/django_orm/server/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# -*- coding: utf-8 -*-
17 changes: 17 additions & 0 deletions examples/django_orm/server/app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
import sys
from os import path

from django import setup as django_setup
from django.conf import settings as django_settings

from aiorest_ws.conf import settings


sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..')))
django_settings.configure(
DATABASES=settings.DATABASES,
INSTALLED_APPS=settings.INSTALLED_APPS
)
django_setup()

23 changes: 23 additions & 0 deletions examples/django_orm/server/app/db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from django.db import models


class Manufacturer(models.Model):
name = models.CharField(max_length=30)

class Meta:
app_label = 'django_orm_example'

def __str__(self):
return '<Manufacturer(%d: %s)>' % (self.id, self.name)


class Car(models.Model):
name = models.CharField(max_length=30, unique=True)
manufacturer = models.ForeignKey(Manufacturer, related_name='cars')

class Meta:
app_label = 'django_orm_example'

def __str__(self):
return '<Car(%d: %s, %s)>' % (self.id, self.name, self.manufacturer)
16 changes: 16 additions & 0 deletions examples/django_orm/server/app/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# -*- coding: utf-8 -*-
from aiorest_ws.db.orm.django import serializers

from app.db import Manufacturer, Car


class ManufacturerSerializer(serializers.ModelSerializer):

class Meta:
model = Manufacturer


class CarSerializer(serializers.ModelSerializer):

class Meta:
model = Car
14 changes: 14 additions & 0 deletions examples/django_orm/server/app/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from aiorest_ws.routers import SimpleRouter

from app.views import ManufacturerListView, ManufacturerView, CarListView, \
CarView


router = SimpleRouter()
router.register('/manufacturer/{name}', ManufacturerView, ['GET', 'PUT'],
name='manufacturer-detail')
router.register('/manufacturer/', ManufacturerListView, ['POST'])
router.register('/cars/{name}', CarView, ['GET', 'PUT'],
name='car-detail')
router.register('/cars/', CarListView, ['POST'])
98 changes: 98 additions & 0 deletions examples/django_orm/server/app/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-
from aiorest_ws.db.orm.exceptions import ValidationError
from aiorest_ws.views import MethodBasedView

from django.core.exceptions import ObjectDoesNotExist

from app.db import Manufacturer, Car
from app.serializers import ManufacturerSerializer, CarSerializer


class ManufacturerListView(MethodBasedView):

def get(self, request, *args, **kwargs):
instances = Manufacturer.objects.all()
serializer = ManufacturerSerializer(instances, many=True)
return serializer.data

def post(self, request, *args, **kwargs):
data = kwargs.get('params', None)
if not data:
raise ValidationError('You must provide arguments for create.')

serializer = ManufacturerSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return serializer.data


class ManufacturerView(MethodBasedView):

def get_manufacturer(self, name):
try:
manufacturer = Manufacturer.objects.get(name__iexact=name)
except ObjectDoesNotExist:
raise ValidationError("The requested object does not exist")

return manufacturer

def get(self, request, name, *args, **kwargs):
manufacturer = self.get_manufacturer(name)
serializer = ManufacturerSerializer(manufacturer)
return serializer.data

def put(self, request, name, *args, **kwargs):
data = kwargs.get('params', None)
if not data:
raise ValidationError('You must provide arguments for create.')

instance = self.get_manufacturer(name)
serializer = ManufacturerSerializer(instance, data=data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return serializer.data


class CarListView(MethodBasedView):

def get(self, request, *args, **kwargs):
data = Car.objects.all()
serializer = CarSerializer(data, many=True)
return serializer.data

def post(self, request, *args, **kwargs):
data = kwargs.get('params', None)
if not data:
raise ValidationError('You must provide arguments for create.')

serializer = CarSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return serializer.data


class CarView(MethodBasedView):

def get_car(self, name):
try:
car = Car.objects.get(name__iexact=name)
except ObjectDoesNotExist:
raise ValidationError("The requested object does not exist")

return car

def get(self, request, name, *args, **kwargs):
instance = self.get_car(name)
serializer = CarSerializer(instance)
return serializer.data

def put(self, request, name, *args, **kwargs):
data = kwargs.get('params', None)
if not data:
raise ValidationError('You must provide data for update.')

instance = self.get_car(name)
serializer = CarSerializer(instance, data=data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return serializer.data
25 changes: 25 additions & 0 deletions examples/django_orm/server/create_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from app.db import Manufacturer, Car

from django.db import connections


if __name__ == '__main__':
# Create tables in memory
conn = connections['default']
with conn.schema_editor() as editor:
editor.create_model(Manufacturer)
editor.create_model(Car)

# Initialize the database
data = {
'Audi': ['A8', 'Q5', 'TT'],
'BMW': ['M3', 'i8'],
'Mercedes-Benz': ['C43 AMG W202', 'C450 AMG 4MATIC']
}

for name, models in data.items():
manufacturer = Manufacturer.objects.create(name=name)

for model in models:
Car.objects.create(name=model, manufacturer=manufacturer)
13 changes: 13 additions & 0 deletions examples/django_orm/server/run_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
import os


def get_module_content(filename):
with open(filename, 'r') as module:
return module.read()


if __name__ == __name__:
os.environ.setdefault("AIORESTWS_SETTINGS_MODULE", "settings")
exec(get_module_content('./create_db.py'))
exec(get_module_content('./server.py'))
19 changes: 19 additions & 0 deletions examples/django_orm/server/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from aiorest_ws.app import Application
from aiorest_ws.command_line import CommandLine
from aiorest_ws.routers import SimpleRouter

from app.urls import router

main_router = SimpleRouter()
main_router.include(router)


if __name__ == '__main__':
cmd = CommandLine()
cmd.define('-ip', default='127.0.0.1', help='used ip', type=str)
cmd.define('-port', default=8080, help='listened port', type=int)
args = cmd.parse_command_line()

app = Application()
app.run(host=args.ip, port=args.port, router=main_router)
10 changes: 10 additions & 0 deletions examples/django_orm/server/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-

USE_ORM_ENGINE = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = ("app", )
2 changes: 1 addition & 1 deletion examples/sqlalchemy_orm/server/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def post(self, *args, **kwargs):
if not data:
raise ValidationError('You must provide arguments for create.')

created_obj_data = data.get('list' , [])
created_obj_data = data.get('list', [])
if not data:
raise ValidationError('You must provide a list of objects.')

Expand Down

0 comments on commit 379199b

Please sign in to comment.