跳转到主要内容

最小化Django资源框架。

项目描述

dj-webmachine是一个应用层,它为Django添加了HTTP语义感知,并提供了一种简单、干净的方式将其与您的应用程序的行为连接起来。dj-webmachine还为您提供根据您的模型构建简单API的可能性,并提供从它自动创建文档和客户端的工具(工作正在进行中)。

安装

请确保您已安装Python 2.x >=2.5并且Django >= 1.1。

使用pip

$ pip install dj-webmachine

从源码获取

获取dj-webmachine代码

$ git clone https://github.com/benoitc/dj-webmachine.git
$ cd dj-webmachine

或使用tarbal

$ wget http://github.com/benoitc/dj-webmachine/tarball/master -o dj-webmachine.tar.gz
$ tar xvzf dj-webmachine.tar.gz
$ cd dj-webmachine-$HASH/

并安装

$ sudo python setup.py install

5分钟内安装dj-webmachine

我们将快速创建一个接受HTML和JSON的Hello world。

$ django-admin startproject helloworld
$ cd helloworld
$ python manage.py startapp hello

在hello文件夹中创建一个名为resources.py的文件

import json
from webmachine import Resource

class Hello(Resource):

    def content_types_provided(self, req, resp):
        """" define the content type we render accoridng the Accept
        header.
        """
        return (
            ("", self.to_html),
            ("application/json", self.to_json)
        )

    def to_html(self, req, resp):
        return "<html><body>Hello world!</body></html>\n"

    def to_json(self, req, resp):
        return "%s\n" % json.dumps({"message": "hello world!", "ok": True})

dj-webmachine和您的hello应用添加到设置中的INSTALLED_APPS

INSTALLED_APPS = (
    ...
    'webmachine',
    'helloworld.hello'
)

将您的Hello资源放入urls.py

from django.conf.urls.defaults import *

from helloworld.hello.resource import Hello

urlpatterns = patterns('',
    (r'^$', Hello()),
)

启动您的应用程序

$ python manage.py runserver

看看!在Web浏览器中指向http://localhost:8000/

或者使用curl

$ curl http://127.0.0.1:8000
<html><body>Hello world!</body></html>

$ curl http://127.0.0.1:8000 -H "Accept: application/json"
{"message": "hello world!", "ok": true}

第一行以html格式请求hello页面,而第二行使用相同的url请求JSON。

要了解如何做更多有趣的事情,请查看一些示例或阅读更多文档

项目详情


下载文件

下载适用于您平台的应用程序。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

dj-webmachine-0.2.1.tar.gz (32.6 kB 查看哈希值)

由以下提供支持