dobarkod / django-restless Goto Github PK
View Code? Open in Web Editor NEWLightweight set of tools for building JSON-based RESTful APIs in Django
Home Page: https://django-restless.readthedocs.org/en/latest/
Lightweight set of tools for building JSON-based RESTful APIs in Django
Home Page: https://django-restless.readthedocs.org/en/latest/
Not sure what approach you'd want to handle this, but if you pass in fields
as a tuple and include
too, then you get AttributeError: 'tuple' object has no attribute 'append'
.
The approaches I can think of would be:
fields
has to be a list (not very pythonic)fields
is a list (extra code)fields
has to be a list (not very pythonic and extra code)relevant code in serialize_model
:
if include is not None:
for i in include:
if isinstance(i, tuple) or (isinstance(i, six.string_types)):
fields.append(i)
We should change the examples to be compatible with custom user models so people aren't confused whether Restless supports it or not.
Django's built-in paginator works in terms of fixed-size pages. While usable in API context, this might pose problems if results are likely to change between subsequent page requests (eg. more data pours in).
A simple pagination model with since
(all objects after the selected one) and limit
works better in this case. Here's a sample implementation:
def get_paginated_data(data, start, count, order='-id'):
if order.startswith('-'):
asc = False
order_field = order[1:]
else:
asc = True
order_field = order
ordered_data = data.order_by(order)
if start:
filter_fields = {
order_field + ('__gte' if asc else '__lte'): start
}
ordered_data = ordered_data.filter(**filter_fields)
retval = list(ordered_data[:count + 1])
if len(retval) > count:
obj = retval[count]
while '__' in order_field:
prefix, order_field = order_field.split('__', 1)
obj = getattr(obj, prefix)
next = getattr(obj, order_field)
retval = retval[:-1]
else:
next = None
return (retval, next)
Note that this example includes the "since" object in results (in effect, returning it twice).
The action method takes the request
param which isn't shown.
l'll get around to doing this:
Reference: https://github.com/dobarkod/django-restless/blob/master/restless/models.py#L190
`--> pip freeze
alabaster==0.7.10
Babel==2.3.4
coverage==4.3.4
Django==1.10.6
docutils==0.13.1
flake8==3.3.0
imagesize==0.7.1
Jinja2==2.9.5
MarkupSafe==0.23
mccabe==0.6.1
pycodestyle==2.3.1
pyflakes==1.5.0
Pygments==2.2.0
pytz==2016.10
requests==2.13.0
six==1.10.0
snowballstemmer==1.2.1
Sphinx==1.5.3
`--> python3 manage.py test --failfast
Creating test database for alias 'default'...
................F
======================================================================
FAIL: test_create_author_multipart (testapp.tests.TestEndpoint)
Exercise multipart/form-data POST
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/cleber/code/third-party/django-restless/testproject/testapp/tests.py", line 346, in test_create_author_multipart
self.assertEqual(r.status_code, 201, r.content)
AssertionError: 400 != 201 : b'{"error": "invalid author data", "details": {"name": ["This field is required."]}}'
I made a slight modification on asserEqual so it could print r.content
. Aparently, although name
is indeed being present on the payload (see below), it's not being recognized somewhere.
The test:
def test_create_author_multipart(self):
"""Exercise multipart/form-data POST"""
r = self.client.post('author_list', data={
'name': 'New User',
}) # multipart/form-data is default in test client
self.assertEqual(r.status_code, 201, r.content)
self.assertEqual(r.json['name'], 'New User')
self.assertEqual(r.json['name'],
Author.objects.get(id=r.json['id']).name)
It'd be really neat to request an endpoint and specify which fields I'd like back in the request, which may help keep size down if you know you only need a few fields.
I've not found a great way to do this yet, but I've got a few ideas around keeping a root serialize dict, and index into that for the values of a serialize call, defaulting to a list of default fields to include. Sounds a bit heavy-handed.
Anyone have better ideas or solutions?
when i send request with content_type == 'application/json' and without payload i get error 400 {"error": "invalid JSON payload: No JSON object could be decoded"}
ujson has been shown to be much faster at parsing json than the standard module. The benchmarks can be found here https://pypi.python.org/pypi/ujson#benchmarks . Upon installation, django-restless could require ujson as a dependency, and replace all of the imports with
import ujson as json
removing the need for the try except lines seen in the code base.
It would be nice if django-restless could support user authentication through Oauth tokens passed from a client, similar to what is described here:
http://blog.wizer.fr/2013/11/angularjs-facebook-with-a-django-rest-api/
One library which looks nice is
I just ran into a bug with 0.0.6 and a client machine using IE9.
It seems IE9 doesn't like the "application/json; charset=utf8" content type header and drops the response data (without warning).
Not sure what the correct way to handle this is, but changing the header to read "application/json; charset=utf-8" (notice the dash) makes it work again.
This also seems to be the correct way of doing it, see http://www.w3.org/International/O-HTTP-charset.en
Since it's just a one character fix in http.py, I didn't issue a pull request.
In Django 1.6, they standardized on get_queryset
. If this is trying to mimic vanilla Django, it should follow.
Announcement:
https://docs.djangoproject.com/en/dev/releases/1.6/#get-query-set-and-similar-methods-renamed-to-get-queryset
Example code where the generic ListView uses get_queryset:
https://github.com/django/django/blob/stable/1.6.x/django/views/generic/list.py#L23
It'd be good to have some form of self-describing API, in terms of providing list (and possibly descriptions) of available resources.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.