.. _ref-resources:
=========
Resources
=========
In terms of a REST-style architecture, a "resource" is a collection of similar
data. This data could be a table of a database, a collection of other resources
or a similar form of data storage. In Tastypie, these resources are generally
intermediaries between the end user & objects, usually Django models. As such,
``Resource`` (and its model-specific twin ``ModelResource``) form the heart of
Tastypie's functionality.
Quick Start
===========
A sample resource definition might look something like::
from django.contrib.auth.models import User
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from myapp.models import Entry
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
class EntryResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Entry.objects.all()
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
resource_name = 'myapp/entry'
authorization = DjangoAuthorization()
filtering = {
'slug': ALL,
'user': ALL_WITH_RELATIONS,
'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'],
}
Why Class-Based?
================
Using class-based resources make it easier to extend/modify the code to meet
your needs. APIs are rarely a one-size-fits-all problem space, so Tastypie
tries to get the fundamentals right and provide you with enough hooks to
customize things to work your way.
As is standard, this raises potential problems for thread-safety. Tastypie has
been designed to minimize the possibility of data "leaking" between threads.
This does however sometimes introduce some small complexities & you should be
careful not to store state on the instances if you're going to be using the
code in a threaded environment.
Why ``Resource`` vs. ``ModelResource``?
=======================================
Make no mistake that Django models are far and away the most popular source of
data. However, in practice, there are many times where the ORM isn't the data
source. Hooking up things like a NoSQL store (see :doc:`non_orm_data_sources`),
a search solution like Haystack or even managed filesystem data are all good
use cases for ``Resource`` knowing nothing about the ORM.
Flow Through The Request/Response Cycle
=======================================
Tastypie can be thought of as a set of class-based views that provide the API
functionality. As such, many part of the request/response cycle are standard
Django behaviors. For instance, all routing/middleware/response-handling aspects
are the same as a typical Django app. Where it differs is in the view itself.
As an example, we'll walk through what a GET request to a list endpoint (say
``/api/v1/user/?format=json``) looks like:
* The ``Resource.urls`` are checked by Django's url resolvers.
* On a match for the list view, ``Resource.wrap_view('dispatch_list')`` is
called. ``wrap_view`` provides basic error handling & allows for returning
serialized errors.
* Because ``dispatch_list`` was passed to ``wrap_view``,
``Resource.dispatch_list`` is called next. This is a thin wrapper around
``Resource.dispatch``.
* ``dispatch`` does a bunch of heavy lifting. It ensures:
* the requested HTTP method is in ``allowed_methods`` (``method_check``),
* the class has a method that can handle the request (``get_list``),
* the user is authenticated (``is_authenticated``),
* the user is authorized (``is_authorized``),
* & the user has not exceeded their throttle (``throttle_check``).
At this point, ``dispatch`` actually calls the requested method (``get_list``).
* ``get_list`` does the actual work of the API. It does:
* A fetch of the available objects via ``Resource.obj_get_list``. In the case
of ``ModelResource``, this builds the ORM filters to apply
(``ModelResource.build_filters``). It then gets the ``QuerySet`` via
``ModelResource.get_object_list`` (which performs
``Resource.apply_authorization_limits`` to possibly limit the set the user
can work with) and applies the built filters to it.
* It then sorts the objects based on user input
(``ModelResource.apply_sorting``).
* Then it paginates the results using the supplied ``Paginator`` & pulls out
the data to be serialized.
* The objects in the page have ``full_dehydrate`` applied to each of them,
causing Tastypie to translate the raw object data into the fields the
endpoint supports.
* Finally, it calls ``Resource.create_response``.
* ``create_response`` is a shortcut method that:
* Determines the desired response format (``Resource.determine_format``),
* Serializes the data given to it in the proper format,
* And returns a Django ``HttpResponse`` (200 OK) with the serialized data.
* We bubble back up the call stack to ``dispatch``. The last thing ``dispatch``
does is potentially store that a request occurred for future throttling
(``Resource.log_throttled_access``) then either returns the ``HttpResponse``
or wraps whatever data came back in a response (so Django doesn't freak out).
Processing on other endpoints or using the other HTTP methods results in a
similar cycle, usually differing only in what "actual work" method gets called
(which follows the format of "``<http_method>_<list_or_detail>``"). In the case
of POST/PUT, the ``hydrate`` cycle additionally takes place and is used to take
the user data & convert it to raw data for storage.
Why Resource URIs?
==================
Resource URIs play a heavy role in how Tastypie delivers data. This can seem
very different from other solutions which simply inline related data. Though
Tastypie can inline data like that (using ``full=True`` on the field with the
relation), the default is to provide URIs.
URIs are useful because it results in smaller payloads, letting you fetch only
the data that is important to you. You can imagine an instance where an object
has thousands of related items that you may not be interested in.
URIs are also very cache-able, because the data at each endpoint is less likely
to frequently change.
And URIs encourage proper use of each endpoint to display the data that endpoint
covers.
Ideology aside, you should use whatever suits you. If you prefer fewer requests
& fewer endpoints, use of ``full=True`` is available, but be aware of the
consequences of each approach.
Accessing The Current Request
=============================
Being able to change behavior based on the current request is a very commmon
need. Virtually anywhere within ``Resource/ModelResource``, if a ``bundle`` is
available, you can access it using ``bundle.request``. This is useful for
altering querysets, ensuring headers are present, etc.
Most methods you may need to override/extend should get a ``bundle`` passed to
them.
If you're using the ``Resource/ModelResource`` directly, with no ``request``
available, an empty ``Request`` will be supplied instead. If this is a common
pattern/usage in your code, you'll want to accommodate for data that potentially
isn't there.
Advanced Data Preparation
=========================
Not all data can be easily pull off an object/model attribute. And sometimes,
you (or the client) may need to send data that doesn't neatly fit back into the
data model on the server side. For this, Tastypie has the "dehydrate/hydrate"
cycle.
The Dehydrate Cycle
-------------------
Tastypie uses a "dehydrate" cycle to prepare data for serialization, which is
to say that it takes the raw, potentially complicated data model & turns it
into a (generally simpler) processe
没有合适的资源?快使用搜索试试~ 我知道了~
PyPI 官网下载 | django-tastypie-0.9.16.tar.gz
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 98 浏览量
2022-01-10
20:22:04
上传
评论
收藏 704KB GZ 举报
温馨提示
共175个文件
py:40个
html:32个
rst:31个
资源来自pypi官网。 资源全名:django-tastypie-0.9.16.tar.gz
资源推荐
资源详情
资源评论
收起资源包目录
PyPI 官网下载 | django-tastypie-0.9.16.tar.gz (175个子文件)
AUTHORS 6KB
.buildinfo 230B
basic.css 8KB
default.css 4KB
pygments.css 4KB
resources.doctree 416KB
testing.doctree 132KB
interacting.doctree 86KB
tutorial.doctree 71KB
fields.doctree 65KB
serialization.doctree 61KB
cookbook.doctree 47KB
authentication.doctree 33KB
contributing.doctree 30KB
index.doctree 30KB
caching.doctree 28KB
authorization.doctree 27KB
non_orm_data_sources.doctree 19KB
settings.doctree 19KB
api.doctree 19KB
validation.doctree 18KB
debugging.doctree 16KB
throttling.doctree 15KB
geodjango.doctree 15KB
tools.doctree 15KB
who_uses.doctree 14KB
paginator.doctree 12KB
bundles.doctree 11KB
content_types.doctree 8KB
compatibility_notes.doctree 7KB
toc.doctree 4KB
resources.html 164KB
testing.html 77KB
cookbook.html 59KB
interacting.html 56KB
tutorial.html 38KB
serialization.html 36KB
fields.html 35KB
index.html 30KB
toc.html 24KB
non_orm_data_sources.html 23KB
genindex.html 22KB
authentication.html 20KB
authorization.html 19KB
caching.html 19KB
validation.html 15KB
geodjango.html 14KB
settings.html 12KB
throttling.html 12KB
api.html 12KB
contributing.html 12KB
tools.html 11KB
paginator.html 11KB
debugging.html 11KB
content_types.html 10KB
who_uses.html 8KB
bundles.html 8KB
compatibility_notes.html 6KB
py-modindex.html 4KB
search.html 3KB
basic.html 846B
list.html 71B
detail.html 71B
objects.inv 2KB
jquery.js 70KB
searchindex.js 37KB
searchtools.js 14KB
underscore.js 8KB
doctools.js 7KB
sidebar.js 5KB
LICENSE 1KB
Makefile 3KB
environment.pickle 190KB
PKG-INFO 5KB
file.png 392B
minus.png 199B
plus.png 199B
resources.py 92KB
fields.py 32KB
serializers.py 19KB
test.py 18KB
authentication.py 17KB
authorization.py 7KB
paginator.py 7KB
api.py 7KB
conf.py 7KB
validate_jsonp.py 6KB
0001_initial.py 6KB
0002_add_apikey_index.py 5KB
throttle.py 4KB
validation.py 4KB
resources.py 2KB
cache.py 2KB
fields.py 2KB
exceptions.py 2KB
mime.py 2KB
models.py 2KB
resources.py 2KB
setup.py 1KB
http.py 1KB
共 175 条
- 1
- 2
资源评论
挣扎的蓝藻
- 粉丝: 13w+
- 资源: 15万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功