I wrote the following python code
import thread
from flask import Flask
app = Flask(__name__)
COOKIE =""
#app.route('/')
def index():
return COOKIE
def request_cookie():
global COOKIE
while 1:
%SOME CODE WHICH GET COOKIE FROM WEB SITE%
sleep 5
if __name__ == '__main__':
app.run(debug=True)
t1 = thread.start_new_thread(get_cookie(), ())
t1.start()
When I run this code. REST server starts but the thread doesn't start.
How can I fix it so that REST server starts and parallely runs the new thread to fetch cookie from a remote site.
You are doing app.run(debug=True) which starts the web server and waits for it to complete. Since it doesn't complete till you terminate the server, the next line is not executed.
So for your thread to start, first start the thread and then start the server.
just change :
if __name__ == '__main__':
t1 = thread.start_new_thread(get_cookie(), ())
t1.start()
app.run(debug=True)
You have to run thread before app.run() because app.run() runs endless loop which works till you stop server.
Working example:
from flask import Flask
import threading
import time
app = Flask(__name__)
COOKIE = 0
#app.route('/')
def index():
return str(COOKIE)
def request_cookie():
global COOKIE
while True:
COOKIE += 1
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=request_cookie)
t1.start()
app.run(debug=True)
Related
I am a new programmer and I am trying to connect my bot to flask to create a URL for discord.
when I run it, it doesn't do it. Am I missing a line here because it is not coming up with an error but it will not run either.
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
app.run(host='0.0.0.0',port=5000)
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run()```
Can someone point me in the right direction? I normally work on python 3.
Thank you
Try running the app when checking the name of your code, not in home() function:
from flask import Flask
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run(host='0.0.0.0',port=5000)
I've been trying threads recently in my webapp, and I've come across an issue that I cannot seem to solve.
The issue is that I have an index page, and every time the user enters that page, a new thread is being started which checks for changes in my database in a while loop, although I only want one thread to be on at that moment. Is there a way to "kill" a thread when the index page is accessed the second time and then start a new one?
I did try to use is_alive() to check if a thread is already running, but had no success since all the time they're different.
Code example below:
#app.route("/")
def index():
#copy_current_request_context
def check_for_updates():
while True:
...... # Query for information
if something_changed:
socketio.emit('new_notifications', {'data': new_data})
if index_opened_again:
break
sleep(5)
index_thread = threading.Thread(target=check_for_updates, daemon=True)
index_thread.start()
return render_template("index.html")
I user the below code to kill threads when I am existing a server ,
My suggestion is to kill all active threadss before opening a new one
for id, thread in threading._active.items():
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
In my example I use a global variable in combination with a lock. It's certainly not optimal, but you can check if a thread is already running.
If you're using flask-socketio anyway, I recommend you take a look at start_background_task. The functionality is compatible with that of a standard thread.
from threading import Lock
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.secret_key = 'your secret here'
sio = SocketIO(app)
thread = None
thread_lock = Lock()
def background_task():
while True:
# ...
sleep(5)
#app.route('/')
def index():
global thread
with thread_lock:
if thread is None:
thread = sio.start_background_task(background_task)
return render_template('index.html')
if __name__ == '__main__':
sio.run(app)
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
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?
I have a bottle app that I eventually wan't to deploy on apache (just fyi in case that's important).
Now I need to run a function once after the bottle app is started. I can't just put it into a routed function because it has to run even if no user has accessed the site yet.
Any best pratice to do this ?
The function starts a APScheduler Instance and adds a jobstore to it.
Here's what I do.
def initialize():
//init whatever you need.
if __name__ == '__main__':
initialize()
#bottle.run(port='8080', yatta yatta)
Honestly your problem is simply a sync vs async issue. Use gevent to easily convert to microthreads, and then launch each separately. You can even add a delay either in your function or before with gevent.sleep if you want to wait for the web server to finish launching.
import gevent
from gevent import monkey, signal, spawn, joinall
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from bottle import Bottle, get, post, request, response, template, redirect, hook, abort
import bottle
#get('/')
def mainindex():
return "Hello World"
def apScheduler():
print "AFTER SERVER START"
if __name__ == "__main__":
botapp = bottle.app()
server = WSGIServer(("0.0.0.0", 80), botapp)
threads = []
threads.append(spawn(server.serve_forever))
threads.append(spawn(apScheduler))
joinall(threads)
Create an APScheduler class.
Look at examples of object use and creation in this same site bacause it's too general to give an especific example to copy.
I don't know if this helps.
class Shed(object):
def __init__(self): # this to start it
# instruccions here
def Newshed(self, data):
# Call from bottle
# more methods ...
...
# init
aps = Shed() # this activates Shed.__init__()
...
# in the #router
x = aps.Newshed(data) # or whatever
Anyway I'm still learning this stuff and it's just an idea.
import threading
import bottle
def init_app():
def my_function_on_startup():
# some code here
pass
app = bottle.app()
t = threading.Thread(target=my_function_on_startup)
t.daemon = True
t.start()
return app
app = init_app()
#app.route("/")
def hello():
return "App is running"
if __name__ == "__main__":
bottle.run(app, host='localhost', port=8080, debug=True)