本文介绍了Django轻松构建RESTful界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在寻找一个借口,为Django学习一个已经出现的新项目。通常,我喜欢构建RESTful服务器端接口,其中URL映射到在某些独立于平台的上下文(例如XML或JSON)中吐出数据的资源。这是
而不是使用框架而非常简单,但是其中一些例如Ruby on Rails方便地允许您根据您现有的URL传递的URL类型轻松地将XML发送到客户端型号代码。

I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This israther straightforward to do without the use of frameworks, but some of them such as Ruby on Rails conveniently allow you to easily spit back XML to a client based on the type of URL you pass it, based on your existing model code.

我的问题是,Django有没有支持这个?我已经google了,发现了一些RESTful第三方代码,可以在Django之上。不知道我是否太热衷。

My question is, does something like Django have support for this? I've googled and found some 'RESTful' 3rd party code that can go on top of Django. Not sure if I'm too keen on that.

如果没有Django,任何其他Python框架已经建立在这一点上,所以我不必重新创造轮子因为我已经有像PHP这样的语言了?

If not Django, any other Python framework that's already built with this in mind so I do not have to reinvent the wheel as I already have in languages like PHP?

推荐答案

这可能很容易做到。

URL映射很容易构建,例如:

URL mappings are easy to construct, for example:

urlpatterns = patterns('books.views',
  (r'^books/$', 'index'),
  (r'^books/(\d+)/$', 'get'))

Django支持,因此很容易将模型转换为XML:

Django supports model serialization, so it's easy to turn models into XML:

from django.core import serializers
from models import Book

data = serializers.serialize("xml", Book.objects.all())

将两者与,您可以构建快速,快速的处理程序:

Combine the two with decorators and you can build fast, quick handlers:

from django.http import HttpResponse
from django.shortcuts import get_object_or_404

def xml_view(func):
  def wrapper(*args, **kwargs):
    result = func(*args, **kwargs)
    return HttpResponse(serializers.serialize("xml", result),
        mimetype="text/xml")
  return wrapper

@xml_view
def index(request):
  return Books.objects.all()

@xml_view
def get(request, id):
  return get_object_or_404(Book, pk=id)

这篇关于Django轻松构建RESTful界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:46