gpt4 book ai didi

django - 在 Django Rest 框架中发布请求处理

转载 作者:行者123 更新时间:2023-12-03 21:24:43 24 4
gpt4 key购买 nike

我正在使用 Django Rest Framework,目前从我们使用 Get 请求的后端提取一些数据,但由于 URL 限制很高,我们计划实现 Post 请求。要做到这一点,首先必须使后端 Django Rest API 可用于处理发布请求。

我是 Django 新手,我在代码中没有找到 post 或 get 方法,我只能说我们正在使用 View 集,我尝试使用“@detail_route(methods=['post'])”,但这没有t 工作,我在这里做错了什么?

class XViewSet(viewsets.ViewSet):
renderer_classes = ''

def retrieve(self, request, pk=None):
try:
pk = int(pk)
except ValueError:
raise InvalidParameterError(parameter_name='id', invalid_value=pk)

queryset = models.X.objects.all()
x = get_object_or_404(queryset, pk=pk)

pipelines = request.query_params.getlist('pipeline[]')

callsets =

callset_ids =

serializer = serializers.XSerializer(x, context={'request': request})

requested_samples = [z[1:] for z in request.query_params.getlist('s')]

filtered_calls = []
serialized_data = serializer.data

unfiltered_calls = serialized_data.get('calls')
if unfiltered_calls:
for serialized_calls in unfiltered_calls:
if serialized_calls['callset'] in callset_ids:
unfiltered_calls = serialized_calls['data']

for call in unfiltered_calls:
if call['y'] in requested_y:
filtered_calls.append(call)

break

serialized_data['calls'] = filtered_calls

return Response(serialized_data, status=status.HTTP_200_OK)

def list(self, request):

qp = self.request.query_params

validated_qp =

# generate the query
query_object =
query =

# execute the query
cursor = connections['default'].cursor()
cursor.execute(query)

qs = utils.dictfetchall(cursor)

# sanitize query results
if 't' in validated_qp:
return_data =
else:
for x in qs:
if 'calls' in x:

x['calls'] =
else:
x['calls'] = {}

return_data =

resp = Response(return_data, status=status.HTTP_200_OK)

if validated_qp.get(''):
resp['content-disposition'] =

return resp

最佳答案

您可以使用 class-based views处理要求,

from rest_framework.views import APIView


class MyAPI(APIView):
def get(selfself, request):
# do stuff with get
return Response(data="return msg or data")

def post(self, request):
post_data = request.data
# do something with `post_data`
return Response(data="return msg or data")

更新:使用 View 集
ViewSet类(class)提供我们 create()创建新模型实例的方法。所以我们可以覆盖它来处理进入 View 的发布数据。只需添加一个 create()在您的 View 类下,如下所示
class XViewSet(viewsets.ViewSet):
renderer_classes = ''

def create(self, request): # Here is the new update comes <<<<
post_data = request.data
# do something with post data
return Response(data="return data")

def retrieve(self, request, pk=None):
# your code

return Response(serialized_data, status=status.HTTP_200_OK)

def list(self, request):
# your code
return resp

关于django - 在 Django Rest 框架中发布请求处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com