Creating an API to execute a python script

馋奶兔 提交于 2021-01-05 11:11:24

问题


I have a python script app.py in my local server (path=Users/soubhik.b/Desktop) that generates a report and mails it to certain receivers. Instead of scheduling this script on my localhost, i want to create an API which can be accessed by the receivers such that they would get the mail if they hit the API with say a certain id. With the below code i can create an API to display a certain text. But, what do i modify to run the script through this? Also if i want to place the script in a server instead of localhost, how do i configure the same?

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return ("hello world")


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

Python Version is 2.7


回答1:


A good way to do this would be to put the script into a function, then import that function in your Flask API file and run it using that. For hosting on a web server you can use Python Anywhere if you are a beginner else heroku is also a good option.




回答2:


If you are tying to achieve something using Python-Flask API than you can have a close look at this documentations and proceed further https://www.flaskapi.org/, http://flask.pocoo.org/docs/1.0/api/

Apart from these here are few basic examples and references you can refer for a quickstart :

1-https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask

2- https://flask-restful.readthedocs.io/en/latest/

3- https://realpython.com/flask-connexion-rest-api/




回答3:


You could do something like this

from flask import Flask
from flask_restful import Resource, Api

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

class ExecuteScript:
  def printScript:
    return "Hello World"

api.add_resource(ExecuteScript, '/printScript')

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


来源:https://stackoverflow.com/questions/52143842/creating-an-api-to-execute-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!