Code is Working Review and Recommend What Are Best Practice
What I am trying to achieve.
API with Flask that runs any python file from the current directory.
Run the file and get output in JSON
Below is the code for the app.py
from flask import Flask,jsonify
from flask_restful import Api,Resource
import os
app = Flask(__name__)
api = Api(app)
class callApi(Resource):
def get(self,file_name):
my_dir = os.path.dirname(__file__)
file_path = os.path.join(my_dir, file_name)
file = open(file_path)
getvalues={}
exec(file.read(),getvalues)
return jsonify({'data':getvalues['total']})
api.add_resource(callApi,"/callApi/<string:file_name>")
if __name__ == '__main__':
app.run(debug='true')
Below is the code for the main.py which sends a request to API.with Filename which to run. The filename will be changed as per requirements.
import requests
BASE = 'https://127.0.0.1/callApi/runMe.py'
response = requests.get(BASE)
print(response.encoding)
Below is the File which runs by exec from API API/app.py can access this file because both are in the same dir.
def fun():
a = 10
b = 10
total = a+b
print(total)
return total
total = fun()
Is there any better way to write all this code please let me know. here are refs which I used to make this
Running a python script saved in local machine from google sheets on a button press