How can I run a python script from within Flask

try this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def run_script():
    file = open(r'/path/to/your/file.py', 'r').read()
    return exec(file)

if __name__ == "__main__":
    app.run(debug=True)

Using import:

  • Wrap what the python script (e.g. website_generator.py) is generating into a function.
  • Place it in the same directory as your app.py or flask.py.
  • Use from website_generator import function_name in flask.py
  • Run it using function_name()

You can use other functions such as subprocess.call et cetera; although they might not give you the response.

Example using import:

from flask import Flask
import your_module # this will be your file name; minus the `.py`

app = Flask(__name__)

@app.route('/')
def dynamic_page():
    return your_module.your_function_in_the_module()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000', debug=True)

Tags:

Python

Flask