Simple RESTFUL client/server example in Python? - python

Is there an online resource that shows how to write a simple (but robust) RESTFUL server/client (preferably with authentication), written in Python?
The objective is to be able to write my own lightweight RESTFUL services without being encumbered by an entire web framework. Having said that, if there is a way to do this (i.e. write RESFUL services) in a lightweight manner using Django, I'd be equally interested.
Actually, coming to thing of it, I may even PREFER a Django based solution (provided its lightweight enough - i.e. does not bring the whole framework into play), since I will be able to take advantage of only the components I need, in order to implement better security/access to the services.

Well, first of all you can use django-piston, as #Tudorizer already mentioned.
But then again, as I see it (and I might be wrong!), REST is more of a set of design guidelines, rather than a concrete API. What it essentially says is that the interaction with your service should not be based on 'things you can do' (typical RPC-style methods), but rather 'things, you can act on in predictable ways, organized in a certain way' (the 'resource' entity and http verbs).
That being said, you don't need anything extra to write REST-style services using django.
Consider the following:
# urlconf
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^tickets$', 'myapp.views.tickets', name='tickets'),
url(r'^ticket/(?P<id>\d+)$', 'myapp.views.tickets', name='ticket'),
url(r'^ticket$', 'myapp.views.tickets', name='ticket'),
)
# views
def tickets(request):
tickets = Ticket.objects.all()
return render_to_response('tickets.html', {'tickets':tickets})
def ticket(request, id=None):
if id is not None:
ticket = get_object_or_404(Ticket, id=id)
if request.method == 'POST':
# create or update ticket here
else:
# just render the ticket (GET)
...
... and so on.
What matters is how your service is exposed to its user, not the library/toolkit/framework it uses.

This one looks promising. http://parand.com/say/index.php/2009/04/30/django-piston-rest-framework-for-django/ I've used it before and it's pretty nifty. Having said that, it doesn't seem maintained recently.

Related

Convert Django Views to rest services

I have an application created long back, now client want to expose its some of views as APIs without breaking existing functionality, so that they can directly consume APIs using REST Tools to see the reports.
Is there any easier way, I can convert my function to a REST View.
P.S - I kept code shorter here to keep question simple, but in fact, its much complex in the actual app.
eg.
URL : -
`path('/users', views.show_user_details, name='users'),`
VIEW
def show_user_details(request, user_id):
users = User.objects.all()
return render(request, "Users.html", {"users":users})
In REST Views, I want it to convert its input and output so that it can be accessible with same urls(or with little modifications), without much updating the existing views.
`path('rest/users', views.show_user_details, name='users'),` #-- I am ok to add new url like this, but without much change in existing view .
def show_user_details(request, user_id):
users = User.objects.all()
return JsonResponse({"users":users})
Due to the fact that a normal website visit is still a GET request and GET is just one of your usual REST actions, you'll probably want to prepare your own independent API endpoint. Check out django-rest-framework for that, and you might just feel at home for this task.

What are the differences between Generics, Views, Viewsets and Mixins in Django?

I am new to Django and Django-Rest. I am confused about when I should use these? what are their advantages and disadvantages? I have only seen this- http://www.cdrf.co
The only thing I know is there are a lot of ways to do 1 thing. But this is totally unclear to me.
In Django, these four terms we use frequently for different purposes in the projects. I have tried to collect and share the actual meaning with the links to details description of each term. Please check if you find these helpful.
Generic views:
“Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.”
— Django Documentation
Read more details
Views:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
Read more details
Viewsets:
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks, you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Read more details
Mixins:
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Read more details

Django REST browser interface

I'm writing a set of REST services for a Django project. I've been using django-rest-framework for a while. Because of its limited functionality I had to switch to django-piston which I quite enjoy.
However, django-rest-framework had one really nice feature - it was able to display an admin-like interface for testing the created services from the browser. It's just terrific for debugging purposes. It's very simple: one form is displayed for each HTTP method like "GET", "POST", etc. Along with that a drop-down list of available content types and a text field for putting in the data to be sent.
As I view it, this isn't really a feature in any way directly connected with a particular REST framework. It isn't even necessarily about Django. It could all be achieved just using HTML + JS, or an external website.
My question is: What do you use for manual testing / debugging web services? Could you point me to some HTML snippet or a Django app that would do the described thing?
This may seem obvious, but:
Why not just use Django's testing client (django.test.client.Client)? then instead of manually 'debugging' in your browser, you can write unit tests with expectations and get leverage out of those further down the track.
e.g.
from django.test.client import Client
client = Client()
resp = client.put('/employee/2/', data={'email': 'here#there.com'}, follow=True)
#... etc
As the author of django-rest-framework it'd be great to pick your brains about which bits of functionality could do with fleshing out. :) (obv i've got some thoughts of my own and areas I'm planning to work on, but be really good to get some user perspective)
Your absolutely right about the API browser not being limited to any particular framework. To me that's the big deal with DRF and I'd love to see more API frameworks take a similar approach. One of the supposed benefits of RESTful APIs is that they should be self-describing, and it seems counter-intuitive to me that so many of the Web APIs we build today are not Web browseable.
Oh, and totally agree with jsw re. testing Web APIs in django, I wouldn't use the framework's browsable API to replace automated tests.
I had the same problem and that was eaily solved by logging out of admin page in that project.

