python - django 编写接口的问题
阿神
阿神 2017-04-17 17:33:48
0
2
462

最近做一个django的项目,和其他项目做对接,接口化。

有些事情不明,
1、用django,写url,views这种方式写接口,行吗。

2、django中有rest_framework 这种rest接口的形式,我粗略看了下,不太明白serializers这个什么作用

3、django原声写url,views的方式去写接口,和用rest_framework有什么区别。

为什么要用rest呢。

小白,sorry,望大神回答疑惑。

阿神
阿神

闭关修行中......

reply all(2)
小葫芦

Use Django to write urls and views to write interfaces, is that okay?

OK. Because the so-called interface is also an ordinary URL.


Django has rest_framework, a form of rest interface. I took a quick look at it, but I don’t quite understand what serializers do.

See the explanation on the official website:

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. -- via http://www.django-rest-framework.org/api...

In the background, we use ORM to process data. In order to facilitate the expression of business logic, the data at this time exists in the form of Python objects. However, in the process of front-end and back-end communication, native objects are not allowed to be transmitted, and all data needs to be converted into pure character formats, such as XML and JSON. This involves the issue of mutual conversion between a Python object and a character stream. Serializers are the bridge between them.


What is the difference between writing url and interface using views in django and using rest_framework.

No difference. But rest-framework encapsulates a lot of functions for you, which can be used out of the box, making your code more concise. This is especially obvious when the number of interfaces is particularly large.


Why use rest?

Reference http://stackoverflow.com/questions/53200...


Also, hats off to the author of DRF. Although he is no longer following this project (http://www.django-rest-framework.org/top...), we will never forget the convenience he and his team brought to developers.

黄舟

Our approach is to write an api decorator, and then use it to annotate the method on the View. The method returns a dict or directly throws an exception. In this way, permission control can also be placed on the decorator. In the end, the actual API only needs to be written like this:

class ApiView(BaseApiView):
    @api
    def login(username,password):
        pass
    @api
    def register(phone,password,email):
        pass
    @asapi(role="admin")
    def sysinfo():
        pass

The BaseApiView and api in the code are what you need to implement. Here is just a simple pseudo code.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template