0

Here is my get method of my Resource class:

from flask_restful import Resource
import subprocess

CMD = ['some', 'cmd' ]

class MyResource(Resource):

    def get(self):

        try:
            completed_process = subprocess.run(CMD, check=True, 
                                               capture_output=True)
      ....

At which point in the above code can I retrieve (and print) the IP of the incoming XGET request?

I am aware of this answer but it does not indicate how to go about it with flask_restful and the Resource class.

pkaramol
  • 16,451
  • 43
  • 149
  • 324
  • 1
    unrelated, but maybe informative: You can use [subprocess.check_output](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) for what you are doing too. You might also want to look at [shlex.quote](https://docs.python.org/3/library/shlex.html#shlex.quote) if you intend to pass end-user arguments into the CMD. – exhuma Sep 25 '19 at 08:52

1 Answers1

1

Here is a full example returning the remote IP. All you need to do is import request and access the remote_addr attribute.

The request object is local to the current request. See The Request Context for more information.

from flask import Flask, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world', 'remote-ip': request.remote_addr}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)
exhuma
  • 20,071
  • 12
  • 90
  • 123