Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
- Code snippets are always associated with a creator.
- Only authenticated users may create snippets.
- Only the creator of a snippet may update or delete it.
- Unauthenticated requests should have full read-only access.
到目前为止,我们的API对编辑或者删除snippets没有任何约束。我们希望有一些更高级的方法来确保:
- Code snippets 通常关联一个创建者。
- 只有授权的用户才可以创建 snippet。
- 只有snippet 的创建者才有权限去更新和删除它。
- 未授权的request只能可读。
Adding information to our model
给模型添加信息
We're going to make a couple of changes to our Snippet
model class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
Add the following two fields to the Snippet
model in models.py
.
我们将会对Snippet数据库模型做些改动。首先,添加一些条目,一个为代表snippet的创建者,另一个为存储高亮 HTML 代码。编辑models.py如下:
owner = models.ForeignKey('auth.User', related_name='snippets') highlighted = models.TextField()
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments
code highlighting library.
We'll need some extra imports:
我们需要确保当保存模型时,我们能够同时保存 highlighted 条目,需要 import pygments 库。
from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight
And now we can add a .save()
method to our model class:
现在给模型添加 .save 方法:
def save(self,*args,**kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and'table'orFalse options = self.title and{'title': self.title}or{} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True,**options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args,**kwargs)
When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
删除之前的数据库,重新创建一个,正常情况下我们可以做数据库改动而不是直接删除 。
rm tmp.db
python ./manage.py syncdb
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser
command.
为了测试 API ,你可能会创建一些不同的用户,快速的办法就是使用命令 createsuperuser:
python ./manage.py createsuperuser
Adding endpoints for our User models
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In serializers.py
add:
现在我们获得了一些用户,我们最后将他们添加到API中。创建一个新的序列化器,在 serializers.py 加入:
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True)
classMeta: model =User fields =('id','username','snippets')
Because 'snippets'
is a reverse relationship on the User model, it will not be included by default when using theModelSerializer
class, so we needed to add an explicit field for it.
由于 User 和 snippets 是逆映射的关系,使用 ModelSerializer 类默认不会包含 sinippets, 所以我们需要显示地将其加入到模型中。
We'll also add a couple of views to views.py
. We'd like to just use read-only views for the user representations, so we'll use the ListAPIView
and RetrieveAPIView
generic class based views.
我们需要稍微更改 views.py,我们希望那些 user reprenstations 只有读的权限,我们使用泛型类 ListAPIView 和 RetrieveAPIView。
from django.contrib.auth.models import User class UserList(generics.ListAPIView): queryset =User.objects.all() serializer_class =UserSerializer class UserDetail(generics.RetrieveAPIView): queryset =User.objects.all() serializer_class =UserSerializer
Make sure to also import the UserSerializer
class
确保导入了 UserSerializer 类
from snippets.serializers import UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in urls.py
.
更改URL配置文件 urls.py 如下:
url(r'^users/$', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
Associating Snippets with Users
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
现在,如果我们要创建一个 snippet ,还没有方法将其关联到 user 。user 不会作为序列化被发送,而是一个request的属性。
The way we deal with that is by overriding a .pre_save()
method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.
通过在snippet的视图函数中重载 pre_save() 方法来达到关联到user的目的,它允许我们处理任何隐藏在request或者reques URL中的信息。
On both the SnippetList
and SnippetDetail
view classes, add the following method:
在 SnippetList 和 SnippetDetail 视图类中,添加如下方法:
def pre_save(self, obj): obj.owner = self.request.user
Updating our serializer
Now that snippets are associated with the user that created them, let's update our SnippetSerializer
to reflect that. Add the following field to the serializer definition in serializers.py
:
现在随着创建 snippets ,也将其关联到 user中了,更新 SnippetSerializer 来反映这种关联。在serializers.py中添加:
owner = serializers.Field(source='owner.username')
Note: Make sure you also add 'owner',
to the list of fields in the inner Meta
class.
注意:确保添加 owner 到内部类中。
This field is doing something quite interesting. The source
argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
ower 域会做一些有趣的事情。 source 参数控制哪一个属性被用来产生这个filed。
The field we've added is the untyped Field
class, in contrast to the other typed fields, such as CharField
, BooleanField
etc... The untyped Field
is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
owner 是一个没有类型的域,不想其他的域,如 ChairField, booleanField等。这些无类型的域通常只是只读的,只是用作序列化的表示,并且更新模型实例时也不会被逆序列化。
Adding required permissions to views
Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.
REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly
, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
现在已经就将 snippet 和 user 关联起来了,我们想确保只有授权的user才能够有权限来进行创建,更新和删除操作。
REST 框架包含了很多权限类,我们可用其来定制权限。 IsAuthenticatedOrReadOnly 类可以确保认证的request有读写权限,而没有被认证的只有读的权限。
First add the following import in the views module
首先导入模块
from rest_framework import permissions
Then, add the following property to both the SnippetList
and SnippetDetail
view classes.
然后,将其添加到 SnippetList 和 SnippetDetail 视图类中
permission_classes =(permissions.IsAuthenticatedOrReadOnly,)
Adding login to the Browsable API
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
如果你打开一个浏览器访问 API, 你会发现你不再能够创建一个snippet了。为了能够创建,我们必须作为一个user去登录。
We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file.
Add the following import at the top of the file:
我们可以给 浏览器访问的 API 添加一个登录视图,在urls.py文件中,加入如下代码:
from django.conf.urls import include
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
在文件末尾,为浏览器 API 包含登录和注销视图。
urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),)
The r'^api-auth/'
part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework'
namespace.
r'^api-auth/'可以随便更改成你想的URL,唯一的约束是包含的URLs必须使用'rest_framework'命名空间。
Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.
Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.
现在,如果你再次打开浏览器,然后你会在页面的右上边看到一个'login'链接。如果你是以一个之前创建的用户登录,你就可以创建一个snippet实例。
一旦你创建了一些 snippet 实例,使用'/users/' URL,你会看到一个列表,在user的'snippets'域关联了snippet pk。
Object level permissions
Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.
To do that we're going to need to create a custom permission.
事实上,我们希望任何人可以访问所有的snippet模型实例,并且只有snippet的创建者可以更改和删除它。为了达到目的,我们需要创建一个自定义权限。
In the snippets app, create a new file, permissions.py
在snippets app 中,创建一个新的文件,名为 permissions.py
from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user
Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes
property on theSnippetDetail
class:
现在,我们可以添加自定义权限到实例中,编辑SnippetDetail类的 permission_classes 属性:
permission_classes =(permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,)
Make sure to also import the IsOwnerOrReadOnly
class.
from snippets.permissions import IsOwnerOrReadOnly
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
现在,如果你再次打开浏览器,你会发现只有作为snippet的创建者才有'DELETE'和'PUT'方法了。
Authenticating with the API
Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication
andBasicAuthentication
.
由于我们对API设置了权限,所以我们需要认证想要编辑snippet的request。我们还没有建立任何的授权类,默认是必须的,授权类是 SessionAuthentication 和 BasicAuthentication。
When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
当我们通过浏览器与 API 交互时,我们可以登录,而且浏览器会话会为request提供需要的授权。
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
如果我们使用程序和API交互,我们就需要在每一个request中显示地提供认证。
If we try to create a snippet without authenticating, we'll get an error:
如果我们使用不带认证信息的request,就会收到一个错误信息:
curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123"
{"detail":"Authentication credentials were not provided."}
We can make a successful request by including the username and password of one of the users we created earlier.
只有在request中包含之前创建的user的用户名和密码,就会request成功:
curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password {"id":5,"owner":"tom","title":"foo","code":"print 789","linenos": false,"language":"python","style":"friendly"}
Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
我们现在为 Web API 设置细致的权限。在第五章,我们会通过创建一个HTML端点来看到怎样将它们绑在一起,然后通过使用超链接改善它们的内聚效果。