Generic endpoint in Flask [duplicate] - python

This question already has an answer here:
Capture arbitrary path in Flask route
(1 answer)
Closed 5 years ago.
In Flask, is it possible to have a generic endpoint which can serve different requests, I take an example, suppose I have a handler for "/" and I want that all request is handled by this handler to generate a reply. A request like "/person/767" or "/car/324" should also handled by the same endpoint and it is going to generate the reply base on resource requested. Is that possible and if yes, how ?

If you want an endpoint to literally capture everything after a particular slash, you can use a path placeholder in your route definition.
#app.route('/<path:path>')
A more detailed example in this answer:
Capture Arbitrary Path in Flask Route

You can register multiple routes to one view function
from flask import Flask
app = Flask(__name__)
#app.route('/')
#app.route('/car/<id>')
#app.route('/person/<id>')
def generic_endpoint(id=None):
...
or, as pointed out by #sql_knievel, use <path:path>.

Related

Use a Post request to turn on and off a different endpoint in Flask [duplicate]

This question already has answers here:
Are global variables thread-safe in Flask? How do I share data between requests?
(4 answers)
Closed 2 days ago.
I am trying to do something a bit unconventional. I was trying to see if there was a common practice or a simple way to achieve this task. I have two (maybe it should be one?) endpoints. One endpoint will receive a request and that should trigger my flask app to either turn on or off a separate endpoint for a predetermined amount of time.
Use case: Its for a Jeopardy game, I want people to Buzz in to answer by sending a post request (from postman) after the question as been revealed. I do not want them to be able to buzz in (send post request) before the answer was revealed (on the front end) or after the time has expired.
Here is a simple code example to help you picture waht I am trying to do
import flask from Flask
app=Flask(__name__)
#route.post("/turn_on")
def turn_on():
#turns off the submit endpoint
#route.post("/submit")
def submit():
#ability to send to this endpoint is determined by the time since the turn_on endpoint was last hit
You can use a flag as a guard in your /submit route.
is_submit_on = False
#route.post("/toggle")
def toggle_submit():
global is_submit_on
is_submit_on = not is_submit_on
#route.post("/submit")
def submit():
if not is_submit_on:
return # return 404 or 401 or whatever here also
...

Create flask modules and divide the application [duplicate]

This question already has answers here:
Split Python Flask app into multiple files
(4 answers)
Closed 2 years ago.
I'm building a small flask application and I want to have a modular structure in my project.
In Django I could just write two separate folders with their own urls.py, register them in my settings.py and create routes to them in base urls.py.
How to achieve this kind of modularity in flask?
Preferably with as little code as possible.
Bonus points if all this can be easily done without extensions.
You are looking for blueprints.
app.py
blueprints/
sample_blueprint.py
another_blueprint.py
Blueprints are like apps but not apps. (very lame explanation but let me show you some code)
# sample_blueprint.py
from flask import Blueprint
# just like `app = Flask(__name__)`
SAMPLE_BLUEPRINT = Blueprint('sample_blueprint', __name__)
# just like `#app.route('/sample')`
#SAMPLE_BLUEPRINT.route('/sample')
def sample():
return 'Sample'
And then in app.py you have to register it.
# app.py
from flask import Flask
from blueprints.sample import SAMPLE_BLUEPRINT
app = Flask(__name__)
# Register all the blueprints, url_prefix is optional
app.register_blueprint(SAMPLE_BLUEPRINT, url_prefix='/sample-br')
if __name__ == '__main__':
app.run(debug=True)
You can now run the app (python3 app.py) and goto localhost:5000/sample-br/sample and see the response of the blueprint route.
This code is not tested. It is just to give you a starting idea. Please read the docs and try it out on your own and find out how blueprints fit into a Flask project.

Accessing request data of all requests that is being received with Flask

So, I want to write this Python code that wants to assess data in requests I am getting and act accordingly. I have many different endpoints and I'd like a way to access the request data for all requests without creating manually every possible endpoint.
Is there a way to do it with Flask/Bottle? A proxy of sorts
You can register a function to be called before every request with the #app.before_request decorator:
#app.before_request
def handle_every_request():
# ...
If this function returns anything other than None, it'll be used as the response and no views will be called. This would let you create any number of routing options.
Another option is to use the request_started signal, see the Signals documentation:
from flask import request_started
#request_started.connect_via(app)
def handle_every_request(sender, **kwargs):
# ...
The above listens to requests for the specific Flask app instance. Use #request_started.connect if you want to listen to all requests for all apps. Signals just listen, they don't route, however.
In general, both Flask and Bottle are WSGI applications. WSGI supports wrapping such applications in WSGI middleware, letting you inspect every ingoing and outgoing byte of a request-response pair. This gives you access to the data at a lower level. You could use this to rewrite paths being requested however.

Flask With Swagger Log input and output

I am using Flask with swagger to create an apis system. Which has json as entry and exit points.
from flask import Flask
app = Flask(__name__)
Swagger(app)
#app.route('/some_url', methods=['POST'])
def get_output():
return json.dumps({"status":"Success"})
The Input for above is e.g.
{"username":username,"password":password,}
Like Above I have several other methods either GET or POST.
Is it possible to log the entry exit points E.g. as in Above Example I should be able to log following
{"username":username,"password":password,} as entry point
{"status":success} as exit point.
As well if some error should be able to log it. Looking forward for right way of doing same.
There are some decorators can help you to achieve that.
You can log request.path, request.head, request.args, request.form, request.data in #app.before_request.
You can log response.data in #app.after_request.

Modular routes in python flask

I am trying to have one service which will fulfill two related functions. I would like to have something like this for my REST api:
/route1/get/as_text
/route2/get/as_json
In nodejs, you can pass off a collection of routes from some base URL by saying:
app.use('/route1/', route1.js)
app.use('/route2/', route2.js)
and then the route1.js will have routes defined like this:
app.router('/as_text', function(){//some stuff})
When I do this, can define a set of routes, that all have /route1/ as the basis of the URL. I would like to do something similar in flask, where I just define the first section of the url, and add all logic of that section of the API into a file which is separate to another section of the api.
Is this possible in flask? Or should I look for a new approach?
You'll want to take a look at Blueprints.
When defining your application, you can register Blueprints with a path prefix:
app = Flask(__name__, template_folder='views')
app.register_blueprint(controllers.route1, url_prefix="/route1")
app.register_blueprint(controllers.route2, url_prefix="/route2")
Then define the controllers for these routes in separate files.
route1 = Blueprint('route1', __name__, template_folder='views')
#route1.route('/get/as_text',methods=['GET'])
def get_as_text_route():
return json.jsonify(data="my data")
You could also checkout Flask Restful for creating REST APIs in with Flask.

Categories

Resources