一. 什么是RESTful
- REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
- REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行标识,客户端应用通过URL来获取资源的表征,获得这些表征致使这些应用转变状态
- 所有的数据,不过是通过网络获取的还是操作(增删改查)的数据,都是资源,将一切数据视为资源是REST区别与其他架构风格的最本质属性
- 对于REST这种面向资源的架构风格,有人提出一种全新的结构理念,即:面向资源架构(ROA:Resource Oriented Architecture)
二.简单示例
Django REST Framework框架是一个功能强大且灵活的工具包,用于构建Web API。让我们看一个使用REST框架构建一个简单的模型支持的API的快速示例。
我们将创建一个读写API,用于访问项目用户的信息。
①Installation/安装
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support
...or clone the project from github.
git clone https://github.com/encode/django-rest-framework
Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = (
...
'rest_framework',
)
如果您打算使用可浏览的API,您可能还需要添加REST框架的登录和注销视图。 将以下内容添加到根urls.py文件中。
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls'))
]
②REST框架API的任何全局设置都保存在名为REST_FRAMEWORK的单个配置字典中。 首先将以下内容添加到settings.py模块:
INSTALLED_APPS = (
... # Make sure to include the default installed apps here.
'rest_framework',
)
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS.
We're ready to create our API now. Here's our project's root urls.py module:
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
ps:与后台进行交互
def api_test(request): data = json.loads(request.POST.get('data')) print(data) serializer_obj = rest_serializer.UserSerializer(data=data) if serializer_obj.is_valid(): serializer_obj.save() serializer_obj return render(request,"crm/api-test.html",locals())
Here you go!
You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.