[Answer]-How to create dual prefix and read POST payload with DRF

1đź‘Ť

Your current code seems to be nearly-complete. Assuming that you have a function that does the actual execution (let’s call it “run_ssh_command”), a rudimentary version of your view could look something like this:

@detail_route(methods=['POST'])
def ssh(self, request):
    input = json.loads(request.data)  # I'd use a serializer here
    output = run_ssh_command(input['command'])  # or whatever the field name is
    return Response(json.dumps({'result': output}),
                            content_type="application/json")

Some caveats:

  1. Make sure you use proper authentication,
  2. Keep in mind that some SSH commands might take a while to run OR they may just hang (E.G., waiting for input),
  3. Take a look at http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ for an example on how to use Serializers for request validation.
👤Mark R.

Leave a comment