Usecase: I have a python flask app that runs background_function() before serving any requests on routes.
When I execute the flask app, I receive the error - RuntimeError: Working outside of application context. I receive the error since I try to get the application context before any request is served.
What is the best pythonic way to execute the background_function() in this example?
from flask import Flask
from download import Download
app = Flask(__name__)
app.config.from_pyfile('config.py')
# run backgroung function
Download.background_function()
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
app.run()
The config file
FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"
# Many other variables are present in this file
The download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
file_path = app.config["FILE_LOCATION"]
# code to download file from server to local
return
Try this:
from flask import Flask
from download import Download
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
Download.background_function()
app.run()
the download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
print("testing")
given output:
testing
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
As you can see, the function runs first and prints testing and then runs the application.
Related
from flask import Flask, escape, request
app = Flask(__name__)
run_with_ngrok()
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
When I run the this from terminal with "flask run" it doesn't print an ngrok link.
Im i an virtual env and i have tried running it with python "file name" and it did not work.
if you are trying to expose your ip through ngrok, you can try tunneling with ngrok on terminal for the flask app's port
your app code should look like :
from flask import Flask, escape, request
app = Flask(__name__)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(port=5000)
you can tunnel the flask app port with the following command:
ngrok http 5000
here the port 5000 denotes the flask app port.
I think you forgot to add this part to end of your file
if __name__ == "__main__":
app.run()
from flask_ngrok import run_with_ngrok
from flask import Flask, escape, request
app = Flask(__name__)
app.secret_key = '33d5f499c564155e5d2795f5b6f8c5f6'
run_with_ngrok(app)
#app.route('/')
def hello():
name = request.args.get("name", "World")
return f'Hello, {escape(name)}!'
if __name__ == "__main__":
app.run(debug=True)
We can grab token from ngrok.com website by signin
In terminal we need to run like
ngrok config add-authtoken <your_token>
ngrok http 5000
for flask it is 5000 and for other application it would be different
And we also need to run our application side by side
I am trying to deploy my flask application to aws app runner, locally everything works perfectly. But I can't figure out how to redirect to another page of my website in app runner
My code looks similar to this
from flask import Flask, url_for
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect(url_for("redirect_to"))
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
App runner provided "Default domain" that redirects all traffic to my app, that is running on 0.0.0.0:8000. When I request default-domain.awsapprunner.com/hello, it successfully redirects to 0.0.0.0:8000/hello, but when I try to request default-domain.awsapprunner.com/redirect_from page loads forever. I think it happens because my app redirects to 0.0.0.0, and app runner expects that all traffic comes to default-domain.awsapprunner.com but I am not sure
What is the best way to fix this problem?
from flask import Flask, url_for, redirect
from waitress import serve
app = Flask(__name__)
#app.route("/hello")
def hello():
return "Hello"
#app.route("/redirect_to")
def redirect_to():
return "Redirected successfully!"
#app.route("/redirect_from")
def redirect_from():
return redirect("http://YOUR_APP_URL.com/redirect_to")
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8000)
I'm new to flask, I'm trying to do a rest api, but when creating my route it doesn't recognize it for me.
I have imported flask and python 3.8.
from products import products
from flask import Flask
#app.route('/greeting')
def greeting():
return 'hi'
if __name__ == '__main__':
app.run(debug=True, port=4000)
You need to create the instance of the Flask class
app = Flask(__name__)
A minimal Flask application looks something like this:
from flask import Flask
app = Flask(__name__)
#app.route('/greeting')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True, port=4000)
Now you could see it running at:
* Running on http://127.0.0.1:4000/
Access the greeting as http://127.0.0.1:4000/greeting
For more info read this
I'm running this very simple application.py file, in debug mode, on my Mac.
import os
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"
socketio = SocketIO(app)
#app.route("/")
def index():
return "hello"
if __name__ == '__main__':
socketio.run(app, debug=True)
It shows up on 127.0.0.1:5000. When I change return "hello" to return "goodbye" and refresh the page, nothing happens. When I try to return render_template(goodbye.html) from my templates directory, nothing happens. I even changed the route from '/' to '/bbbb' and nothing changed. I see a bunch of GET requests in my terminal, each with a status code of 200.
I've never had this problem with Flask, that is until I tried to use sockets.io. Any thoughts on what is happening?
I made the following file yesterday.
# import flask
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
# create url & function mapping for root or /
#app.route('/')
def index():
return "Hello from Flask"
# create another mapping name /hello
#app.route('/hello')
def hello():
myName = "kayak"
return "Hello again !!" + myName
# create mapping for /myprofile
#app.route('/myprofile')
def showmyprofile():
return render_template('myprofile.html')
# create mapping for /myprofile
#app.route('/addprofileform')
def addprofileform():
return render_template('myprofileform.html')
# create a mapping for /addprofile
#app.route('/addprofile')
def addprofile():
myname = request.args.get('myname')
state_of_residence = request.args.get('state_of_residence')
return render_template('myprofile.html', html_page_name=myname,
html_page_state_of_residence=state_of_residence)
if __name__== '__main__':
app.run()
Then I made the following file today.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'This is the homepage'
if __name__ == "__main__":
app.run(debug=True)
I thought
app.run(debug=True)
would work to clear the old data, but I doesn't and http://127.0.0.1:5000/ page keeps showing "Hello from Flask".
How do I fix this?
Just clear the cache in your browser and try running it again.
Here's how to clear your cache in some browsers:
Firefix->https://support.mozilla.org/en-US/kb/how-clear-firefox-cache
Chrome->https://support.google.com/accounts/answer/32050?co=GENIE.Platform%3DDesktop&hl=en
You can export the FLASK_ENV environment variable and set it to development before running the server
export FLASK_ENV=development
flask run
This worked for me.
Running the program in incognito tab will not cause this error. No need to clear caches also. See https://support.google.com/chrome/answer/95464?co=GENIE.Platform%3DAndroid&hl=en