Django, REST, and Web Development - django

I'm new to web development, but have recently been getting going with it pretty fast, using Django (which I'm falling in love with). However, while Django is easy to get going with and pick up quite fast, I'm afraid there are concepts I don't know much about, particularly REST and RESTful web services. I hear those terms thrown around a lot, and I'm assuming are important to modern web apps, and I want to know basically what they mean, when I should use them, and how I should use them (package, plugin, etc.).
My web app consists of the following functionality:
Discussion Board which I've implemented so far only using the model layer
Messaging which I've implemented so far only using the model layer
Payments (not yet implemented)
Calendar (not yet implemented)
And that's about it for now. When should I be thinking about REST within these functionalities?

You could get really in depth with the subject, but when I think of it, I think of the URLs your site will be providing. That, for me at least, is the simple way to think of a RESTful service. I also think it's a good way to get to grips with Django & it's generic views.
Taken your example there of a calendar. A RESTful approach to a calendar app, with django's generic views, might implement URLs like;
# ListView
/calendar
# DetailView for a given item in the calendar
/calendar/<id>
# UpdateView for an item
/calendar/<id>/update
# DeleteView for an item
/calendar/<id>/delete
Beyond that, REST requires you consider the HTTP methods in use, so you should then define what methods your URLs will accept in order to better control the interaction. Furthermore, if you were enforcing the HTTP method on each action, you could write a more generic view which didn't expose the /update or /delete URLs. But I'd consider that a more advanced approach & you may wish to start from a more explicit design.
Once you start to write a consistent structure for your apps then you can easily make generic functions, and expand.
There is a whole load of things you could read on this subject, depending on where you see it going.
If you're thinking of building something that can provide an API then there's already a Django framework for this; http://www.django-rest-framework.org/
But if you're getting started & just want to know more about the concepts, Wikipedia is always a good place to look, and finally this looks like a great example for this subject using Django which should hopefully help you on your way.
To understand the idea of a resource, take a look at this answer

Related

Django-Rest: Reusable application design

My application stack includes AngularJs -> Django Rest Framework -> Django.
I am designing a comments application for articles on my website. These articles are linked to a topic entity. Now for writing a REST backend for these comments I end up with urls that look like -
/topics/(topic_id)/articles/(article_id)/comments.
Thus my views in turn end up having signature like:
get(self, requests, topic_id, article_id, format=None)
The Comments do not need to have any information about topic to which this article is attached and yet it has that information.
I am unable to figure out whether this is a bad REST design or if I can do it in some better way in django.
BTW I looked at generic implementation of comments application. It seems to be relying on template tags for information like article_id which I can not use since I am not using django templates.
A lot of how your API is designed will depend on how tight the relations are. This isn't really a REST problem, or a Django problem, but it's more of a url design problem.
You are currently using nested urls, where each part of the hierarchy is included in the url, even if it isn't useful or necessary. It is generally recommended that if you don't need each part of the hierarchy, it shouldn't be in the url, and your urls will become flat as a result. Heroku's API design guide is a useful read, though you must consider the impact on your application and whether or not it is worth it.
The Comments do not need to have any information about topic to which this article is attached and yet it has that information.
This is one of the problems with nested designs, you end up with deeply nested structures with a lot of useless information. But what is important to remember is that REST is not at all related to the URL structure of your API, but some people do have strong opinions on how they should work together.
If you were looking to go for a flat approach with your urls, which would remove topic and article from the patterns, you would end up with urls similar to the following:
/topics/{topic_id}/
/articles/?topic={topic_id}
/articles/{article_id}/
/comments/?article={article_id}
/comments/{comment_id}/
This will allow you to remove the need for the topics to be in the url, as well as the article, so only the most important information is visible in the url: the comment information.
Django REST Framework has great filtering support that can be used to make useful, flat APIs.

Ember-data in a non-RESTful environment

