DJANGO REST 框架django-restit安装配置路由代码

2024-06-2417:51:15后端程序开发Comments819 views字数 3483阅读模式

django-restit使构建用于任何 Web 或应用程序开发的 rest 框架变得容易,可以采用任何模型,并通过继承RestModel将它们转换为REST模型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

安装文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

pip install django-restit

配置文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

将“restit”添加到 DJANGO 应用程序。
添加中间件文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

'rest.middleware.SessionMiddleware''rest.middleware.GlobalRequestMiddleware''rest.middleware.CorsMiddleware'

在 urls.py 中将 url(r'^rpc/', include('rest.urls')) 添加到路由中文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

class ExampleTODO(models.Model, RestModel):    your standard django fields  ...

创建一个rpc.py文件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

# decorator that defines your routes, note the app_name is assumed@rd.url('todo')@rd.url('todo/<int:pk>')@login_requireddef on_rest_todo(request, pk=None):    return ExampleTODO.on_rest_request(request, pk)

这将为你提供一个完整的 Rest 接口进入你的 Django 模型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

定义如何返回模型对象文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

class ExampleTODO(models.Model, RestModel):    class RestMeta:        GRAPHS = {            "default": {        "exclude":["priority"],                "graphs":{                    "user":"default"                }            },            "list": {        "fields":["id", "name", "priority"]            }        }    user = models.ForeignKey(User, related_name="+")  name = models.CharField(max_length=80)  description = models.TextField(max_length=80)  priority = models.IntegerField(default=0)

在上面可以定义“图形”,控制返回的内容。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

访问http://localhost:8000/rpc/rest_example/todo 将默认为“列表”图并返回如下文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

{    "status": true,    "size": 25,    "count": 2,    "data": [        {            "id": 1,            "name": "test 1",            "priority": 1,      "user": 21        },        {            "id": 2,            "name": "test 2",            "priority": 1,      "user": 21        },    ]}

因此,如果我们去 http://localhost:8000/rpc/rest_example/todo?graph=default文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

{    "status": true,    "size": 25,    "count": 2,    "data": [        {            "id": 1,            "name": "test 1",            "description": "this is test 1",      "user": {        "id": 21,        "username": "jsmith",        "display_name": "TEST USER 5",        "avatar": "http://localhost:8000/media/ax1fg.png"      }        },        {            "id": 2,            "name": "test 2",            "description": "this is test 2",      "user": {        "id": 21,        "username": "jsmith",        "display_name": "TEST USER 5",        "avatar": "http://localhost:8000/media/ax1fg.png"      }        },    ]}

RestModel
RestModel 类是一个帮助程序类,可帮助现有模型适应 REST 框架。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

API可以覆盖的关键方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

def on_rest_get(self, request):        # override the get method        return self.restGet(request, graph)
    def on_rest_post(self, request):        # override the post method        return self.restGet(request, graph)         def on_rest_pre_save(self, request):        # called before instance saved via rest, no return        pass            def on_rest_created(self, request):        # called after new instance created via rest, no return        pass
    def on_rest_saved(self, request):        # called after old instance saved via rest, no return        pass
    def on_rest_delete(self, request):        can_delete = getattr(self.RestMeta, "CAN_DELETE", False)        if not can_delete:            return self.restStatus(request, False, error="deletion not allowed via rest for this model.")        self.delete()        return GRAPH_HELPERS.restStatus(request, True)
    @classmethod    def onRestCanSave(cls, request):        # override to validate permissions or anything if this can create or save this instance        return True            @classmethod    def on_rest_list_filter(cls, request, qset):        # override on do any pre filters, returns new qset        # qset = qset.filter(id__gt=50)        return qset            @classmethod    def on_rest_list(cls, request, qset=None):        # normally you would override on_rest_list_filter, but you could override this        return cls.restList(request, qset)        @classmethod    def on_rest_create(cls, request, pk=None):        obj = cls.createFromRequest(request)        return obj.restGet(request)

创建和保存
createFromRequest(request, **kwargs)- 这允许您传递一个请求对象(通常是一个帖子)并从该请求创建一个新模型。还可以在请求后传入任何覆盖字段。
MyModel.createFromRequest(request, owner=request.user)
saveFromRequest(request, **kwargs)- 这允许传递一个请求对象(通常是一个帖子)并将该请求中的数据保存到模型中。
其他帮助程序方法
getFromRequest(cls, model_name)- @classmethod - 尝试从请求中获取模型实例,检查 REQUEST 参数中的 classname 和 classname+ “_id”。
restGetModel(app_name, model_name)- @staticmethod - 按应用和模型名称获取模型类.
restGetGenericModel(self, fieldname)- 按应用和模型名称获取模型类。
restGetGenericRelation(self, fieldname)- 按应用和模型名称获取模型类。
返回 JSON 图
通过设置适当的 RestMeta 属性,可以很容易地从模型自动构建图形。
getGraph(name)- @classmethod - 指定要返回的图形的名称。
RestMeta
这是添加到模型中以定义图形的 Property 类。默认情况下,图形将仅返回字段,而不会递归到外部模型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

参考文档文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html

https://pypi.org/project/django-restit/
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/64226.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/64226.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定