Tech Stack
Python API
Flask Framework
We have developed Python API which then will be consumed by our React UI.
We have URL as follows
http://client-be.domain.com/admin
We want to change url to some random string
http://client-be.domain.com/fvcd9e72
But i am not able to find out where exactly i need to change this in my code.
I can see "admin" folder inside my API code and inside view, code is as follows
admin_views = view1 + view2 + view3 & so on...
So does it means, if i change folder name to random string, my url will be changed?
you can achieve this by adding an argument in your api end point. rest you can handle the situation/conditions in that itself
eg
from flask import Flask
app = Flask(__name__)
#app.route('/<stre>')
def home(stre):
return stre
if __name__ == '__main__':
app.run()
You can set custom url instead of 'admin'. Admin is default url in Flask.
eg:
from flask_admin import Admin
admin = Admin(name='app_name', url='/your_string')
Related
I am testing loginradius for authentication in a fastapi app but cant seem to get the redirect or modal form to work correctly. I have tried using the OAuth2PasswordBearer and OAuth2AuthorizationCodeBearer classes but neither worked as desired. I would like to be able to click the "Authorize" button and either get redirected to the loginradius login page https://<app_name>.hub.loginradius.com (and returned to the api page with the token from loginradius) or render the loginradius login/registration form instead of the fastapi OAuth2PasswordBearer form. example:
Instead of
Desired outcome
Small Code Snippet
"""Fastapi routes for all User related endpoints"""
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordBearer
router = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# oauth2_scheme = OAuth2AuthorizationCodeBearer(
# tokenUrl="https://<app_name>.hub.loginradius.com",
# authorizationUrl="https://<app_name>.hub.loginradius.com")
#router.post("/me", response_model=None)
def create_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
Is that possible?
Thanks
I would like to be able to generate a navbar based on an object's contents, basically having a navbar array or class that holds subpages and generates the appropriate navbar with collapsing parts etc. I have experience with Laravel in PHP which is similar to Flask but I can't figure out a way to do it easily. I would have to provide a set of data objects to every single page since it's part of the layout but would prefer not to have to specify it specifically for each page. Is there a way to do this?
So far I only have the basics, an app factory, view and blueprint:
Factory
def create_app():
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.register_blueprint(blueprint_index)
return app
Blueprint
from flask import Blueprint, render_template, session
blueprint_index = Blueprint('simple_page', __name__)
#blueprint_index.route('/')
def index():
if 'text' in session:
session['text'] += 1
else:
session['text'] = 0
return render_template('pages/index.html', text=str(session['text']))
Ignore the little bit of debug text I added to the route.
You could do this with a context processor. Add this to the end of your blueprint code-block:
#blueprint_index.context_processor
def inject_text():
return dict(text=session['text'])
{{text}} will now be available within every template on that blueprint.
I am getting confused with configurations and imports once I started using the Flask factory application pattern.
I am creating an application with the function create_app in #app/init.py
I have a config file for setting the development/testing/production variables, and an instance folder with another config file.
def create_app(config_name):
app=Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
etc...
return app
I am using blueprints and have an authentication view in #app/auth/views.py
I am trying to set up email confirmation tokens using URLSafeTimedSerializer...
from itsdangerous import URLSafeTimedSerializer
#auth.route('/register', methods=['GET','POST'])
def register():
ts = URLSafeTimedSerializer(app.config['SECRET_KEY'])
token = ts.dumps(self.email, salt='email-confirm-key')
etc...
Now my problem is, my variable 'ts' needs the app.config['SECRET_KEY'] set. But I am unable to define the app variable (as is shown in all online tutorials). I get an error when I try to import...(in #app/auth/views.py)
from .. import app
and when I try to import like...
from .. import create_app
Can someone shine light on how to initialize modules using 'app' and app.config outside the flask app factory create_app?
Hope you understand my question.
In this scenario you should use Flask.current_app
from flask import current_app
...
ts = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
From the documentation:
flask.current_app
Points to the application handling the request. This
is useful for extensions that want to support multiple applications
running side by side. This is powered by the application context and
not by the request context, so you can change the value of this proxy
by using the app_context() method.
This link aso explains further details about the Flask application factory methodology, in particular using current_app to access the app configuration.
I have two application factory functions - one creates the "customer" app, and the other creates the "admin" backend app. Both of the factory functions essentially do what is described here - create a flask app and register some extensions to it and then add some blueprints(with a url_prefix). I glue the two apps together via the create_combined_app() from below. It is the return value of that function which I register with my Flask-Script's Manager.
def create_combined_app(config_name):
customer_app = create_customer_app(config_name)
admin_app = create_admin_app(config_name)
from werkzeug.wsgi import DispatcherMiddleware
customer_app.wsgi_app = DispatcherMiddleware(customer_app.wsgi_app, {
'/admin': admin_app
})
return customer_app
And then this is how I run it.
def make_me_an_app():
return create_combined_app(config)
manager = Manager(make_me_an_app)
...
if __name__ == '__main__':
manager.run()
I want to do some testing which involves getting all GET routes of my app and making sure they load. I followed the example from here, but I only see the urls of the customer app, and none of the urls from the admin backend.
#main.route("/site-map")
def site_map():
from flask import current_app, jsonify
links = []
app = current_app
for rule in app.url_map.iter_rules():
if "GET" in rule.methods and has_no_empty_params(rule):
url = url_for(rule.endpoint, **(rule.defaults or {}))
links.append((url, rule.endpoint))
return jsonify(links)
The admin backend works when I try to access it from the browser - it all works nicely, except that I don't see the admin's urls when I call /site-map.
Thanks! :)
I think DispatcherMiddleware create separate apps. Which mean you created customer_app and admin_app. Those 2 live as standalone. They don't know each others, therefor current_app is just the show customer_app.
Here is the describe from Flask http://flask.pocoo.org/docs/0.12/patterns/appdispatch/
I have a Python Flask app that accesses the Github API. For this I need to store an access token. What is the common practice to store that data and how do I access that inside my app?
from flask import Flask, request
app = Flask(__name__)
app.config['DEBUG'] = True
#app.route('/',methods=['POST'])
def foo():
...
Flask has a custom context to store app variables:
http://flask.pocoo.org/docs/1.0/appcontext/
You can use g object to store your variables:
from flask import g
g.github_token = 'secret'
And after initialization:
from flask import g
token = g.github_token
The simpliest way is to place it into configuration module (regular python .py file) and then import and use it in your code as suggested by this snippet on Flask site.