【问题标题】:Is it possible to send a request to django rest api to run a script?是否可以向 django rest api 发送请求以运行脚本?
【发布时间】:2021-11-01 07:40:09
【问题描述】:

我安装了 Django 和 Django Rest Api。我想向rest api发送一些数据。 Rest api 将获取数据并使用此数据运行脚本并获得结果。然后把这个结果发回给我。 不会有数据库使用。

这样,请求:http://testerapi.com:8000/search?q=title:xfaster564CertVal9body:A%22&fl=id 响应:{验证:真}

有可能吗?

【问题讨论】:

  • 你想从请求中获取脚本还是只获取某些参数?
  • 请求者将数据发送到api。 Api 会将数据提供给服务器上的脚本。脚本将获取数据并生成新数据并将其发送回 api。 Api 会将新数据发送回请求者。

标签: json django django-rest-framework


【解决方案1】:

是的,这是可能的!但我会尝试用 基于 API 函数的视图来回应。

假设我们在调用 API(GETPOST)时调用的工作函数位于 utilities.py 文件中,即 models.pyserializers.pyviews.py

utilities.py

def my_worker(a, b=0, c=0):
    # do something with a, b, c
    return a + b + c > 10

models.py

from datetime import datetime
class User(object):
    def __init__(self, email, name, created = None):
        self.email = email
        self.name = name
        self.created = created or datetime.now()

serializers.py 我使用简单的序列化器,但我认为 ModelSerializer 更好

from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    # initialize fields
    email = serializers.EmailField()
    name = serializers.CharField(max_length = 200)
    created = serializers.DateTimeField()

views.py

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt # Allow request without csrf_token set
from rest_framework.decorators import api_view

from .models import User
from .serializers import UserSerializer
# Import my_worker from .utilities
from .utilities import my_worker

@csrf_exempt
@api_view('GET')  # Only get request is allowed
def user_worker(request, a, b, c):
    """
    Do something with 
    """
    if request.method == 'GET':
        # Do some stuff
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        # Call the utilities script here
        result = my_worker(a, b, c)
        if result:  # a+b+c > 10
            return JsonResponse({"validation": "true"}, safe=False)
        else:
            return JsonResponse({"validation": "false"}, safe=False)

请注意,我不使用 UserSerializer,而是在示例中显示它。 然后你可以执行一个更复杂的函数(这里是my_worker)。 根据您的需要进行调整。

【讨论】:

  • 完美答案。多谢!那就是我一直在寻找的东西。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-07-17
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多