Merge master

This commit is contained in:
Tom Christie 2013-12-09 07:45:45 +00:00
commit 80ef2685e5
20 changed files with 254 additions and 46 deletions

View File

@ -118,7 +118,13 @@ Renders the request data into `JSONP`. The `JSONP` media type provides a mechan
The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
**Note**: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
---
**Warning**: If you require cross-domain AJAX requests, you should almost certainly be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions.
---
**.media_type**: `application/javascript`
@ -419,6 +425,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt
[cors]: http://www.w3.org/TR/cors/
[cors-docs]: ../topics/ajax-csrf-cors.md
[jsonp-security]: http://stackoverflow.com/questions/613962/is-jsonp-safe-to-use
[testing]: testing.md
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

View File

@ -17,6 +17,18 @@ Using bare status codes in your responses isn't recommended. REST framework inc
The full set of HTTP status codes included in the `status` module is listed below.
The module also includes a set of helper functions for testing if a status code is in a given range.
from rest_framework import status
from rest_framework.test import APITestCase
class ExampleTestCase(APITestCase):
def test_url_root(self):
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
and [RFC 6585][rfc6585].
@ -90,6 +102,15 @@ Response status codes beginning with the digit "5" indicate cases in which the s
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
## Helper functions
The following helper functions are available for identifying the category of the response code.
is_informational() # 1xx
is_success() # 2xx
is_redirect() # 3xx
is_client_error() # 4xx
is_server_error() # 5xx
[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

View File

@ -168,5 +168,5 @@ Each of these decorators takes a single argument which must be a list or tuple o
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
[settings]: api-guide/settings.md
[throttling]: api-guide/throttling.md
[settings]: settings.md
[throttling]: throttling.md

View File

@ -170,7 +170,7 @@ The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`,
#### Example
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes, or the `model` attribute shortcut. For example:
class AccountViewSet(viewsets.ModelViewSet):
"""

BIN
docs/img/travis-status.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -100,7 +100,7 @@ Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_
We're ready to create our API now.
Here's our project's root `urls.py` module:
from django.conf.urls.defaults import url, patterns, include
from django.conf.urls import url, patterns, include
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, routers
@ -177,6 +177,7 @@ General guides to using REST framework.
* [Browser enhancements][browser-enhancements]
* [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [Contributing to REST framework][contributing]
* [2.0 Announcement][rest-framework-2-announcement]
* [2.2 Announcement][2.2-announcement]
* [2.3 Announcement][2.3-announcement]

View File

@ -102,6 +102,7 @@
<li><a href="{{ base_url }}/topics/browser-enhancements{{ suffix }}">Browser enhancements</a></li>
<li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li>
<li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
<li><a href="{{ base_url }}/topics/contributing{{ suffix }}">Contributing to REST framework</a></li>
<li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
<li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
<li><a href="{{ base_url }}/topics/2.3-announcement{{ suffix }}">2.3 Announcement</a></li>
@ -171,7 +172,7 @@
<div>
<hr>
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
<p><strong>The team behind REST framework is launching a new API service.</strong></p>
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>

View File

@ -6,19 +6,27 @@
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
# Community
## Community
If you use and enjoy REST framework please consider [staring the project on GitHub][github], and [upvoting it on Django packages][django-packages]. Doing so helps potential new users see that the project is well used, and help us continue to attract new users.
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
You might also consider writing a blog post on your experience with using REST framework, writing a tutorial about using the project with a particular javascript framework, or simply sharing the love on Twitter.
If you use REST framework, we'd love you to be vocal about your experiances with it - you might consider writing a blog post on your experience with using REST framework, or publishing a tutorial about using the project with a particular javascript framework. Experiances from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are and aren't easy to understand and work with.
Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
## Code of conduct
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
# Issues
It's really helpful if you make sure you address issues to the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
Some tips on good issue reporting:
@ -26,30 +34,61 @@ Some tips on good issue reporting:
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
## Triaging issues
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
* TODO: Triage
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
# Development
To start developing on Django REST framework, clone the repo:
* git clone & PYTHONPATH
* Pep8
* Recommend editor that runs pep8
git clone git@github.com:tomchristie/django-rest-framework.git
### Pull requests
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.
* Make pull requests early
* Describe branching
## Testing
### Managing compatibility issues
To run the tests, clone the repository, and then:
* Describe compat module
# Setup the virtual environment
virtualenv env
env/bin/activate
pip install -r requirements.txt
pip install -r optionals.txt
# Testing
# Run the tests
rest_framework/runtests/runtests.py
* Running the tests
* tox
You can also use the excellent `[tox][tox]` testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
tox
## Pull requests
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
GitHub's documentation for working on pull requests is [available here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Once you've made a pull request take a look at the travis build status in the GitHub interface and make sure the tests are runnning as you'd expect.
![Travis status][travis-status]
*Above: Travis build notifications*
## Managing compatibility issues
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
# Documentation
@ -77,7 +116,7 @@ Some other tips:
* Keep paragraphs reasonably short.
* Use double spacing after the end of sentences.
* Don't use the abbreviations such as 'e.g..' but instead use long form, such as 'For example'.
* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
## Markdown style
@ -118,25 +157,19 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
---
**Note:** Make sure you do this thing.
**Note:** A useful documentation note.
---
# Third party packages
* Django reusable app
# Core committers
* Still use pull reqs
* Credits
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
[github]: https://github.com/tomchristie/django-rest-framework
[django-packages]: https://www.djangopackages.com/grids/g/api/
[code-of-conduct]: https://www.djangoproject.com/conduct/
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[so-filter]: http://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
[pep-8]: http://www.python.org/dev/peps/pep-0008/
[travis-status]: ../img/travis-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: http://tox.readthedocs.org/en/latest/
[markdown]: http://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
[mou]: http://mouapp.com/

View File

@ -179,6 +179,8 @@ The following people have helped make REST framework great.
* Yamila Moreno - [yamila-moreno]
* Rob Hudson - [robhudson]
* Alex Good - [alexjg]
* Ian Foote - [ian-foote]
* Chuck Harmston - [chuckharmston]
Many thanks to everyone who's contributed to the project.
@ -394,3 +396,5 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[yamila-moreno]: https://github.com/yamila-moreno
[robhudson]: https://github.com/robhudson
[alexjg]: https://github.com/alexjg
[ian-foote]: https://github.com/ian-foote
[chuckharmston]: https://github.com/chuckharmston

View File

@ -40,9 +40,15 @@ You can determine your currently installed version using `pip freeze`:
## 2.3.x series
### Master
### 2.3.10
**Date**: 6th December 2013
* Add in choices information for ChoiceFields in response to `OPTIONS` requests.
* Added `pre_delete()` and `post_delete()` method hooks.
* Added status code category helper functions.
* Bugfix: Partial updates which erronously set a related field to `None` now correctly fail validation instead of raising an exception.
* Bugfix: Responses without any content no longer include an HTTP `'Content-Type'` header.
* Bugfix: Correctly handle validation errors in PUT-as-create case, responding with 400.
### 2.3.9

View File

@ -1,6 +1,20 @@
__version__ = '2.3.9'
"""
______ _____ _____ _____ __ _
| ___ \ ___/ ___|_ _| / _| | |
| |_/ / |__ \ `--. | | | |_ _ __ __ _ _ __ ___ _____ _____ _ __| | __
| /| __| `--. \ | | | _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
| |\ \| |___/\__/ / | | | | | | | (_| | | | | | | __/\ V V / (_) | | | <
\_| \_\____/\____/ \_/ |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_|
"""
VERSION = __version__ # synonym
__title__ = 'Django REST framework'
__version__ = '2.3.10'
__author__ = 'Tom Christie'
__license__ = 'BSD 2-Clause'
__copyright__ = 'Copyright 2011-2013 Tom Christie'
# Version synonym
VERSION = __version__
# Header encoding (see RFC5987)
HTTP_HEADER_ENCODING = 'iso-8859-1'

View File

@ -514,6 +514,11 @@ class ChoiceField(WritableField):
choices = property(_get_choices, _set_choices)
def metadata(self):
data = super(ChoiceField, self).metadata()
data['choices'] = [{'value': v, 'display_name': n} for v, n in self.choices]
return data
def validate(self, value):
"""
Validates that the input is in self.choices.

View File

@ -61,6 +61,10 @@ class Response(SimpleTemplateResponse):
assert charset, 'renderer returned unicode, and did not specify ' \
'a charset value.'
return bytes(ret.encode(charset))
if not ret:
del self['Content-Type']
return ret
@property

View File

@ -896,7 +896,10 @@ class ModelSerializer(Serializer):
# Update an existing instance...
if instance is not None:
for key, val in attrs.items():
setattr(instance, key, val)
try:
setattr(instance, key, val)
except ValueError:
self._errors[key] = self.error_messages['required']
# ...or create a new instance
else:

View File

@ -6,6 +6,23 @@ And RFC 6585 - http://tools.ietf.org/html/rfc6585
"""
from __future__ import unicode_literals
def is_informational(code):
return code >= 100 and code <= 199
def is_success(code):
return code >= 200 and code <= 299
def is_redirect(code):
return code >= 300 and code <= 399
def is_client_error(code):
return code >= 400 and code <= 499
def is_server_error(code):
return code >= 500 and code <= 599
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_200_OK = 200

View File

@ -707,20 +707,21 @@ class ChoiceFieldTests(TestCase):
self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES)
def test_invalid_choice_model(self):
s = ChoiceFieldModelSerializer(data={'choice' : 'wrong_value'})
s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']})
self.assertEqual(s.data['choice'], '')
def test_empty_choice_model(self):
"""
Test that the 'empty' value is correctly passed and used depending on the 'null' property on the model field.
Test that the 'empty' value is correctly passed and used depending on
the 'null' property on the model field.
"""
s = ChoiceFieldModelSerializer(data={'choice' : ''})
s = ChoiceFieldModelSerializer(data={'choice': ''})
self.assertTrue(s.is_valid())
self.assertEqual(s.data['choice'], '')
s = ChoiceFieldModelWithNullSerializer(data={'choice' : ''})
s = ChoiceFieldModelWithNullSerializer(data={'choice': ''})
self.assertTrue(s.is_valid())
self.assertEqual(s.data['choice'], None)
@ -740,6 +741,23 @@ class ChoiceFieldTests(TestCase):
self.assertEqual(f.from_native(''), None)
self.assertEqual(f.from_native(None), None)
def test_metadata_choices(self):
"""
Make sure proper choices are included in the field's metadata.
"""
choices = [{'value': v, 'display_name': n} for v, n in SAMPLE_CHOICES]
f = serializers.ChoiceField(choices=SAMPLE_CHOICES)
self.assertEqual(f.metadata()['choices'], choices)
def test_metadata_choices_not_required(self):
"""
Make sure proper choices are included in the field's metadata.
"""
choices = [{'value': v, 'display_name': n}
for v, n in models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES]
f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES)
self.assertEqual(f.metadata()['choices'], choices)
class EmailFieldTests(TestCase):
"""

View File

@ -64,17 +64,23 @@ class MockView(APIView):
class MockGETView(APIView):
def get(self, request, **kwargs):
return Response({'foo': ['bar', 'baz']})
class MockPOSTView(APIView):
class MockPOSTView(APIView):
def post(self, request, **kwargs):
return Response({'foo': request.DATA})
class EmptyGETView(APIView):
renderer_classes = (JSONRenderer,)
def get(self, request, **kwargs):
return Response(status=status.HTTP_204_NO_CONTENT)
class HTMLView(APIView):
renderer_classes = (BrowsableAPIRenderer, )
@ -97,6 +103,7 @@ urlpatterns = patterns('',
url(r'^parseerror$', MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
url(r'^html$', HTMLView.as_view()),
url(r'^html1$', HTMLView1.as_view()),
url(r'^empty$', EmptyGETView.as_view()),
url(r'^api', include('rest_framework.urls', namespace='rest_framework'))
)
@ -232,6 +239,17 @@ class RendererEndToEndTests(TestCase):
self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8')
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
def test_204_no_content_responses_have_no_content_type_set(self):
"""
Regression test for #1196
https://github.com/tomchristie/django-rest-framework/issues/1196
"""
resp = self.client.get('/empty')
self.assertEqual(resp.get('Content-Type', None), None)
self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
_flat_repr = '{"foo": ["bar", "baz"]}'
_indented_repr = '{\n "foo": [\n "bar",\n "baz"\n ]\n}'

View File

@ -558,6 +558,29 @@ class ModelValidationTests(TestCase):
self.assertFalse(second_serializer.is_valid())
self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']})
def test_foreign_key_is_null_with_partial(self):
"""
Test ModelSerializer validation with partial=True
Specifically test that a null foreign key does not pass validation
"""
album = Album(title='test')
album.save()
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = Photo
photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk})
self.assertTrue(photo_serializer.is_valid())
photo = photo_serializer.save()
# Updating only the album (foreign key)
photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True)
self.assertFalse(photo_serializer.is_valid())
self.assertTrue('album' in photo_serializer.errors)
self.assertEqual(photo_serializer.errors['album'], photo_serializer.error_messages['required'])
def test_foreign_key_with_partial(self):
"""
Test ModelSerializer validation with partial=True

View File

@ -0,0 +1,33 @@
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework.status import (
is_informational, is_success, is_redirect, is_client_error, is_server_error
)
class TestStatus(TestCase):
def test_status_categories(self):
self.assertFalse(is_informational(99))
self.assertTrue(is_informational(100))
self.assertTrue(is_informational(199))
self.assertFalse(is_informational(200))
self.assertFalse(is_success(199))
self.assertTrue(is_success(200))
self.assertTrue(is_success(299))
self.assertFalse(is_success(300))
self.assertFalse(is_redirect(299))
self.assertTrue(is_redirect(300))
self.assertTrue(is_redirect(399))
self.assertFalse(is_redirect(400))
self.assertFalse(is_client_error(399))
self.assertTrue(is_client_error(400))
self.assertTrue(is_client_error(499))
self.assertFalse(is_client_error(500))
self.assertFalse(is_server_error(499))
self.assertTrue(is_server_error(500))
self.assertTrue(is_server_error(599))
self.assertFalse(is_server_error(600))

View File

@ -12,7 +12,7 @@ def get_version(package):
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.match("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
def get_packages(package):