The REST Server
Set up a FLASK service using Flask and FlaskLogin.
About the application
In this application, we can see how administrative and database routes are configured as Flask blueprints. We can look into the connect
call that ensures the database’s existence. Next, we’ll have session management that includes authenticating a user with proper validation checks, invalidating the session, and so on. It will also return the status code as a response.
This is what the application looks like:
Note: To test the database, please run the widget and follow the instructions explained below.
Copyright (c) 2020 John Sheehan Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Configuring Flask service
Now that we have the database in place, let’s work on the back-end Flask server that will access it. So, to serve this purpose, we have a module appserver.py
that needs to go into the bookapp/server/
folder.
Initially, we can see some logging and a few constants.
Then, at line 35, there is a call to the connect()
function in the appserver.py
module to make sure the database exists before trying to use it.
The actual routes for our REST API are defined in separate modules that are set up as Flask blueprints:
- Line 20: For general admin use.
- Line 21: For database access.
Dealing with session management
We can also set up user session management using Flask-Login, the response headers at lines 66 and 68, and default handlers for unauthorized and unknown requests at line 43. At line 72, the only actual route that is set up here ...