I would like to use ember-data in a project I am building, but the API I am working with does not follow REST conventions.
For example, all the HTTP requests are POST and the naming conventions of the endpoints are unique to the actions they perform. e.g. /api/thing/retrieve would require me to post a JSON object with some parameters, and would return a 'thing' to me.
Do I use the Restful adapter and reopen the class and redefine the various find functions?
OR
Do I have to make a new adapter?
OR
Should I just abandon ember-data and and use ajax in my models(or maybe even controllers)?
I'm not sure how I would handle any of those options. Any guidance would be appreciated.
The only information which I have seen on this subject has been an article by the Discourse folks linked below.
http://eviltrout.com/2013/03/23/ember-without-data.html
I personally have toyed around with the reopenClass method in the article, and would probably drop it into a mixin or something to that effect if I had a consistent but non-REST API which I was calling regularly.
I would say that, if your API is consistent (reliable) then you should create/extend the DS.Adapter (not DS.RESTAdapter) to implement to your specification.
All the hooks are there, you will just end up defining it once which all models can use.
I would also read through the Basic Adapter code - (https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/basic_adapter.js) it might be a better staring point for you then DS.Adapter.
If your API is not reliable, then you are probably better off with just using the $.ajax() calls as necessary. But, in my opinion, that does not scale well.
A link worth reading when looking at Basic Adapter: http://emberjs.com/blog/2013/03/22/stabilizing-ember-data.html
One last note, building an ORM or even a something more simple then an ORM is not a trivial task, that for me, makes using ember-data worth the effort, and yes sometimes pain.

Integrating django apps in your own views

Let's say I'm writing a complex site in django with wikis, forums, ... or writing my own apps that I intend to reuse from different sites.
I really want to create, for example, a wiki page that has a forum at the bottom, or reuse my previously written wiki app with a different graphical layout.
What is the best way to structure my app to allow this kind of reuse?
So far, I have been giving apps their own urls in urls.py. This however does not work if I want to combine multiple apps together in a single page.
Additionally, most of the apps I found online come with their own templates, which has the full html, and do not separate the logic of creating / preparing a context from that of handling a request and generating a reply.
What is the best practice here? What do you do? edit the templates that come from applications you download online? refactor them to fit in your application?
what should I do for my own applications? structure them so they have a method to get the context, and a method to render it?
Django hasn't great support out of the box to component-oriented architectures. I find this problematic some times too. You'll face to problems here.
Architecture
Code
Architecture: As Django is not component oriented, all the apps aren't component oriented neither. The designers and coders for those apps haven't thought about that. So they've just built "views" to interface with their apps. You'll need to get something more "pluggable".
Code: Once you decide to build that, you'll have to find what support you have for that. Most Django apps are pretty well coded, so you won't have much code in views, but abstracted in other places. That way you could reuse that code and build your own components.
Example: Suppose you're working with a third-party Wiki app. That wiki has a view to display highest ranked Tags and other view to create a wiki entry. If the code is good enough (that I'm assuming it is because Django has a pretty good community), you could refactor that to use components. The view to create an entry must be using some Form, that you can plug in your own site. And the view to get highest ranked tags probably uses some utility function, or some Tag manager's method. In that case you could refactor it to your own needs.
Hope it helps.

