Skip to content

Assignment 4

Dan Carr edited this page Mar 6, 2017 · 1 revision

Assignment 4 - DRF Fun

Prerequisites

  • Student has Github account
  • Student has Docker installed.
  • Adequate bandwidth. This is not a cafe exercise.
  • Student has completed Assignment 3

Concepts Introduced

  • Git branching best practices
  • Docker Containers
  • Implement Django Rest Framework API

Step 0 - Create GitHub Repo and Check in

Create a git repo on github replacing {{githubuser}} with your github user name using the github API:

curl -u {{githubuser}} https://api.github.com/user/repos -d '{ "name": "fooproject" }'

When prompted, enter your github password.

Initialize the repository on your local machine:

git init

Add project files to git and make your first commit:

git add .

git commit -m 'first commit'

Add the github remote and push your project to github

git remote add origin https://github.com/{{githubusername}}/fooproject.git

git push origin master

Create a new branch for the next Assignment. Important Concept. Main is always deployable.

git checkout -b assign4

Step 1 - Create the user app

docker-compose run web python manage.py startapp user

Step 2 - Add DRF to the project settings

Create the file: /fooapi/foo_api_settings.py with the following contents:

from django.conf import settings
import os

## connect to the linked docker postgres db
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

## we extend INSTALLED_APPS here.
## Any apps you want to install you can
## just add here (or use app.py)
settings.INSTALLED_APPS.extend([
	'rest_framework',
  'user',
])

## Rest framework settings
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

## We set the static root to the mapped volume /code
## When you run docker-compose run web python manage.py collectstatic
## You will notice that it creates a `static` directory in the
## root folder of the project
STATIC_ROOT = '/code/static/'

Make sure that Django uses our foo_api_settings. Add the following at the end of thefooapi/settings.py file:

from fooapi.foo_api_settings import *

Step 3 - Add the API views

We will expose Django's User object in our API, so add the following to your user/views.py file:

from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

Step 4 - Add our API to urls

Add our API to fooapi/urls.py so that we can access the API:

# you'll need to add the include import
from django.conf.urls import url, include
from django.contrib import admin

# here we import the router from our views.py
# the router handles all url mapping for our app
from user.views import router

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    # This includes all our registered ViewSets
    url(r'^', include(router.urls)),

    # This provides the ability to login to the app
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

]

## Setting up static files for development:
if settings.DEBUG == True:
  urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Step 6 - Run the migrations to for user

We need to run the migrations for our new user view

docker-compose run web python manage.py migrate auth

Step 6 - View the API

Start up the server to see the DRF browsable API:

docker-compose up

Check to see that your Django DRF user API is up:

  • Docker Native: http://localhost:8000
  • Docker Toolbox: run docker-machine ip to get the ip of your docker/vm instance and then [http://{{replace with ip from docker-machine ip command }}:8000](http://{{replace with ip from docker-machine ip command}}:8000)

Step 7 - Commit and Merge

If everything is working ok, then it's time to commit to our Assign4 development branch.

git add .

git commit -m 'Assignment 4 Complete'

`git push origin assign4'

Important Note: This is the point where automation will take over in a future assignment. Stay tuned.

Clone this wiki locally