This question already has an answer here:
Global variables in Flask templates
(1 answer)
Closed 1 year ago.
So I have this Flask app that I need a pass a particular user to all routes as all pages in the app will be needing the particular user to render templates. I don't want to pass the user as it's normal done
return render_template('index.html',user=user)
Because I'd have to repeat the same thing for all routes in the render_templates.
Please how can I do this?
You can do so by creating a custom render template function using the following implementation
from flask import render_template as real_render_template
from yourapp import user # Import the user variable or set it
def render_template(*args, **kwargs):
return real_render_template(*args, **kwargs, user=user)
it can also be done via functools.partial:
from flask import render_template as real_render_template
from yourapp import user # Import the user variable or set it
from functools import partial
render_template = partial(real_render_template, user=user)
If you want to send a variable to all routes/pages/templates. You can use sessions in flask
from flask import Flask,session
[...]
session['x'] = user
Now you can use it anywhere in the code, templates using session['x']
In templates
{{session['x']}}
Related
i'm building an app similar to myPhpAdmain
i need to allow users in session to create route (aka: #app.route) for the page they require
#app.route('/<x>')
def <x>():
return render_template (<x>+'.html')
where x is a variable that has been given by a user through the front-end
x = request.form.get('x')
how can I allow users to create Pages route like that by a function without allowing them to write it themselves in my flask app ?
Use variable routing:
#app.route('/<x>')
def user_route(x):
return render_template(f"{x}.html")
For the past two days I've been trying to intergrate flask-admin to my already existing flask application. But the problem is that I keep getting the same error:
builtins.AssertionError
AssertionError: A name collision occurred between blueprints <flask.blueprints.Blueprint object at 0x000001D8F121B2B0> and <flask.blueprints.Blueprint object at 0x000001D8ECD95A90>. Both share the same name "admin". Blueprints that are created on the fly need unique names.
and that error comes from this block of lines:
Main flask application:
app.route("/admin")
def admin():
if not session.get('logged_in'):
return redirect(url_for('login'))
return adminScreen.adminPage()
admin.py
def adminPage():
admin=Admin(app)
admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(PointOfSale, db.session))
return admin
And what I want to do is to manage the users that I already have in my database by using the functions that flask-admin provide.
So my question is; is there a simple way to route flask-admin to my pre-existing flask application?
P.S I already know that there is this post from May of 2018, but I have no idea how to implement the solution that was provided.
You don't have to create an app.route("/admin") yourself. That is provided by the built-in blueprint from flask-admin.
In order to use blueprints correctly you should update your app to use app factory instead global variable. Otherwise you cannot have multiple instances of the application.
In existing project it may require some work to do but it's worth it.
Example factory may looki like this:
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from yourapplication.model import db
db.init_app(app)
from yourapplication.views.admin import admin
from yourapplication.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
You can find more information here:
http://flask.pocoo.org/docs/1.0/patterns/appfactories/
This question already has answers here:
Add a prefix to all Flask routes
(15 answers)
Closed 7 years ago.
I have a Flask App, which will run later as a "subpart" of a server and I am unsure how to configure that.
As an example:
localhost/OtherServer/rest/myFlask/
OtherServer is an IIS Website which normally handles all my requests, but for certain requsts control is handed to Flask - e.g. all routes which are found unter myFlask/*.
This already works thanks to WFASTCGI and some config magic, but in Flask I have to supply to the full URL for each route:
#app.route('/OtherServer/rest/myFlask/status')
I would like to only specify the part including or after myFlask, particularly because the firt part of the url is configurable in a C#-app and getting the name at runtime is a major headache.
So:
#app.route('/myFlask/status')
You can use blueprint, use the url_prefix parameter.
I'll show you a simple example:
view.py
from flask import Blueprint
my_blueprint = Blueprint('my_blueprint', __name__, template_folder='templates',
url_prefix='/OtherServer/rest')
#my_blueprint.route('/myFlask/status')
def index():
return 'Hello, world.'
...other routes...
in your app.py, you can
from flask import Flask
from my_app.view import my_blueprint
app = Flask(__name__)
app.register_blueprint(my_blueprint)
How to get Flask to pass some of my own context along with url context? I would like to set the context when the URL is provided e.g. via add_url_rule:
app = Flask(__name__)
app.add_url_rule('/myproj/one, view_func=myfuncone,
methods=['GET'], context=mycontextone)
and I would like to access mycontextone when Flask calls myfuncone().
Curious - doesn't look like it's an option in flask as far as I can tell but you could wrap your view:
def myfuncone(id, **kwargs):
print kwargs.keys()
import functools
myfuncone_with_context = functools.partial(myfuncone, context=mycontextone)
app.add_url_rule('/myproj/one', methods=['GET'],
view_func=myfuncone_with_context)
Flask provides a url_for function to generate URLs to handlers based on the URL pattern. But this would imply that the handler functions must have unique names across the entire application. Is that correct?
Example
Module A has a handler index:
#app.route('/')
def index(): pass
And Module B has another handler index:
#app.route('/anotherindex')
def index(): pass
How to distinguish the handlers called index when building URLs?
url_for('index')
I don't know how you could do with all the views routed by the same module.
What I usually do is separate my views in different modules (like you did with module A and B), and register them as blueprints, after that, when using the url_for() function, you can prefix the view name with your blueprint name and then avoid conflicts and potential problems.
Here is an example:
main_views.py:
from flask import Blueprint
main = Blueprint('main', __name__)
#main.route('/')
def index():
pass
admin_views.py:
from flask import Blueprint
admin = Blueprint('admin', __name__)
#admin.route('/admin')
def index():
pass
application.py:
from flask import Flask
from main_views import main
from admin_views import admin
app = Flask('my_application')
app.register_blueprint(main)
app.register_blueprint(admin)
Now, to access the 2 index views and still distinguish one from the other, just use url_for('main.index') or url_for('admin.index')
EDIT:
Just one more useful details about routing using blueprints, when registering the blueprint, you can pass a url_prefix argument, that will apply to every view within this blueprint.
For example, given the following code:
admin_views.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
#admin.route('/')
def index():
pass
#admin.route('/logout')
def logout():
pass
application.py:
from flask import Flask
from admin_views import admin
app = Flask('my_application')
app.register_blueprint(admin, url_prefix='/admin')
The 2 views would be available at the URL /admin/ and /admin/logout