What are the differences between django-tastypie and djangorestframework? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Why would you use one over the other, for exposing an API for your Django app?
http://pypi.python.org/pypi/djangorestframework/
http://pypi.python.org/pypi/django-tastypie
As the author of django-rest-framework, I've got an obvious bias ;) but my hopefully-fairly-objective opinion on this is something like:
TastyPie
As Torsten noted, you're not going to go far wrong with something written by the same peeps as the awesome django-haystack. From what I've seen on their mailing list Daniel Lindsey et al are super-helpful, and Tastypie is stable, comprehensive and well documented
Excels in giving you a sensible set of default behaviour and making building an API with that style incredibly easy.
Django REST framework
Gives you HTML browse-able self-describing APIs. (EG, see the tutorial API.) Being able to navigate and interact with the API directly in the browser is a big usability win.
Tries to stay close to Django idioms throughout - built on top of Django's class based views, etc... (Whereas TastyPie came along before Django's CBVs existed, so uses it's own class-based views implementation)
I'd like to think that the underlying architecture is pretty nicely built, decoupled etc...
In any case, both are good. I would probably characterise Tastypie as giving you a sensible set of defaults out of the box, and REST framework as being very nicely decoupled and flexible. If you're planning on investing a lot of time in the API, I'd def recommend browsing through the docs & codebase of each and trying to get a feel for which suits you more.
Obviously, there's also the 'Why TastyPie?' section in it's README, and the 'REST framework 3'.
See also Daniel Greenfeld's blog post on Choosing an API framework for Django, from May 2012 (Worth noting that this was still a few months before the big REST framework 2.0 release).
Also a couple of threads on Reddit with folks asking this same question, from Dec 2013 and July 2013.
Both are good choices.
For filters, tastypie is more powerful out-of-the-box. If you have a view that exposes a model, you can do Django-style inequality filters:
http://www.example.com/api/person?age__gt=30
or OR queries:
http://www.example.com/api/mymodel?language__in=en&language__in=fr
these are possible with djangorestframework, but you have to write custom filters for each model.
For tracebacks, I've been more impressed with django-rest-framework. Tastypie tries to email settings.ADMINS on exceptions when DEBUG = False. When DEBUG = True, the default error message is serialised JSON, which is harder to read.
EDIT Outdated answer, tastypie is not really maintained anymore. Use Django REST framework if you have to choose a framework to do REST.
For an overview about the actual differences between both of them you should read their documentation. They are both more or less complete and quite mature.
I personally tend to tastypie though. It seems to be easier to set it up. It's done from the same people which created django-haystack which is awesome and according to django-packages it is used more than Django REST framework.
It's worth noting that since this was first asked DRF has gone from strength to strength.
It's the more active of the two on github (both in terms of commits, stars, forks and contributors)
DRF has OAuth 2 support and the browsable API.
Honestly for me that last feature is the killer. Being able to point all my front-end devs at the browsable API when they aren't sure how something works and say 'Go play; find out' is fantastic.
Not least because it means they get to understand it on their own terms and know that the API really, definitely, absolutely does what the 'documentation' says it does. In the world of integrating with APIs, that fact alone makes DRF the framework to beat.
Well, Tastypie and DRF both are excellent choices. You simply can’t go wrong with either of them. (I haven’t worked on Piston ever; and its kind of not trending anymore now a days so won’t / can’t comment on it. Taken for Granted.).
In my humble opinion: Choice should be made on yours (and your tech team’s) skills, knowledge and capabilities. Rather than on what TastyPie and DRF offers, unless off-course you are building something really big like Quora, Facebook or Google.
Personally, I ended up starting working first on TastyPie at a time when I didn’t even know django properly. It all made sense at that time, only knowing REST and HTTP very well but with almost no or little knowledge about django. Because my only intention was to build RESTful APIs in no time which were to be consumed in mobile devices. So if you are just like ‘I happen to be at that time called django-new-bie’, Don’t think more go for TastyPie.
But if you have many years of experience working with Django, knows it inside out and very comfortable using advanced concepts (like Class Based Views, Forms, Model Validator, QuerySet, Manager and Model Instances and how all they interact with one another), **go for DRF. **DFR is bases on django’s class based views.
DRF is idiomatic django. Its like you are writing model forms, validators etc. (Well, idiomatic django is no where near to idiomatic python. If you are python expert but have no experience with Django then you might be having hard time initially fit into idiomatic django philosophy and for that matter DRF as well).
DRF comes with lots of inbuilt magic methods just like django. If you love the django magical methods and philosophy **DRF **is just for you.
Now, just to answer the exact question:
Tastypie:
Advantages:
Easy to get started with and provide basic functionalities OOB (out of the box)
Most of the time you won’t be dealing with Advanced Django concepts like CBVs, Forms etc
More readable code and less of magic!
If your models are NON-ORM, go for it.
Disadvantages:
Doesn’t strictly follow idiomatic Django (mind well python and django’s philosophies are quite different)
Probably bit tough to customize APIs once you go big
No O-Auth
DRF:
Follow idiomatic django. (If you know django inside out, and very comfortable with CBV, Forms etc without any doubt go for it)
Provides out of the box REST functionality using ModelViewSets. At the same time, provides greater control for customization using CustomSerializer, APIView, GenericViews etc.
Better authentication. Easier to write custom permission classes. Work very well and importantly very easy to make it work with 3rd party libraries and OAuth. DJANGO-REST-AUTH is worth mentioning LIBRARY for Auth/SocialAuthentication/Registration. (https://github.com/Tivix/django-rest-auth)
Disadvantages:
If you don’t know Django very well, don’t go for this.
Magic! Some time very hard to understand magic. Because its been written on top of django’s CBV which are in turn quite complex in nature. (https://code.djangoproject.com/ticket/6735)
Has steep learning curve.
Personally what would I use in my next project?
Now, I am no more a fan of MAGIC and Out-of-box functionalities. Because all they come at a *great cost. * Assuming I have all choices and control over project time and budget, I would start with something light weight like RESTLess (https://github.com/toastdriven/restless) (created by the creator of TastyPie and django-haystack (http://haystacksearch.org/)). And for the same matter probably/definately choose the lightweight web framework like Flask.
But why? - More readable, simple and manageable idiomatic python (aka pythonic) code. Though more code but eventually provide great flexibility and customization.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
What if you have only no choice but Django and one of TastyPie and DRF?
Now, knowing the Django reasonably well, I will go with **DRF. **
Why? - idiomatic djagno! (I don’t love it though). Better OAuth and 3rd party integration (django-rest-auth is my favorite).
Then why you chose the DRF/TastyPie at first place?
Mostly I have worked with startups and small firms, which are tight on budget and time; and need to deliver something quick and usable. Django serve this purpose very well. (I am not at all saying that django is not scalable. There are websites like Quora, Disquss, Youtube etc run on it. But all it require time and more then average skills)
I hope, it will help you to take better decision.
Other references -
1. The State of Tastypie (http://toastdriven.com/blog/2014/may/23/state-tastypie/)
2. What are the differences between django-tastypie and djangorestframework? (What are the differences between django-tastypie and djangorestframework?)
Having used both, one thing that I liked (preferred) about Django Rest Framwork is that is is very consistent with Django.
Writing model serializers is very similar to writing model forms. The built in Generic Views are very similar to Django's generic views for HTML.
Django-tastypie is no longer maintained by it's original creator and he created a new light weight framework of his own.
At present you should use django-rest-framework with django if you are willing to expose your API.
Large corporations are using it. django-rest-framework is a core member of django team and he get funding to maintain django-rest-framework.
django-rest-framework also have huge number of ever growing 3rd arty packages too which will help you build your API's more easily with less hassles.
Some part of drf will also be merged in django proper.
drf provide more better patterns and tools then django-tastypie.
In short it's well designed, well maintained, funded, provide huge 3rd party apps, trusted by large organisations, easier and less boilerplate etc over tastypie.

Django vs. Grok / Zope3 vs. Pylons

I am a computer programmer by training but have been away from web development for a while. I am doing a little bit of background research on various Python web development frameworks. I understand that Django, Grok / Zope 3, and Pylons are all good solid frameworks, but have little in the way of background working with them. Can someone explain to me the difference in approach of the each of the frameworks, and where one shines when compared to the others?
My specific use case is in building a web application that will recommend products to users based on a variety of user supplied information. Thus, it will take a fair bit of user input in the shape of a basic profile, product preferences, attempt to establish social relationships between users. It will also need to support staff uploading products into the system with labeled features that can be then matched to users.
On the last point, would parts of Plone help with providing an interface for non-tech people to upload products and descriptions of the products? Are piece of Plone easy to borrow? Seems like I shouldn't have to reinvent the wheel in terms of having a way for people to upload items for sale / recommendation along with some metadata to describe the items. Thanks for the help.
Based on your background and requirements, I'd advise you to go with something like http://pinaxproject.com/ which is based on Django.
Pyramid (the successor to Pylons) is a very low-level framework and you need to either choose the libraries or write all your application code yourself. For someone experienced this makes sense and gives you full control over your code. But it is a bit of a hurdle if you start from scratch and aren't familiar with the available libraries.
Django and Grok are both high level frameworks, with Django being the more popular choice. If you aren't familiar yet with using object databases or URL traversal, Grok is more time consuming to learn.
Plone is not suited for your use-case. It's a content management system and not a general web framework. Very little of the libraries it uses can be reused in a different context, certainly none of its UI. If you want to provide an engaging user experience with personalized content, Plone isn't for you - that's not what its been build to handle.
Disclaimer: I'm a release manager for Plone and Zope 2 / Zope Toolkit and have used Pyramid but not Django.
Dolmen project is a CMS built on top of Grok. Is very simple, but there are very few that use it. If you go with Grok, you could be able to reuse the GUI.
But As Hanno said, Grok is more time-consuming to learn than Django. Also Django has far more users than Grok.
The advantage of using Grok is that you can profit from Zope Component Architecture almost without writing ZCML and using decorators instead.
With Pyramid/Pylons you get a very simple framework and nothing else. It is a decoupled framework, so you are free to use whatever templating enginge you want (Mako, Genshi, Jinja, Cheetah), you are free to choose sqlalchemy, zodb, mongoDb, etc., and you are also free to choose the url mapping scheme (traversal vs. django-style mapping or a combination of both). You can also use ZCA here if you want. For starters this might become quite confusing or verbose.
Django is a kind of monolithic framework that gives you one way to do stuff. That's why it's easy to learn and a very good option. But, in my experience, you sometimes get to a point where you want to deviate from Django standards and it simply cannot be done without patching a bunch of stuff.
And, as for Zope3, I'd recommend you to download a copy of BlueBream and se how it does for you.
As a Plone user I can say that creating Content Objects in Plone is difficult. There is not much documentation on how to do it and it is complicated. Some recommend using UML and specialized Plone products to make it easier but that introduces yet another dependency.
I mention the problem with content objects because your "products" (not the same as a Plone product) would probably be represented in Plone as a content object which you would need to write yourself.
Plone is best when users and editors are entering and approving text in the form of news articles, press releases, photos etc. When that is the use case there are predefined content objects for such things so one does not need to write them oneself.
--Jonathan Mark