api
Posted 羊小羚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了api相关的知识,希望对你有一定的参考价值。
virtualenv
is a tool to create isolated Python environments.
建立一个新的环境
Before we do anything else we‘ll create a new virtual environment, using virtualenv. This will make sure our package configuration is kept nicely isolated from any other projects we‘re working on.
# 创建一个隔离的空间 virtualenv env source env/bin/activate
Now that we‘re inside a virtualenv environment, we can install our package requirements.
# 安装所需模块 pip install django pip install djangorestframework pip install pygments # We‘ll be using this for the code highlighting
Note: To exit the virtualenv environment at any time, just 键入deactivate
. For more information see the virtualenv documentation.
入门
摘要:入门部分创建了一个Django项目。
Okay, we‘re ready to get coding. To get started, let‘s create a new project to work with.
# Linux下创建一个项目 cd ~ django-admin.py startproject tutorial cd tutorial [email protected]:~$ tree tutorial tutorial ├── manage.py └── tutorial ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py 1 directory, 5 files
Once that‘s done we can create an app that we‘ll use to create a simple Web API.
# 创建一个app python manage.py startapp snippets
We‘ll need to add our new snippets
app and the rest_framework
app to INSTALLED_APPS
. Let‘s edit the tutorial/settings.py
file:
# 配置文件 INSTALLED_APPS = ( ... ‘rest_framework‘, ‘snippets.apps.SnippetsConfig‘, )
Please note that if you‘re using Django <1.9, you need to replace snippets.apps.SnippetsConfig
with snippets
.
Okay, we‘re ready to roll.
创建一个可以使用的model
For the purposes of this tutorial we‘re going to start by creating a simple Snippet
model that is used to store code snippets. Go ahead and edit the snippets/models.py
file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
# models.py
from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default=‘‘) code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default=‘python‘, max_length=100) style = models.CharField(choices=STYLE_CHOICES, default=‘friendly‘, max_length=100) class Meta: ordering = (‘created‘,) #排序字段
We‘ll also need to create an initial migration for our snippet model, and sync the database for the first time.
# 初始化数据库 python manage.py makemigrations snippets python manage.py migrate
创建一个Serializer类
The first thing we need to get started on our Web API is to provide a way of 序列化和反序列化 the snippet instances into representations such as json
. We can do this by declaring serializers that work very similar to Django‘s forms. Create a file in the snippets
directory named serializers.py
and add the following.
#serializers.py from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={‘base_template‘: ‘textarea.html‘}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=‘python‘) style = serializers.ChoiceField(choices=STYLE_CHOICES, default=‘friendly‘) def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get(‘title‘, instance.title) instance.code = validated_data.get(‘code‘, instance.code) instance.linenos = validated_data.get(‘linenos‘, instance.linenos) instance.language = validated_data.get(‘language‘, instance.language) instance.style = validated_data.get(‘style‘, instance.style) instance.save() return instance
The first part of the serializer class defines the fields that get serialized/deserialized. The create()
and update()
methods define how fully fledged instances are created or modified when calling serializer.save()
A serializer class is very similar to a Django Form
class, and includes similar validation flags on the various fields, such as required
, max_length
and default
.
The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. 上面的 {‘base_template‘: ‘textarea.html‘}
flag 相当于 using widget=widgets.Textarea
on a Django Form
class. This is particularly useful for controlling how the browsable API should be displayed, as we‘ll see later in the tutorial.
实际上,我们也可以使用 the ModelSerializer
class 来节省一些时间 , as we‘ll see later, but for now we‘ll keep our serializer definition explicit.
使用Serializers串行器
摘要:这一部分都是在python shell下操作的。
Before we go any further we‘ll familiarize ourselves with using our new Serializer class. Let‘s drop into the Django shell.
# python shell下 python manage.py shell
Okay, once we‘ve got a few imports out of the way, let‘s create a couple of code snippets to work with.
# from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code=‘foo = "bar"\n‘) #实例化一个对象并填写code字段,然后保存。 snippet.save() snippet = Snippet(code=‘print "hello, world"\n‘) snippet.save()
We‘ve now got a few snippet instances to play with. Let‘s take a look at serializing one of those instances.
# serializer = SnippetSerializer(snippet) #snippet是类Snippet的对象
serializer.data # {‘id‘: 2, ‘title‘: u‘‘, ‘code‘: u‘print "hello, world"\n‘, ‘linenos‘: False, ‘language‘: u‘python‘, ‘style‘: u‘friendly‘}
At this point we‘ve translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json
.
# content = JSONRenderer().render(serializer.data) content # ‘{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}‘
反序列化是类似的. First we parse a stream into Python native datatypes...
# from django.utils.six import BytesIO stream = BytesIO(content) data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance.
# serializer = SnippetSerializer(data=data) serializer.is_valid() # True serializer.validated_data # OrderedDict([(‘title‘, ‘‘), (‘code‘, ‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]) serializer.save() # <Snippet: Snippet object>
请注意,API与forms何其相似. 相似性甚至更加明显 when we start writing views that use our serializer.
我们也可以实例化 querysets 而不是 model instances. 为了做到这一点, 我们仅仅添加 a many=True
flag to the serializer arguments.
# serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data # [OrderedDict([(‘id‘, 1), (‘title‘, u‘‘), (‘code‘, u‘foo = "bar"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 2), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 3), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)])]
使用ModelSerializers
Our SnippetSerializer
class is replicating a lot of information that‘s also contained in the Snippet
model. 如果我们可以保持我们的代码更简洁,那将是很好的。
与Django提供Form
类和ModelForm
类的方式相同,REST框架包括Serializer
类和ModelSerializer
类。
让我们来看看使用ModelSerializer
类重构我们的serializer。再次打开文件 snippets/serializers.py
, and replace the SnippetSerializer
class with the following.
# class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = (‘id‘, ‘title‘, ‘code‘, ‘linenos‘, ‘language‘, ‘style‘)
serializers 有一个很好的属性是你可以检查一个serializer instance的所有字段, by printing its representation. Open the Django shell with python manage.py shell
, then try the following:
# from snippets.serializers import SnippetSerializer serializer = SnippetSerializer() print(repr(serializer)) # SnippetSerializer(): # id = IntegerField(label=‘ID‘, read_only=True) # title = CharField(allow_blank=True, max_length=100, required=False) # code = CharField(style={‘base_template‘: ‘textarea.html‘}) # linenos = BooleanField(required=False) # language = ChoiceField(choices=[(‘Clipper‘, ‘FoxPro‘), (‘Cucumber‘, ‘Gherkin‘), (‘RobotFramework‘, ‘RobotFramework‘), (‘abap‘, ‘ABAP‘), (‘ada‘, ‘Ada‘)... # style = ChoiceField(choices=[(‘autumn‘, ‘autumn‘), (‘borland‘, ‘borland‘), (‘bw‘, ‘bw‘), (‘colorful‘, ‘colorful‘)...
Notes that ModelSerializer
classes don‘t do anything particularly magical, they are simply a shortcut for creating serializer classes:
- An automatically determined set of fields.
- Simple default implementations for the
create()
andupdate()
methods.
使用我们的Serializer编写正常的Django视图
让我们来看看该如何使用新的Serializer类来编写一些API视图。目前我们不会使用任何REST框架的其他功能,我们只编写一些常规的Django视图函数。
编辑 snippets/views.py
文件,并添加以下内容。
# from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer
The root of our API 将是一个视图,它支持列出所有现有的片段,或创建一个新的片段。
# @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == ‘GET‘: snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == ‘POST‘: data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
请注意,因为我们希望能够从不具有CSRF token的客户端以POST方法访问此视图函数,因此我们需要用csrf_exempt标记视图
。这不是你通常想要做的事情,REST框架视图实际上使用比这更有明显的行为,但它现在将用于我们的目的。
我们还需要一个与 an individual snippet对应的视图,并可用于检索,更新或删除the snippet。
# @csrf_exempt def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == ‘GET‘: serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == ‘PUT‘: data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == ‘DELETE‘: snippet.delete() return HttpResponse(status=204)
最后我们需要把这些视图函数连接起来。创建snippets/urls.py
文件:
# from django.conf.urls import url from snippets import views urlpatterns = [ url(r‘^snippets/$‘, views.snippet_list), url(r‘^snippets/(?P<pk>[0-9]+)/$‘, views.snippet_detail), ]
我们还需要在tutorial/urls.py
文件中连接根urlconf ,以包含我们的片段应用程序的URL。
# from django.conf.urls import url, include urlpatterns = [ url(r‘^‘, include(‘snippets.urls‘)), ]
It‘s worth noting that there are a couple of edge cases we‘re not dealing with properly at the moment. If we send malformed json
, or if a request is made with a method that the view doesn‘t handle, then we‘ll end up with a 500 "server error" response. Still, this‘ll do for now.
测试我们在Web API上的第一次尝试
现在我们可以启动一个运行我们的代码片段的示例服务器。
退出shell...
quit()
...and start up Django‘s development server.
# python manage.py runserver Validating models... 0 errors found Django version 1.11, using settings ‘tutorial.settings‘ Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
在另一个终端窗口中,我们可以测试服务器。
我们可以使用curl或httpie来测试我们的API 。Httpie是用Python编写的用户友好的http客户端。我们来安装它。
您可以使用pip安装httpie:
# pip install httpie
最后,我们可以得到所有片段的列表:
# http http://127.0.0.1:8000/snippets/ HTTP/1.1 200 OK ... [ { "id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly" }, { "id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly" } ]
或者我们可以通过引用其id来获取特定的代码段:
# http http://127.0.0.1:8000/snippets/2/ HTTP/1.1 200 OK ... { "id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly" }
同样,您可以通过在网络浏览器中访问这些URL来显示相同??的json。
以上是关于api的主要内容,如果未能解决你的问题,请参考以下文章
Android 插件化VirtualApp 源码分析 ( 目前的 API 现状 | 安装应用源码分析 | 安装按钮执行的操作 | 返回到 HomeActivity 执行的操作 )(代码片段
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段