In my flask application I need to fetch data from my database whenever the users clicks a button, I know I can just make a flask route, using the flask restful module or plain routes. But my question is if I can make that route/endpoint not visible for users.
#app.route("/api/fetch/")
def fetch_data():
return some_data
I dont wan't the user having access to this endpoint directly, I just want the web application to be able to use it. Not sure if it is possible or where to look.
I found that maybe using Flask-CORS could help. Any help or guidance would be appreciated.
On flask you can use Blueprint
example from the above snippet would be
from flask import Blueprint
sample_bp = Blueprint("sample_bp", __name__)
#sample_bp.before_request
def restrict_with_token():
# Do something here on checking header or token
#sample_bp.route("/api/fetch/")
def fetch_api():
# Your logic
Otherwise you can have some referrence here : https://flask.palletsprojects.com/en/1.1.x/tutorial/views/
Related
Is there a prefered way of setting up Flask so that it routes by username (mysite.com/<username>) at the top level but still works well (and fast) for all other routes and static files?
The way I imagine it now is something like:
#app.route('/<username>', methods=['GET'])
def username_route(username):
if username_is_valid(username): # DB checks, not too fast
display_user_page(username)
render_template('user_not_found.html')
But would that have any unwanted effects on other routes or static assets, favicons, or something that I'm forgetting?
You can send data with post request on frontend for clicking profile cases.
<button onclick="urlfor('username', {'user_id': id})"/>
Top level solution is possible with app.config.
app.config['RESERVED_ROUTES'] = [
"faqs",
"settings",
"login",
...
]
Now we decide on request are user or reserved route. Because when we want to use blueprint in Flask it copy the config and give them an instance. So it is reachable for every request even you want to scale your app with blueprints.
#app.before_request
def decide_user_or_not():
if request.path in app.config['RESERVED_ROUTES']:
register_blueprint(route_blueprint)
else:
register_blueprint(user_blueprint)
Put your username_route at the end. Flask checks for each route from top to bottom. So, when you put faqs_route at the top which points to mysite.com/faqs, flask will consider that first.
Now, if you want to go to mysite.com/<username>, it will check all the top functions and since it can't find the corresponding route, it will go to the username_route at the end which will be the right route for mysite.com/<username>
I'm making a customer support popup bot in Flask. I added the customer support popup bot to the layout template in the base.html file so that it appears on all of the routes.
In the customer support bot it has a form to get user input, but I can't figure out a way to get the post/get request from the bot. Since the bot is not in the views route.
I am not sure how to send and get info to my layout/customer_support.html page. Since the page is not rendering constantly.
Any advice on how to send the info back and retrieve the info from my layout/customer_support.html bot would be much appreciated thanks
EDIT: I'm aware of context manager, but now sure how to get the post/get information from my layout/customer_support.html form with the context manger. Am I suppose to somehow route the layout to get post/get request?
Some link I tried
Flask + Jinja: Pass Data to a Base Template/All Templates
Maybe make a session like:
import from flask_session import Session
And then create a session function
def session_support(chat):
if "support" not in session:
session["support"] = []
else:
session["support"].append(chat)
This might work somehow...
I am currently using code found here:
http://flask.pocoo.org/snippets/8/
And I decorate my function accordingly to have the admin authenticate when requesting a specific admin page. However, instead of requiring the admin to keep authenticating each time they admin page, I noticed that it somehow keeps track of the session and no longer requires authentication after successfully authenticating once. Is there some way to force flask to re-authenticate every time an admin requests the given decorated admin page?
Using the included snippet, there is no good way to force a user to log in every time they request the given page.
This is because that snippet is using HTTP Basic Auth and there is no good way to ask the browser to stop sending that header.
What you are looking for can be done with a custom decorator. You can use the sample below. Note that your case will be different, but you can use this as a guide.
from web import app, has_role
#app.route("/admin/my_page")
#login_required
#has_role(role="admin")
def admin_my_page():
//do stuff
Then, in your project init, or an include file you can add the following:
def has_role(role=None):
def _initial_decorator(view_func):
def _decorator(*args, **kwargs):
response = view_func(*args, **kwargs)
if g.user.user_level != role:
from flask import redirect, url_for
return redirect(url_for("no_access"))
return response
return wraps(view_func)(_decorator)
return _initial_decorator
This should at lease give you an idea of how to create a custom decorator, and then check for role permissions. You can expand this to however you need. You can put engine logic, or other checks to fit your project.
I am working on a small web project using Flask/Python. This is a simple client side application without database.
I want to set the REST service address as a global attribute, but haven't figured out how to do that.
I know that attributes can be seted in flask.config like this:
app = Flask(__name__)
app.config['attribute_name'] = the_service_address
but the Blueprint module cannot access the 'app' object.
Thanks a lot for your time.
Within a request context (i.e. in a view/handler) you can access the config on the current_app
from flask import current_app
current_app.config['attribute_name']
You can do this like adding an attribute to any python object:
def create_web_app():
app = Flask('foods')
setattr(app, 'cheese', CheeseService())
I am building an app for making API calls to websites like (FB, LinkedIn, etc.) I need to use OAuth to authorize my application to request data on behalf of the user. I am stuck with a problem of storing the instance of my website interface library (LinkedIn) across views. I used request.session - with file back end.
Below is the code http://pastebin.com/QTgqSr7W
Am I doing something wrong? can see the value being set in login() but I cannot see the same value in token(). Is this wrong to expect? Any workaround for passing the value of the api instance?
Thanks and Regards,
Atul.
hmm, i think its because you are saving the entire api python instance, i dont think that sessions support that kind of data, why not just redirect user to auth url without saving something in session, then in callback view, you instantiate the linkedin.LinkedIn class like so
from django.conf import settings
key = settings.KEY
secret = settings.SECRET
return_url = settings.CALLBACK
# You make the api connection here, so its not tied to any function
api = linkedin.LinkedIn(key, secret, return_url)
def login(request):
if api.request_token():
auth_url = api.get_authorize_url()
return HttpResponseRedirect(auth_url)
#below is the view that will get called with the oauth oken.
def token(request, param):
#do stuff with the api.