Commit ee5a564c authored by Nadrieril's avatar Nadrieril

Improved PEP8 compliance

parent 9155302f
/db.sqlite3
*.pyc
/static
*.pyc
......@@ -24,12 +24,12 @@ class UserManager(BaseUserManager):
user.save(using=self._db)
return user
## User
class User(models.Model): # cannot inherit from AbstractBaseUser, need to override password field
# User
class User(models.Model): # cannot inherit from AbstractBaseUser, need to override password field
username = models.CharField(max_length=128, unique=True)
password = models.CharField(max_length=128, unique=True)
full_name = models.CharField(max_length=128, blank = True)
pseudo = models.CharField(max_length=128, blank = True)
full_name = models.CharField(max_length=128, blank=True)
pseudo = models.CharField(max_length=128, blank=True)
last_login = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
......
......@@ -8,7 +8,7 @@ from bars_api.auth import User
from bars_api import VirtualField
## Bar
# Bar
class Bar(models.Model):
id = models.CharField(max_length=50, primary_key=True)
name = models.CharField(max_length=100)
......@@ -17,12 +17,14 @@ class Bar(models.Model):
def __unicode__(self):
return self.id
class BarSerializer(serializers.ModelSerializer):
class Meta:
model = Bar
_type = VirtualField("Bar")
## Account
# Account
class Account(models.Model):
class Meta:
unique_together = (("bar", "owner"))
......@@ -32,13 +34,15 @@ class Account(models.Model):
last_modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.owner.name + " ("+self.bar.id+")"
return self.owner.name + " (" + self.bar.id + ")"
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
_type = VirtualField("Account")
class AccountViewSet(viewsets.ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
......@@ -49,31 +53,34 @@ class AccountViewSet(viewsets.ModelViewSet):
serializer = self.serializer_class(request.user.account_set.get(bar=Bar.objects.all()[0]))
return Response(serializer.data)
## Item
# Item
class Item(models.Model):
bar = models.ForeignKey(Bar)
name = models.CharField(max_length=100)
keywords = models.CharField(max_length=200) # Todo: length
keywords = models.CharField(max_length=200) # Todo: length
qty = models.DecimalField(max_digits=7, decimal_places=3)
price = models.DecimalField(max_digits=7, decimal_places=3)
deleted = models.BooleanField(default = False)
deleted = models.BooleanField(default=False)
last_modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
_type = VirtualField("Item")
## Transaction
# Transaction
class Transaction(models.Model):
bar = models.ForeignKey(Bar)
author = models.ForeignKey(User)
type = models.CharField(max_length=25)
timestamp = models.DateTimeField(auto_now_add=True)
canceled = models.BooleanField(default = False)
canceled = models.BooleanField(default=False)
last_modified = models.DateTimeField(auto_now=True)
# def clean(self):
......@@ -116,13 +123,13 @@ class AccountOperation(models.Model):
account = models.ForeignKey(Account)
delta = models.DecimalField(max_digits=7, decimal_places=3)
class ItemOperation(models.Model):
transaction = models.ForeignKey(Transaction)
item = models.ForeignKey(Item)
delta = models.DecimalField(max_digits=7, decimal_places=3)
class BaseTransactionSerializer(serializers.ModelSerializer):
class Meta:
model = Transaction
......@@ -130,17 +137,16 @@ class BaseTransactionSerializer(serializers.ModelSerializer):
def to_native(self, transaction):
fields = self.fields
self.fields = {k:v for k,v in self.fields.items() if k in ('id', 'bar', 'author', 'type', 'timestamp', 'last_modified', 'canceled')}
self.fields = {k: v for k, v in self.fields.items() if k in ('id', 'bar', 'author', 'type', 'timestamp', 'last_modified', 'canceled')}
obj = super(BaseTransactionSerializer, self).to_native(transaction)
self.fields = fields
return obj
def restore_object(self, attrs, instance=None):
t = super(BaseTransactionSerializer, self).restore_object(attrs, instance)
# Todo: add correct author/bar
t.author = User.objects.all()[0] # self.context['request'].user
t.bar = Bar.objects.all()[0] # self.context['request'].bar
t.author = User.objects.all()[0] # self.context['request'].user
t.bar = Bar.objects.all()[0] # self.context['request'].bar
return t
# def to_native(self, transaction):
......@@ -200,7 +206,6 @@ class BaseTransactionSerializer(serializers.ModelSerializer):
# return False
class BuyTransactionSerializer(BaseTransactionSerializer):
item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
qty = serializers.DecimalField(max_digits=7, decimal_places=3)
......@@ -213,11 +218,12 @@ class BuyTransactionSerializer(BaseTransactionSerializer):
delta=-t.qty)
t.accountoperation_set.create(
account=Account.objects.get(owner=t.author, bar=t.bar),
delta=-t.qty*t.item.price)
delta=-t.qty * t.item.price)
def to_native(self, transaction):
obj = super(BuyTransactionSerializer, self).to_native(transaction)
if transaction is None: return obj
if transaction is None:
return obj
try:
error = serializers.ValidationError("")
......@@ -245,7 +251,6 @@ class BuyTransactionSerializer(BaseTransactionSerializer):
return obj
class GiveTransactionSerializer(BaseTransactionSerializer):
account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all())
amount = serializers.DecimalField(max_digits=7, decimal_places=3)
......@@ -262,7 +267,8 @@ class GiveTransactionSerializer(BaseTransactionSerializer):
def to_native(self, transaction):
obj = super(GiveTransactionSerializer, self).to_native(transaction)
if transaction is None: return obj
if transaction is None:
return obj
try:
error = serializers.ValidationError("")
......@@ -291,7 +297,6 @@ class GiveTransactionSerializer(BaseTransactionSerializer):
return obj
class TransactionSerializer(serializers.Serializer):
serializers_class_map = {
"": BaseTransactionSerializer,
......@@ -345,7 +350,7 @@ class TransactionViewSet(viewsets.ModelViewSet):
@decorators.detail_route(methods=['post'])
def cancel(self, request, pk=None):
transaction = Transaction.objects.get(pk=pk)
transaction.canceled = True;
transaction.canceled = True
transaction.save()
serializer = self.serializer_class(transaction)
return Response(serializer.data)
......@@ -353,7 +358,7 @@ class TransactionViewSet(viewsets.ModelViewSet):
@decorators.detail_route(methods=['post'])
def restore(self, request, pk=None):
transaction = Transaction.objects.get(pk=pk)
transaction.canceled = False;
transaction.canceled = False
transaction.save()
serializer = self.serializer_class(transaction)
return Response(serializer.data)
......@@ -92,7 +92,7 @@ AUTHENTICATION_BACKENDS = ('bars_api.auth.AuthenticationBackend',)
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=7*24), ## Todo: temporary
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=7*24), # Todo: temporary
}
# CORS headers
......@@ -103,4 +103,3 @@ CORS_ORIGIN_ALLOW_ALL = True
# API app
AUTH_USER_MODEL = 'bars_api.User'
......@@ -4,31 +4,33 @@ from django.contrib import admin
admin.autodiscover()
from rest_framework import viewsets, routers, mixins, status
from rest_framework import viewsets, routers, mixins
# Todo: organize imports
from bars_api.models import *
from bars_api.auth import *
router = routers.DefaultRouter()
for (name, x) in {
# 'user': (User, UserSerializer),
'bar': (Bar, BarSerializer),
# 'account': (Account, AccountSerializer),
'item': (Item, ItemSerializer),
# 'transaction': (Transaction, TransactionSerializer)
}.items():
router.register(name,
type("ViewSet", (viewsets.ModelViewSet,),
{
"queryset": x[0].objects.all(),
"serializer_class": x[1]
}))
# 'user': (User, UserSerializer),
'bar': (Bar, BarSerializer),
# 'account': (Account, AccountSerializer),
'item': (Item, ItemSerializer),
# 'transaction': (Transaction, TransactionSerializer)
}.items():
router.register(
name,
type("ViewSet", (viewsets.ModelViewSet,),
{
"queryset": x[0].objects.all(),
"serializer_class": x[1]
}))
router.register('user', UserViewSet)
router.register('account', AccountViewSet)
router.register('transaction', TransactionViewSet)
urlpatterns = patterns('',
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
......
......@@ -8,7 +8,7 @@ https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))));
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bars_django.settings.dev_local")
from django.core.wsgi import get_wsgi_application
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment