Flask hangs the main thread - python

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?

Related

Flask is not providing a URL

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)

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

waitress command line returning "Malformed Application" when deploying flask web app

I'm attempting to deploy a simple web app, and I'm using command line waitress-serve --call command. But every time, the command immediately returns 1. Malformed application 'name_of_project_here'.
Here's my flask web app in python:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run(debug = True)
and the command I run is just
waitress-serve --call "name_of_project"
I did try looking through the documentation, and I found where the error occurs, but couldn't find an explanation of why it's occurring. What does malformed application mean?
Minimal working example:
If you put code in file main.py
from flask import Flask
def create_app():
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World!"
return app
if __name__ == '__main__':
app = create_app()
app.run()
then you can run it as
waitress-serve --call "main:create_app"
So "name_of_project" has to be "filename:function_name" which creates Flask() instance.
It can't be any text. And if you forget : then you may see "Malformed application"
when defining your appname and the function that initialize your app with : dont put them into quotes('')

Using requests module in flask route function

Consider the following minimal working flask app:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "I am /"
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
r = requests.get("http://127.0.0.1:5000/api")
return "I am /" # This never happens :(
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
So my questions are: Why does this happen and how can I fix this?
You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.
You'll need to enable threading:
if __name__ == "__main__":
app.run(threaded=True)
or use a more advanced WSGI server; see Deployment Options.

Categories