Schedule a function at particular time of day using a flask app - python

I want to schedule (every day at 17:00) a single function in a flask app (my flask app has multiple functions). How can I do that?
from flask import Flask
import schedule
import time
app = Flask(__name__)
app.secret_key = 'my precious'
def fct1():
print("bla bla bla")
def myfunction():
print("aaaaaaaaaaaaaaaa")
def programare():
schedule.every().day.at("17:00").do(fct1)
while True:
schedule.run_pending()
time.sleep(1)
if __name__== '__main__':
app.run(debug=True)

Simple thread if server startted standalone:
if __name__== '__main__':
import threading
threading.Thread(target=programare).start()
app.run(debug=True)
If server deployed with wsgi or etc I suggest to run shedule separately.

Related

What is the best way for a Python script to communicate with a Python Flask server that transports content to the client?

The following scenario:
I have a Raspberry Pi running as a server. Currently I am using a Python script with Flask and I can also access the Raspberry Pi from my PC. (The flask server runs an react app.)
But the function should be extended. It should look like the following:
2nd Python script is running all the time. This Python script fetches data from an external API every second and processes it. If certain conditions are met, the data should be processed and then the data should be communicated to the Python Flask server. And the Flask server then forwards the data to the website running on the computer.
How or which method is best to program this "interprocess communication". Are there any libraries? I tried Celery, but then it throws up my second Python script whenever I want to access the external API, so I don't know if this is the right choice.
What else would be the best approach? Threading? Direct interprocess communication?
If important, this is how my server application looks so far:
from gevent import monkey
from flask import Flask, render_template
from flask_socketio import SocketIO
monkey.patch_all()
app = Flask(__name__, template_folder='./build', static_folder='./build/static')
socket_io = SocketIO(app)
#app.route('/')
def main():
return render_template('index.html')
#socket_io.on('fromFrontend')
def handleInput(input):
print('Input from Frontend: ' + input)
send_time()
#socket_io.on('time')
def send_time():
socket_io.emit('time', {'returnTime': "some time"})
if __name__ == '__main__':
socket_io.run(app, host='0.0.0.0', port=5000, debug=True)
Well i found a solution for my specific problem i implemented it with a thread as follows:
import gevent.monkey
gevent.monkey.patch_all()
from flask import Flask, render_template
from flask_socketio import SocketIO
import time
import requests
from threading import Thread
app = Flask(__name__, template_folder='./build', static_folder='./build/static')
socket_io = SocketIO(app)
#app.route('/')
def main():
thread = Thread(target=backgroundTask)
thread.daemon = True
thread.start()
return render_template('index.html')
#socket_io.on('fromFrontend')
def handleInput(input):
print('Input from Frontend: ' + input)
#socket_io.on('time')
def send_time():
socket_io.emit('time', {'returnTime': 'hi frontend'})
def backgroundTask():
# do something here
# access socket to push some data
socket_io.emit('time', {'returnTime': "some time"})
if __name__ == '__main__':
socket_io.run(app, host='0.0.0.0', port=5000, debug=True)

Python Flask call index function without refresh page?

from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def index():
print('hello')
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
the index function is run whenever there is a request, so it is pressed on the "hello" console screen every time the site is refreshed or entered. So how can I always print "hello" in real time without refreshing this page?
What do you mean, saying "always"?
When you run flask app it starts in main thread, so if you want to make some worker(who for example prints your hello word), just create a new thread, and put in there.
Example:
from flask import Flask,render_template
import threading,time
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def start_new_thread():
def worker(arg1,arg2):
while(True):
print("hello")
time.sleep(2)
thread = threading.Thread(target=worker,args=("your argument","sencond one"))
thread.start();
if __name__ == '__main__':
start_new_thread()
app.run(debug=True)
print("OK")#never be printed because app.run starts in main thread

How to run python flask app and webview simultaneosuly

I am trying to run flask app and webview simultaneously but it seems that only flask app is running first and blocking the webview to open it.
if __name__ == '__main__':
os.system('python app.py')
webview.create_window('Hello world', 'http://127.0.0.1:5000/')
webview.start()
Webview command is only initiated once I close the flask server (Ctr+C) but till then webview returns connection refused.
You need to run your flask app in the background. Here is a sample working example. os.system('python app.py &')
main.py
import webview
import os
if __name__ == '__main__':
os.system('python app.py &')
webview.create_window('Hello world', 'http://127.0.0.1:5000/')
webview.start()
app.py
# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask
# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
#app.route('/')
# ‘/’ URL is bound with hello_world() function.
def hello_world():
return 'Hello World'
# main driver function
if __name__ == '__main__':
# run() method of Flask class runs the application
# on the local development server.
app.run()

Flask plus Schedule

Hi I want to integrate schedule with my Flask app since I would need to do some routinely tasks. I found it here that he used threading to run it on the background. However when I tried it on mine, I cannot exit my app using Ctrl-C, I am using Windows. I will soon deploy it on Heroku, what's wrong?
Also is there any better and 'human-friendly' like schedule to do some routine task for Flask? Thanks.
Here is my code:
from flask import Flask
from datetime import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import mysql.connector
from mysql.connector import Error
import schedule
import time
from threading import Thread
app = Flask(__name__)
def job():
print("I'm working...")
def run_schedule():
while True:
schedule.run_pending()
time.sleep(1)
#app.route('/')
def homepage():
return '<h1>Hello World!</h1>'
if __name__ == '__main__':
schedule.every(5).seconds.do(job)
sched_thread = Thread(target=run_schedule)
sched_thread.start()
app.run(debug=True, use_reloader=False)
Try APScheduler. It supports background scheduler.
Here's sample code I used flask with apscheduler.
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
app = Flask(__name__)
executors = {
'default': ThreadPoolExecutor(16),
'processpool': ProcessPoolExecutor(4)
}
sched = BackgroundScheduler(timezone='Asia/Seoul', executors=executors)
def job():
print('hi')
sched.add_job(job, 'interval', seconds=5)
if __name__ == '__main__':
sched.start()
app.run(debug=True, use_reloader=False)

Flask hangs the main thread

I want to use the Flask as my RESTful API server, but the main thread hangs and it doesn't execute the code after the app.run().
In util/restAPI.py
from flask import Flask
app = Flask('__name__')
#app.route('/')
def index():
return "Hello, World!"
In main.py
from util import restAPI
if __name__ == "__main__":
restAPI.app.run()
print "haha"
Should I use threads or something else to help me?

Categories