From d6e5b3575bcec994e5b36268a33efe5b04bdac94 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Thu, 13 Aug 2015 17:45:27 +0100 Subject: [PATCH 1/3] Add basic serializers, viewsets and routers for djangorestframwork --- feedreader/api.py | 36 +++++++++++++ feedreader/serializers.py | 89 ++++++++++++++++++++++++++++++++ feedreader/test_serializers.py | 93 ++++++++++++++++++++++++++++++++++ feedreader/urls.py | 22 +++++++- 4 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 feedreader/api.py create mode 100644 feedreader/serializers.py create mode 100644 feedreader/test_serializers.py diff --git a/feedreader/api.py b/feedreader/api.py new file mode 100644 index 0000000..3ada275 --- /dev/null +++ b/feedreader/api.py @@ -0,0 +1,36 @@ +from rest_framework import viewsets + +from .models import Entry, Feed, Group, Options +from .serializers import EntrySerializer, FeedSerializer, GroupSerializer, OptionsSerializer + + +class OptionsViewSet(viewsets.ReadOnlyModelViewSet): + """ + This viewset automatically provides `list` and `detail` actions. + """ + queryset = Options.objects.all() + serializer_class = OptionsSerializer + + +class GroupViewSet(viewsets.ReadOnlyModelViewSet): + """ + This viewset automatically provides `list` and `detail` actions. + """ + queryset = Group.objects.all() + serializer_class = GroupSerializer + + +class FeedViewSet(viewsets.ReadOnlyModelViewSet): + """ + This viewset automatically provides `list` and `detail` actions. + """ + queryset = Feed.objects.all() + serializer_class = FeedSerializer + + +class EntryViewSet(viewsets.ReadOnlyModelViewSet): + """ + This viewset automatically provides `list` and `detail` actions. + """ + queryset = Entry.objects.all() + serializer_class = EntrySerializer \ No newline at end of file diff --git a/feedreader/serializers.py b/feedreader/serializers.py new file mode 100644 index 0000000..144024c --- /dev/null +++ b/feedreader/serializers.py @@ -0,0 +1,89 @@ +from __future__ import absolute_import +from rest_framework import serializers + +from .models import Entry, Feed, Group, Options + + +class OptionsSerializer(serializers.ModelSerializer): + """ + Options controlling feedreader behavior + + :Fields: + + number_initially_displayed : integer + Number of entries, from all feeds, initially displayed on webpage. + number_additionally_displayed : integer + Number of entries added to displayed results when scrolling down. + max_entries_saved : integer + Maximum number of entries to store for each feed. + """ + + class Meta: + model = Options + + +class GroupSerializer(serializers.ModelSerializer): + """ + Group of feeds. + + :Fields: + + name : char + Name of group. + num_unread_entries: int + """ + + class Meta: + model = Group + + +class FeedSerializer(serializers.ModelSerializer): + """ + Feed information. + + :Fields: + + title : char + Title of feed. + xml_url : char + URL of xml feed. + link : char + URL of feed site. + description : text + Description of feed. + published_time : date_time + When feed was last updated. + last_polled_time : date_time + When feed was last polled. + group : ForeignKey + Group this feed is a part of. + num_unread_entries + """ + + class Meta: + model = Feed + + +class EntrySerializer(serializers.ModelSerializer): + """ + Feed entry information. + + :Fields: + + feed : ForeignKey + Feed this entry is a part of. + title : char + Title of entry. + link : char + URL of entry. + description : text + Description of entry. + published_time : date_time + When entry was last updated. + read_flag: boolean + Has the entry been read? + """ + + class Meta: + model = Entry + diff --git a/feedreader/test_serializers.py b/feedreader/test_serializers.py new file mode 100644 index 0000000..728e477 --- /dev/null +++ b/feedreader/test_serializers.py @@ -0,0 +1,93 @@ +"""Feedreader Models Unit Test.""" +from __future__ import absolute_import + +from django.test import TestCase + +from .models import Entry, Feed, Group, Options +from .serializers import EntrySerializer, FeedSerializer, GroupSerializer, OptionsSerializer +from .simple_test_server import (PORT, setUpModule as server_setup, + tearDownModule as server_teardown) + + +def setUpModule(): + server_setup() + + +def tearDownModule(): + server_teardown() + + +class OptionsTest(TestCase): + """ + Create and access Options. + """ + + def setUp(self): + self.options = Options.manager.get_options() + + def test_options_unicode(self): + """Retrieve Options object's unicode string.""" + options_unicode = self.options.__unicode__() + self.assertEqual(options_unicode, + 'Options', + 'Options: Unexpected __unicode__ value: Got %s expected "Options"' % + (options_unicode)) + + +class GroupTest(TestCase): + """ + Create and access Group. + """ + + def setUp(self): + self.group = Group.objects.create(name='Test Group') + self.group_serializer = GroupSerializer(self.group) + + def test_group_unicode(self): + """Retrieve Group object's unicode string.""" + group_unicode = self.group.__unicode__() + self.assertEqual(group_unicode, + 'Test Group', + 'Group: Unexpected __unicode__ value: Got %s expected "Test Group"' % + (group_unicode)) + + +class FeedTest(TestCase): + """ + Create and access Feed. + """ + + def setUp(self): + self.feed = Feed.objects.create(xml_url='http://localhost:%s/test/feed' % (PORT)) + self.feed.title = 'Test Feed' + self.feed.save() + self.feed_serializer = FeedSerializer(self.feed) + + def test_feed_unicode(self): + """Retrieve Feed object's unicode string.""" + feed_unicode = self.feed.__unicode__() + self.assertEqual(feed_unicode, + 'Test Feed', + 'Feed: Unexpected __unicode__ value: Got %s expected "Test Feed"' % + (feed_unicode)) + + +class EntryTest(TestCase): + """ + Create and access Entry. + """ + + def setUp(self): + self.feed = Feed.objects.create(xml_url='http://localhost:%s/test/feed' % (PORT)) + self.entry = Entry.objects.create(feed=self.feed, + title='Test Entry', + link='http://example.com/test') + self.entry_serializer = EntrySerializer(self.entry) + + def test_entry_unicode(self): + """Retrieve Entry object's unicode string.""" + entry_unicode = self.entry.__unicode__() + self.assertEqual(entry_unicode, + 'Test Entry', + 'Entry: Unexpected __unicode__ value: Got %s expected "Test Entry"' % + (entry_unicode)) diff --git a/feedreader/urls.py b/feedreader/urls.py index ddd0ec8..e80ee7d 100644 --- a/feedreader/urls.py +++ b/feedreader/urls.py @@ -1,6 +1,7 @@ from __future__ import absolute_import -from django.conf.urls import patterns, url +from django.conf import settings +from django.conf.urls import patterns, url, include from .views import (FeedList, Search, EntryList, NumbersUnread, MarkEntryRead, @@ -32,3 +33,22 @@ view=UpdateItem.as_view(), name='update_item'), ) + +if 'rest_framework' in settings.INSTALLED_APPS: + print('Loading REST extensions for django-feedreader') + from rest_framework.routers import DefaultRouter + from .api import EntryViewSet, FeedViewSet, GroupViewSet, OptionsViewSet + + + # Create a router and register our ViewSets with it. + router = DefaultRouter() + router.register(r'options', OptionsViewSet) + router.register(r'group', GroupViewSet) + router.register(r'feed', FeedViewSet) + router.register(r'entry', EntryViewSet) + + # The API URLs are now determined automatically by the router. + # Additionally, we include the login URLs for the browsable API. + urlpatterns += [ + url(r'^api/', include(router.urls)), + ] From 109c31899a4ed3604c6a8f66e2e236798f81b953 Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Thu, 13 Aug 2015 17:46:50 +0100 Subject: [PATCH 2/3] Add example project --- .gitignore | 1 + example/.gitignore | 1 + example/example/__init__.py | 0 example/example/settings.py | 109 ++++++++++++++++++++++++++++++++++++ example/example/urls.py | 23 ++++++++ example/example/wsgi.py | 16 ++++++ example/manage.py | 10 ++++ example/requirements.txt | 2 + 8 files changed, 162 insertions(+) create mode 100644 example/.gitignore create mode 100644 example/example/__init__.py create mode 100644 example/example/settings.py create mode 100644 example/example/urls.py create mode 100644 example/example/wsgi.py create mode 100755 example/manage.py create mode 100644 example/requirements.txt diff --git a/.gitignore b/.gitignore index 9482752..b26c62e 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,4 @@ tramp Thumbs.db Desktop.ini +env* diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..6061583 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1 @@ +*.sqlite3 diff --git a/example/example/__init__.py b/example/example/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/example/example/settings.py b/example/example/settings.py new file mode 100644 index 0000000..3cb0027 --- /dev/null +++ b/example/example/settings.py @@ -0,0 +1,109 @@ +""" +Django settings for example project. + +Generated by 'django-admin startproject' using Django 1.8.3. + +For more information on this file, see +https://docs.djangoproject.com/en/1.8/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.8/ref/settings/ +""" + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +import os + +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.8/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'rozpjhivw(nj_3@zp*c6$5zlf=%x+zug6uju8eceqo$hj81+m%' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + +# Account stuff +ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value. +REGISTRATION_AUTO_LOGIN = True # Automatically log the user in. + +# Application definition + +INSTALLED_APPS = ( + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + # 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'registration', + 'feedreader', + 'rest_framework' +) + +MIDDLEWARE_CLASSES = ( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'django.middleware.security.SecurityMiddleware', +) + +ROOT_URLCONF = 'example.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 = 'example.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.8/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Internationalization +# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/example/example/urls.py b/example/example/urls.py new file mode 100644 index 0000000..626cf01 --- /dev/null +++ b/example/example/urls.py @@ -0,0 +1,23 @@ +"""example URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls + 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) +""" +from django.conf.urls import include, url +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', include(admin.site.urls)), + url(r'^accounts/', include('registration.backends.default.urls')), + url(r'^feedreader/', include('feedreader.urls', namespace='feedreader')), +] diff --git a/example/example/wsgi.py b/example/example/wsgi.py new file mode 100644 index 0000000..986d3c1 --- /dev/null +++ b/example/example/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for example 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.8/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") + +application = get_wsgi_application() diff --git a/example/manage.py b/example/manage.py new file mode 100755 index 0000000..2605e37 --- /dev/null +++ b/example/manage.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") + + from django.core.management import execute_from_command_line + + execute_from_command_line(sys.argv) diff --git a/example/requirements.txt b/example/requirements.txt new file mode 100644 index 0000000..0371baa --- /dev/null +++ b/example/requirements.txt @@ -0,0 +1,2 @@ +django-registration-redux==1.2 +djangorestframework==3.2.2 From 6b7e98df8d28922dad57e6706f691a8e5fdb2b8b Mon Sep 17 00:00:00 2001 From: Chris Franklin Date: Thu, 13 Aug 2015 17:50:22 +0100 Subject: [PATCH 3/3] Add djangorestframework requirement to README --- README.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/README.rst b/README.rst index c8d6505..721a122 100644 --- a/README.rst +++ b/README.rst @@ -44,6 +44,7 @@ Dependencies ------------ - `Django 1.8 `__ +- `djangorestframework 3.2.2 `__ - `django-braces 1.4.0 `__ - `factory_boy 2.5.1 `__ - `feedparser 5.2.0 `__