How to invoke/run a Python script using a web URL? - python

I have a Python script that pulls data from a 3 rd party API. Currently this Pyhton script is automated on server side.
There are few instances where I have to toggle the script manually for new data updates. For the manual toggle I have to login to the server each time and run it from command line. Is there a way where I can create web url or something similar and just run that URL to make that script run from the browser address bar.

One approach you could take is to use Flask, which is a minimal web framework. Here's an example of how you could use it:
from flask import Flask
from your_script import your_func
app = Flask(__name__)
#app.route('/run')
def run_command():
your_func()
return 'Executed your function!'
if __name__ == '__main__':
app.run(debug=False, port=8080)
If you run this code you'd get a web server running on port 8080 that executes your function when you access the url. Here's a tutorial in the Flask documentation to get you started.

I think the easiest way to do this is by using Flask.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
# your code here
return 'Hello, World!'

Related

How do you make flask execute a function via the app.run command?

I have been trying to follow the tutorials to get flask apps to run on Heroku, like this one: https://dev.to/emcain/how-to-set-up-a-twitter-bot-with-python-and-heroku-1n39.
They all tell you to put this in your code in a file server.py:
from flask import Flask
app = Flask(__name__)
app.run(host='0.0.0.0')
And then run the app via the following command:
python3 server.py
But the tutorials don't explain how to connect the actual function you want to run using the app. In my case, I have a File testbot.py that has the function test(arg1) that contains the code I want to execute:
def test(arg1):
while(1):
#do stuff with arg1 on twitter
I want to do something like this:
from flask import Flask
from testbot import test
from threading import Thread
app = Flask(__name__)
app.addfunction(test(arg1='hardcodedparameter'))
app.run(host='0.0.0.0')
So that when the app runs my test() function executes with the argument. Right now my server is starting, but nothing is happening.
Am I thinking about this correctly?
*Edit: I got it working with the solution, so my server.py now looks like this:
from flask import Flask
from testbot import test
def main_process():
test("hardcodeparam")
app = Flask(__name__)
Thread(target=main_process).start()
app.run(debug=True,host='0.0.0.0')
And now test runs as expected.
Before app.run, register the function with a path, e.g.
#app.route('/')
def test(): # no argument
... do one iteration
return 'ok'
Then visiting the URL will trigger the function. Sites such as https://cron-job.org/ can automate that visiting on a regular basis for free, as suggested here.
If the regular intervals aren't good enough, then you could try:
#app.route('/')
def index(): # no argument
return 'ok'
def test():
while True:
# do stuff
from threading import Thread
Thread(target=test).start()
app.run(...)
You will probably still need to have a job regularly visiting the URL so that Heroku sees that the server is alive and in use.

Make a python script API

I have a script on python, which prints some data. The script is on Centos7, nginx.
How could I connect to the script via URL (GET query) to be able to parse the data?
You can use a framework like Django or flask to make an api out of it. I'll suggest flask since it's very light-weight, making it ideal for such small tasks.
E.g.
def your_function(input):
# do something
return output
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/my_api')
def your_api_function():
input = request.args.get('my_query_string')
return your_function(input)
if __name__ == '__main__':
app.run(debug=True)
And then use the endpoint
/my_api?my_query_string=my_input
You can further play around with it to return JSON, take parameters from request body and so on and so forth.
Read more here http://flask.pocoo.org/

Python script with flask server takes too long to exit on Windows

I'm new to Python.
As a part of a project I'm trying to deploy a Flask server locally, through the Windows command line.
My Python version is 3.6.0.
The code:
from flask import Flask
app = Flask(__name__)
#app.route('/') def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run()
The problem:
It's about killing the script as it runs. Launching this script with python deploy.py and hitting CTRL+C shuts it off.
BUT - if I hit access that '/' route via the browser once or more, and a moment later try to kill the script in the same manner, then it would take about 10 seconds of nothing until it responds and is finally killed.
Why is this happening? How can I shut the server off immediately each time for continuous and quick development?
Thanks!!
Well if your goal is continuous and quick development, then you can change flask's configuration.
Best solution for your problem would be setting the DEBUG setting to True. If DEBUG is set to True, then flask will automatically reload the server on code changes.
There are a few ways to do this but the easiest one(because you said you are a beginner) is to pass the debug argument to app.run()
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run(debug=True)

How to run python script via url using Flask

What I want to do is run a python script(has nothing to do with html) via a url and display the result in the browser. The output can be as simple as an addition answer.
Whatever research I am doing shows I need Apache, cgi, Flask etc.
What I wanted to know is, can I do the aforementioned without using Apache or anything like that. Can I only use Flask to do the above task?
You don't need Apache
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World"
if __name__ == "__main__":
app.run()
Run with:
python my_file.py
And check localhost:5000, you should see "Hello World"

flask 'hello world' not working

I copy pasted the flask's 'hello world' app from their website and am trying to run it. I get an error message in Chrome saying
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Here is the 'hello world' app straight from flasks website
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.debug = True
app.run()
What I have tried:
-temporarily disabling Avast!
-disabling windows firewall
-ensuring that the flask module is installed
This was working a couple days ago actually...
I don't know why but when I change
app.run()
to
app.run(port=4996)
it starts working. No idea why the default port is throwing an error. Oh well.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello World'
if __name__ == '__name__':
app.run()
app.run(port=5000)
For Windows machines you can use the command in cmd:
set FLASK_APP=python_file.py
flask run
Some other process is running on port 5000. It may be you still have an old Flask process running, with broken code. Or a different web server altogether is running on that port. Shut down that process, or run on a different port.
You can switch to using a different port with the port argument to app.run():
app.run(port=8080)
If you can't figure out what process is still bound to port 5000, use the Windows Resource Monitor or run netstat -a -b from a command line. See How can you find out which process is listening on a port on Windows?
I think you are trying to copy the route generated through your flask program in cmd by pressing ctrl+c which quits your running flask program . i was also doing the same.just try to type the route generated by your flask program on your browser . it will definitely resolve your problem.
Where your python file store is, use cmd and then go on your file store directory, then
set FLASK_APP=filename.py
After this your flask run cmd will work.
from flask import Flask
app = Flask(__name__) # creating app
#app.route('/', methods['GET']) #routing it to the home page
def home(): #function
return "hello world"
app.run(port=5000, debug=true) #function call by the app
Add port and use methods whatever your need is USE GET in your case and try to remove your cache and run the this code it will definitely work.

Categories