This question already has answers here:
Importing flask.ext raises ModuleNotFoundError
(3 answers)
Python flask.ext.mysql is deprecated?
(2 answers)
Closed 4 years ago.
I've created an AngularJS app served by node.js and now I've been asked to move from that to python flask. I encountered some errors and after search I was informed I have to include flask.ext.triangle but when I try to access localhost:5000 I get this error:
flask.cli.NoAppException: While importing "server", an ImportError was
raised: ModuleNotFoundError: No module named 'flask.ext'
I have installed flask-triangle using pip. My server.py is this:
from flask import Flask, render_template
from flask.ext.triangle import Triangle
app = Flask(__name__)
Triangle(app)
#app.route('/')
def mainPage():
return render_template('main.html')
Before importing triangle I got errors regarding AngularJS filters. All the routing and utility is handled by AngularJS, I just want flask to serve my app.
Couldn't get triangle to work so I found another way to make things happen. Found out that if you change the AngularJS expression brackets to something else and you forget completely about triangle the page loads. Here is my configuration on AngularJS app.js:
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//').endSymbol('//');
});
Now all I had to do is go to my HTML files and change {{ }} to // //.
EDIT:
Found the most proper way to do it. Instead of using render_template and have to mess with Jinja I used current_app.send_static_file to serve my HTML and faced no problems at all. My updated server.py:
from flask import Flask, current_app
app = Flask(__name__)
#app.route('/')
def mainPage():
return current_app.send_static_file('main.html')
Everything else is handled by AngularJS, no need to configure expression delimiters, used the built-in {{ }}.
Related
This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
What is the g object in this Flask code?
(1 answer)
Closed 1 year ago.
I'm trying to share a variable I defined in my main function with a flask app which is imported from another file. First I tried to solve it via a classic global variable which did not bring me any further, until I stumbled over the concept of flask.g and the app context.
So I tried the following: I have two files in the same directory, a main.py:
# main.py
import app
from flask import g
if __name__ == "__main__":
with app.app.app_context():
g.value = "Hello World"
app.app.run(debug=True, threaded=True, host='localhost', port=5000)
and a app.py:
# app.py
from flask import Flask, g
app = Flask(__name__)
#app.route('/helloworld')
def send_response():
return g.value
However, when I request at http://localhost:5000/helloworld I get
AttributeError: '_AppCtxGlobals' object has no attribute 'value'
So it seems that setting the value g.value in one file is not reflected in the app.
I'm a beginner in Flask and it is very likely I did not get the concept right.
Similar questions did not get me any answer I could use to fix the issue:
Flask passing global variable, python-How to set global variables in Flask?, Preserving global state in a flask application
Help would be much appreciated!
Just use a regular Python module-level variable.
# app.py
g = "Example"
#app.route("/example")
def example_endpoint():
return g
# main.py
import app
app.g = "Hello"
Quoting the same page you linked:
The application context is created and destroyed as necessary. When a Flask application begins handling a request, it pushes an application context and a request context. When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request.
So your setting flask.g outside of a request context (in your main.py) doesn't carry your value to anywhere.
I'm working on updating an existing university department internal website to run using Flask. Before we completely release the project where it will use shibboleth to manage authentication, I've been trying to setup authentication for testing using htpassword using this tutorial. I'm able to get authentication using htpasswords working for a single file, but I can't figure out how to add the authentication to separate files. Currently, the project looks like this:
This is my main file called app.py:
#app.py
from flask import Flask
from flask_htpasswd import HtPasswdAuth
app = Flask(__name__)
app.config['FLASK_HTPASSWD_PATH'] = '.htpasswd'
app.config['FLASK_SECRET'] = "Super secret key that I will change later"
htpasswd = HtPasswdAuth(app)
import exampleRoute
#app.route('/')
#htpasswd.required
def home(user):
return "This is the homepage"
This is an example of one of my route files called exampleRoute.py:
# exampleRoute.py
from app import app
from flask import Flask
#app.route('/exampleRoute')
def exampleRoute():
return "This is an example route in another file"
When I place the #htpassword.required decorator in front of exampleRoute(), I get an error saying that htpassword is not defined (which makes sense). I've tried to import the app configuration a few different ways and at best, I end up with a circular dependency. I know that I could place the authentication code in a separate file and then import that into all my endpoints, but I didn't think this was possible since this method is incorporated into the app configuration.
I ended up getting an answer from the reddit user alexisprince. The solution was to use Blueprints that import htpasswd from another file (called extensions.py).
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:
NameError: name 'Response' is not defined"
from flask import Flask, render_template
import requests
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/farmdata')
def farmdata():
r = requests.get('http://74.114.75.91:8080')
r.url
r.encoding
return Response(
r.text,
status=r.status_code,
content_type=r.headers['content-type'],
)
if __name__== '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
Edit - to anyone else with the problem, this was the solution.
from flask import Flask, render_template, Response
You have never defined Response. If you want to use flask.Response, you either have to import flask and then access it via flask.Response, or from flask import Response and then simply use Response.
In your code, you import Flask from the flask module, and that's where you get Flask from. If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.
In Python, a name is defined if:
you defined it via variable assignment [or with a def or a class statement, which is pretty much the same] (like app in your example)
you imported it from another module explicitly (like Flask)
it's defined on startup (like list)
Is there not a " ," too much before closing the brackets of the response?
This question already has answers here:
Flask at first run: Do not use the development server in a production environment
(6 answers)
Closed 4 years ago.
This is my code for application.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/zuck")
def zuck():
return render_template("zuck.html")
#app.route("/login")
def login():
return render_template("login.html")
This is pretty much the same as what David types out but when I type flask run in the terminal window, it throws up a bunch of nasty errors
Error msg
Please help! What could the issue be?
If you want to turn of debug mode, you can do that in the app.run function call
app.run(debug=False)
But as Dietrich Epp mentioned in the comment, it's not an error, just a warning.
You can read more about flask debug mode here.
I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.