Django和REST API服务于基于计算的请求 [英] Django and REST API to serve calculation-based requests

查看:83
本文介绍了Django和REST API服务于基于计算的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中编写了一个机器学习应用程序,因此用户可以以表格形式指定一些参数并训练模型。训练完模型后,我想提供以下请求:

I wrote a machine learning application in Django so a user can specify in a form some parameters and train a model. Once the model is trained, I want to serve requests like:

curl http://localhost:8000/.../?model_input='XYZ' 

我希望Django在给定输入XYZ的情况下返回模型的输出。我从Tastypie或REST框架看到的每个示例都是根据查询集建立响应的。如果响应不是查询集的结果而是内存中纯计算的结果,我该如何进行?在我的情况下,响应是矩阵(训练模型)乘以矢量(输入)的结果,并且此结果未存储在表中。

and I want Django returns the output of the model given the input XYZ. Every example I saw from Tastypie or REST framework builds its response from a queryset. How can I proceed if the response is not the result of a queryset but the result of in-memory pure calculation? In my case, the response is the result of a matrix multiplication (the trained model) by a vector (the input) and this result is not stored in a table.

建议如何处理此类请求?
任何帮助将不胜感激。
问候,
Patrick

What is the recommended way to manage such requests? Any help is greatly appreciated. Regards, Patrick

推荐答案

Django REST Framework不需要模型源或查询集,尽管在与其中任何一个一起工作时,它的确表现最佳。 它确实提供了基本的 Serializer 为此,以及基本的 APIView 允许在基于Django类的标准视图之上使用内容协商。

Django REST Framework does not require a model source, or a queryset, though it does perform its best when working with either of them. It does provide a basic Serializer for this reason, as well as basic APIView classes to allow for content negotiation to be used on top of standard Django class-based views.

您最有可能除非您要序列化结果对象,否则不需要使用 Serializer Serializer 的另一个常见用途是验证传入的数据并将其转换为预期的格式。

You most likely won't need to use the Serializer unless you were looking to serialize the results object. The other common use for a Serializer is to validate the incoming data and convert it to an expected format.

如果您只是想返回一个基本值(您没有指定矩阵相乘的结果实际上可能是什么),那么即使仅使用基本视图也要比手动完成所有步骤都要先进。 Django REST Framework提供的 Response 对象允许您返回任意数据,并将其自动转换为可比较的JSON或XML表示形式。您无需调用 json.dumps 或将数据强制转换为特定的表示形式, Response 对象即可完成所有操作您。

If you were just looking to return a basic value (you didn't specify what "the result of a matrix multiplication" actually could be), then even just using the basic views is a step up from doing it all manually. The Response object that Django REST Framework provides allows you to return arbitrary data and have it be converted into a comparable JSON or XML representation, automatically. You never need to call json.dumps or coerce the data into a specific representation, the Response object does it all for you.

from rest_framework.response import Response
from rest_framework import serializers, views

class IncredibleInputSerializer(serializers.Serializer):
    model_input = serializers.CharField()

class IncredibleView(views.APIView):

    def get(self, request):
        # Validate the incoming input (provided through query parameters)
        serializer = IncredibleInputSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # Get the model input
        data = serializer.validated_data
        model_input = data["model_input"]

        # Perform the complex calculations
        complex_result = model_input + "xyz"

        # Return it in your custom format
        return Response({
            "complex_result": complex_result,
        })

在上面的示例中,我们创建了一个 IncredibleInputSerializer 来验证 model_input 查询参数,以确保该参数包含在请求中。这是一个非常基本的示例,因为Django REST Framework支持对输入进行其他操作,例如将其转换为数字或验证它是否符合特定格式。

In the example above, we create a IncredibleInputSerializer that validates the model_input query parameter to make sure that it is included in the request. This is a very basic example, as Django REST Framework supports doing additional things to the input, like converting it to a number or validating that it conforms to a specific format.

当然,如果您需要序列化一个对象或对象列表,这就是Django REST Framework的优势。它不必是模型对象,它可以是具有属性或方法来获取数据的对象,甚至可以是基本字典,并且Django REST Framework应该能够为您序列化它。

Of course, if you need to serialize an object or list of objects, that's where Django REST Framework excels. It doesn't have to be a model object, it can be an object with attribute or methods to get the data, or even just a basic dictionary, and Django REST Framework should be able to serialize it for you.

这篇关于Django和REST API服务于基于计算的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