Django for a simple web application

I'm developing an app (an API) in python and I would like to offer some of its functionality through a web interface (like web services do).
I've been looking at django, but I don't know if really fits well in my idea. I only want to create a web page that invokes to my API methods in order to acomplish the functionality that offers that web page. But, after followed the tutorial, I feel a little confused about the point of django. It seems to me to be more related with an ORM than a classic web application.
Is django a solution so heavy for such a simple development (as I mentioned, make calls to my API through the web)? Do I always have to use a database?
Thanks.
I love django but there is an lot of it to get your head around! If you don't want the database bit, focus on urls.py and views.py that will process your urls and return the info you want as an http response.
eg. urls.py
urlpatterns += patterns('myapp.views',
url(r'^getstuff/$', 'getstuff' ),
)
in views.py
def getstuff(request):
do whatever in python
return HttpResponse(stuff to return)
You don't need to use database in Django projects.
Basically django comes with some standardized architecture that follows MVC pattern (or MVT as sometimes described). This includes models, views, url dispatching, templates, etc.
Probably you need to do following things to accomplish your task:
create url definition in urls.py
to some django view
write
django view that call somehow your
api and displays result as a web
page
you don't need models and database at all but you need to get familliar with views, urls, templates. It might look like a big machinery for your simple case but if you have some time I encourage you to these django basics.
If you are looking for somethin much simpler I heard about webpy project. This might be better option if you need something really simple.
An important question is: Do you want the web services to be provided by a full-featured server like Apache, or are you just looking at the "web server" to be a thread (or equivalent) in your program?
If you want to run Apache, then I'd recommend something like Werkzeug, which will handle most of the WSGI stuff for you. For templating, I've heard good things about Jinja2.
If that is too much, and all you want is a lightweight, simple server (something that, say, just spits out some HTML or XML when asked, and doesn't need any fancy URL handling), you can use the SimpleHTTPServer or CGIHTTPServer modules that ship with Python.
Django is a full-featured, integrated package that provides almost everything you need to write database-backed web applications. While its various components can be used in isolation, if you're only using one thing (the template and view engines, in your case), it is probably overkill.
No need for a framework at all. Raw wsgi isn't hard but a little verbose. So I like to use WebOb
Here's Raw wsgi
def application(environ, start_response):
start_response("200 OK", [])
return ["<html><body><h1>Hello World</h1></body></html>"]
Here's the webob version
from webob.dec import wsgify
from webob import Request
#wsgify
def application(request):
return Response("<html><body><h1>Hello World</h1></body></html>")
That's enough to run under apache mod_wsgi, and there are plenty of libraries that you can use that expect/produce webob Request and Responses. Anything that Turbogears 2 or repoze.bfg uses is fair game at that point.
You definitely don't have to use a database with Django. Whether it fits your needs, only you can tell. There are other Python web frameworks that you can use.

Django, how to generate an admin panel without models?

I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with is the web interface. I want to use Django, because it's both written in python and has that incredibly useful automatic admin panel generator.
The web interface doesn't access any database. It connects to an Ice service on Server #1 via the Glacier2 router and uses the API exposed by those services to manipulate data.
And as you probably know, the admin generation in Django depends on the use of Django's ORM; which I'm not using since I have no database to access.
So I need to generate the admin panel, but, instead of having an standard data access like the ORM normally does, I need to intercept any "db-access" calls and transform them into Ice service calls, and then take the service's output (if any), transform it into whatever the ORM normally returns and return control to Django.
Anyone knows how I could do this? what would I need to subclass? Any specific ideas?
Thanks for your time.
I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.
Take a look at models.py, admin.py and urls.py here: django-webfaction
To create an entry on the admin index page use a dummy model that has managed=False
Register that model with the admin.
You can then intercept the admin urls and direct them to your own views.
This makes sense if the add/edit/delete actions the admin provides make sense for your app. Otherwise you are better off overriding the admin index or changelist templates to include your own custom actions
The real power of the contrib.admin is django Forms. In essence, the admin tool is basically auto-generating a Form to match a Model with a little bit of urls.py routing thrown in. In the end it would probably just be easier to use django Forms apart from the admin tool.
you can "mock" some class so it look like a model but it does proxy to your APIs
f.e.
class QuerysetMock(object):
def all():
return call_to_your_api()
[...]
class MetaMock(object):
def fields():
return fields_mock_objects..
verbose_name = ''
[...]
class ModelMock(object):
_meta = MetaMock()
objects = QuerysetMock()
admin.site.register(ModelMock)
This may work.. but you need to do a lot django.model compatible stuff
The django ORM has a pluggable backent, which means that you can write a backend for things that aren't RDBMSes. It's probably a rather large task, but a good place to get started is with Malcolm Tredinnick's talk from DjangoCon 2008, Inside the ORM.
Otherwise, you could bypass the ORM altogether, and write the forms manually for the access you need.

Categories