简体   繁体   中英

How to return both string and value within HttpResponse?

I need the code to return a string and value in HttpResponse but it returns only first value(val). Why should I do to return both val and val2? String I will use as message and I need val in function return to use it as value in next function,something like this:

def func1(request):
   data = json.loads(request.body)
   val = "string"
   val2 = data['email']
   return HttpResponse(val, val2)

def func2():
   val3 = func1
   val4 = "client %s" % val2
   if val4:
      return True
   else:
      return False

your client (web browser) expects one string as response:

return HttpResponse("a string: {}".format(val))

or use JSON for the response:

return JsonResponse({'message': 'a string', 'val': val})

or, to send a variable to the next Django view:

def my_view(request):
    if request.session.get('val', None):
        # do something with the 'val' variable.
    else:
        request.session['val'] = 'somevalue'
        return HttpResponse('some message')

More about Django session here.

Use JsonResponse That will solved CORS problem also ''' Handling content type for json no more to add content-type. '''

    def __init__(self, content={}, status=None,content_type='application/json'):
        super(JsonResponse, self).__init__(
            json.dumps(content),
            status=status, content_type=content_type)

and response will be like this :

return JsonResponse({"message": " message", "subject": subject})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM