Writing function-based views and URL routes
This is the simplest way of writing views and URL routes in Flask. We can just write a method and decorate it with the endpoint.
Getting ready
To understand this recipe, we can start with any Flask application. The app can be a new, empty, or any complex app. We just need to understand the methods outlined in this recipe.
How to do it…
The following are the three most widely used, different kinds of requests, demonstrated with short examples.
A simple GET request
Consider the following code:
@app.route('/a-get-request') def get_request(): bar = request.args.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar
This is a simple example of what a GET request looks like. Here, we just check whether the URL query has an argument called foo
. If yes, we display this in the response; otherwise, the default is bar
.
A simple POST request
Consider the following code:
@app.route('/a-post-request', methods=['POST']) def post_request(): bar...