Django - Write an app

From XennisWiki
Jump to: navigation, search

This article gives some hints how to write a Django app.

Tutorial - Basics

See Django documentation with includes a really good tutorials for beginners.

Logging

Further information: Django documentation - Logging

Add to MYAPP/settings.py (log into file and console)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        }, 
    },
    'loggers': {
        'MYAPP': {
            'formatter': 'verbose',
            'handlers': ['file', 'console'],
            'level': 'DEBUG'
        },
    },
}

Use logger

import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)

logger.debug('Debug!')
logger.error('Error!')

Providing initial data

Further information: Providing initial data for models

Create a file sampleData.json, which looks for instance like this:

[
{
    "model": "myApp.location", 
    "pk": 1,
    "fields": {
        "latitude": 43.0,
        "longitude": 32.0, 
        "altitude": 100.0
        "updated": "2014-11-30T17:20:59.763Z", 
        "created": "2014-11-30T17:20:59.762Z"
    }
},
{
    "model": "myApp.location", 
    "pk": 2,
    "fields": {
        "latitude": -24.0,
        "longitude": 23.0, 
        "altitude": 321.0,
        "created": "2014-11-30T17:25:05.761Z", 
        "updated": "2014-11-30T17:25:05.761Z"
    }
}
]

You can load the data by using the command python manage.py loaddata <FILE-NAME> [--format=xml|yaml]. Also you can create such a JSON file with the current data by python manage.py dumpdata --indent 4 >> <FILE-NAME>.

If you name the file initial_data.json (also .xml and .yaml possible) the data gets loaded automatically when execution syncdb or a migration.

Admin site

Further information: Django documentation - The Django admin site

MYAPP/settings.py

# Application definition

INSTALLED_APPS = (
    # ... other stuff

    'django.contrib.admin',
    # admin dependencies:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
)

MIDDLEWARE_CLASSES = (
    # ... other stuff

    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

MYAPP/urls.py

# ... other stuff
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    # ... other stuff
    url(r'^admin/', include(admin.site.urls)),
)

MYAPP/admin.py (example only: in MYAPP/models.py the class User is defined)

from django.contrib import admin
from MYAPP.models import User

admin.site.register(User)

Create cron jobs using django-cron

Further information: django-cron, GitHub - django-cron

Installation

Using pip to install it: pip install django-cron

Simple example

The cron job in this examples deletes each 10 minutes old messages.

MYAPP/settings.py

INSTALLED_APPS = (
    # ... other stuff
    'django_cron',
)

CRON_CLASSES = [
    "MYAPP.chronjob.DeleteOldMessages",
]

MYAPP/chronjob.py (example only: in MYAPP/models.py the class Massage is defined)

from django_cron import CronJobBase, Schedule
from MYAPP.models import Message
from datetime import datetime
from django.utils.timezone import utc

class DeleteOldMessages(CronJobBase):

    RUN_EVERY_MINS = 10
    RETRY_AFTER_FAILURE_MINS = 1

    schedule = Schedule(run_every_mins=RUN_EVERY_MINS,  retry_after_failure_mins=RETRY_AFTER_FAILURE_MINS)
    code = 'MYAPP.DeleteOldMessages'    # a unique code

    def do(self):
    	now_utc = datetime.utcnow().replace(tzinfo=utc)
    	Message.objects.filter(expires__range=["2011-01-01", now_utc]).delete()

Create REST API using Tastypie (django-tastypie)

Tastypie is an API framework for creating REST APIs. A good alternative is the Django REST framework.

Installation

Further information: Getting Started with Tastypie

Use pip to install Tastypie: pip install django-tastypie

Simple example

Further information: Getting Started with Tastypie, Create a Super Basic REST API with django-tastypie

Add to your MYAPP/settings.py

INSTALLED_APPS = (
    # ... other stuff
    'tastypie',
)

#SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
#TASTYPIE_DEFAULT_FORMATS = ['json']

Add to your MYAPP/urls.py

from django_sample_server.api import UserResource, MessageResource
from tastypie.api import Api

api = Api(api_name='v1')
api.register(UserResource())
api.register(MessageResource())

urlpatterns = patterns('',
    # ... other stuff
    # Tastypie API
    url(r'^api/', include(api.urls)),
}

MYAPP/api.py (example only: in MYAPP/models.py the class User is defined)

from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from MYAPP.models import User

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        fields = ['username', 'first_name', 'last_name', 'last_login']
        allowed_methods = ['get']

Now go to http://localhost:8000/api/v1/user/.

Authorization with OAuth 2 (django-oauth2-provider)

Further information: Building a True OAuth 2.0 API with Django and Tasty Pie, [http://django-tastypie.readthedocs.org/en/latest/cookbook.html Tastypie Cookbook - Creating a Full OAuth 2.0 API]

Setup

Install OAuth 2 using pip: pip install django-oauth2-provider

Add authentication.py to your MYAPP/ folder.

Simple example

Add to your MYAPP/settings.py

INSTALLED_APPS = (
    # ... other stuff
    'provider',
    'provider.oauth2',
)

MIDDLEWARE_CLASSES = (
    # ... other stuff
    #'MYAPP.django-crossdomainxhr-middleware.XsSharing',
)

Add to your MYAPP/urls.py

urlpatterns = patterns('',
    # ... other stuff
    # Oauth2
    url(r'^oauth2/', include('provider.oauth2.urls', namespace = 'oauth2')),
}

MYAPP/api.py (example only: in MYAPP/models.py the class User is defined)

# ... other stuff
from tastypie.authorization import DjangoAuthorization
from authentication import OAuth20Authentication

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        # ... other stuff
        authorization = DjangoAuthorization()
        authentication = OAuth20Authentication()

Documentation with Swagger (django-tastypie-swagger)

Further information: django-tastypie-swagger

Setup

Install Tastypie Swagger using pip: pip install django-tastypie-swagger

Add to your MYAPP/settings.py

INSTALLED_APPS = (
    # ... other stuff
    'tastypie_swagger',
)

TASTYPIE_SWAGGER_API_MODULE = 'MYAPP.urls.api'

Add to your MYAPP/urls.py

urlpatterns = patterns('',
    # ... other stuff
    # Tastypie Swagger
    url(r'api/doc/', include('tastypie_swagger.urls', namespace='tastypie_swagger')),
}

Open documentation: http://localhost:8000/api/doc/

See also

External links