Pass a Path in Python Flask

When we are creating Rest services in Python Flask may need to upload a file to a service. In this case it is possible that a path will have to be sent to the service. And what does it mean that we pass a path as a variable to a Flask service, since the structure of the path variable can be confused with the service’s own Path. In this example we are going to see how we can pass a Path in PythonFlask.

If you have already installed the Flask microframework:

pip install Flask

And you have created your Flask application:

from flask import Flask
app = Flask(__name__)

if __name__ == '__main__':
    app.run()

You must create a route that accepts the path as a request variable on the endpoint.

@app.route('/file/',methods=['GET'])
def file(path):
    return 'File path ' + path

The problem with creating this route with the .route() method is that Flask will ignore variables of the type '/file/directory/subdirectory/file.png' since it is confused with the path of the endpoint.

In order to solve it we must indicate that the variable is of type Path. So we will encode our route in Flask as follows:

@app.route('/file/',methods=['GET'])
def file(path):
    return 'File path ' + path

This way we can pass a Path in Python Flask and upload the path of a file to our Flask service.