Skip to content

Commit

Permalink
by Packt
Browse files Browse the repository at this point in the history
Code bundle
  • Loading branch information
anushreet committed Oct 25, 2016
1 parent b1590c9 commit c0f5f70
Show file tree
Hide file tree
Showing 671 changed files with 23,286 additions and 0 deletions.
Binary file not shown.
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.contrib import admin

# Register your models here.
11 changes: 11 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/games/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.apps import AppConfig


class GamesConfig(AppConfig):
name = 'games'
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-27 01:47
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Game',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('name', models.CharField(blank=True, default='', max_length=200)),
('release_date', models.DateTimeField()),
('game_category', models.CharField(blank=True, default='', max_length=200)),
('played', models.BooleanField(default=False)),
],
options={
'ordering': ('name',),
},
),
]
Empty file.
Binary file not shown.
Binary file not shown.
18 changes: 18 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/games/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.db import models


class Game(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200, blank=True, default='')
release_date = models.DateTimeField()
game_category = models.CharField(max_length=200, blank=True, default='')
played = models.BooleanField(default=False)

class Meta:
ordering = ('name',)
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from rest_framework import serializers
from games.models import Game


class GameSerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=200)
release_date = serializers.DateTimeField()
game_category = serializers.CharField(max_length=200)
played = serializers.BooleanField(required=False)

def create(self, validated_data):
return Game.objects.create(**validated_data)

def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.release_date = validated_data.get('release_date', instance.release_date)
instance.game_category = validated_data.get('game_category', instance.game_category)
instance.played = validated_data.get('played', instance.played)
instance.save()
return instance
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.test import TestCase

# Create your tests here.
13 changes: 13 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/games/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.conf.urls import url
from games import views

urlpatterns = [
url(r'^games/$', views.game_list),
url(r'^games/(?P<pk>[0-9]+)/$', views.game_detail),
]
60 changes: 60 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/games/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import status
from games.models import Game
from games.serializers import GameSerializer


class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
def game_list(request):
if request.method == 'GET':
games = Game.objects.all()
games_serializer = GameSerializer(games, many=True)
return JSONResponse(games_serializer.data)

elif request.method == 'POST':
game_data = JSONParser().parse(request)
game_serializer = GameSerializer(data=game_data)
if game_serializer.is_valid():
game_serializer.save()
return JSONResponse(game_serializer.data, status=status.HTTP_201_CREATED)
return JSONResponse(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@csrf_exempt
def game_detail(request, pk):
try:
game = Game.objects.get(pk=pk)
except Game.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)

if request.method == 'GET':
game_serializer = GameSerializer(game)
return JSONResponse(game_serializer.data)

elif request.method == 'PUT':
game_data = JSONParser().parse(request)
game_serializer = GameSerializer(game, data=game_data)
if game_serializer.is_valid():
game_serializer.save()
return JSONResponse(game_serializer.data)
return JSONResponse(game_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

elif request.method == 'DELETE':
game.delete()
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
130 changes: 130 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/gamesapi/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
"""
Django settings for gamesapi project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# 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/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z-dpgdh7nm4_*bg5^4as$_4q#a-ikk_#*jmth-650(9y_p&-et'

# 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',
# Django REST Framework
'rest_framework',
# Games application
'games.apps.GamesConfig',
]

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 = 'gamesapi.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 = 'gamesapi.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/1.10/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/1.10/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/1.10/howto/static-files/

STATIC_URL = '/static/'
26 changes: 26 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/gamesapi/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
"""gamesapi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include

urlpatterns = [
url(r'^', include('games.urls')),
]
16 changes: 16 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/gamesapi/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for gamesapi 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/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gamesapi.settings")

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions Chapter 1/restful_python_chapter_01_01/gamesapi/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gamesapi.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
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?"
)
raise
execute_from_command_line(sys.argv)
Loading

0 comments on commit c0f5f70

Please sign in to comment.