使用DRF在RESTful API中实现RPC [英] Implementing RPC in RESTful API using DRF
问题描述
我正在使用Django Rest框架来呈现一个RESTful API。我有一个路由器/ viewset / serializer为 Person
资源创建一个端点:
I am using the Django Rest Framework to present a RESTful API. I have a router/viewset/serializer creating an endpoint for a Person
resource:
/api/People/<id>/
我想要一些触发方式对该资源的非幂等动作(例如 send-email-to
)。我不得不重新做很多路由/序列化基础设施的一个想法是向序列化程序添加一个只写布尔字段:
I would would like some way of triggering a non-idempotent action on this resource (for example send-email-to
). One idea I had to do so without having to re-do a lot of the routing/serialization infrastructure was to add a write-only boolean field to the serializer:
class PersonSerializer(serializers.ModelSerializer):
send_email = serializers.BooleanField(write_only=True, required=False)
然后向模型添加一个只写属性:
and then add a write-only property to the model:
class Person(models.Model):
...
def do_send_email(self, value):
# We also need to check the object is fully constructed here, I think
if do_send_email:
...
send_email = property(fset=do_send_email)
然后我可以将 PATCH
到有效载荷 send_email = True
的终点。
and then I can PATCH
to the end point with the payload of send_email=True
.
这是使用REST API完成类似RPC的功能的最佳方式吗?这是在DRF中完成此项工作的最佳方式吗?理想情况下,我想尽可能少地解决这个问题(即查看解决方案的代码行数)。 send-email-to
不是我想要处理的唯一操作。
Is this the best way to accomplish an RPC like function using a REST API? Is this the best way to accomplish this in DRF? Ideally I would like to solve this problem having to-implement as little as possible (ie see how few lines of code the solution is). send-email-to
is not the only action that I would like to handle.
推荐答案
您可以使用 drf提供的额外动作。在你的情况下,特别地,我会使用@detail_route。
You can use the extra actions drf provides. In your case especifically, I would use @detail_route.
这样的东西:
@detail_route(methods=['post'])
def send_mail(self, request, pk=None):
send_mail_to(pk) # Write here your email function.
您必须在Person视图集中定义此函数,因此为了调用此函数,您将必须在 / people / {person_id} / send_mail 下 POST ,其中 {person_id} 是该人的主要关键。
You have to define this function within the Person viewset so, in order to call this function, you will have to POST at /people/{person_id}/send_mail where {person_id} is the primary key for the person.
作为附注,由于此功能是从客户端同步调用的,可能需要一段时间才能回答,我建议您使用芹菜。这将允许您异步调用send_mail_to函数,而不会延迟用户响应。
As a side note, since this function are synchronously called from the client and it may take a while to answer, I would recommend you the use of celery. This will allow you to call the send_mail_to function asynchronously without delaying the user response.
这篇关于使用DRF在RESTful API中实现RPC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!