This is Part 3 of a series of articles that will walk you through the basics of Flask Web Development by developing and hosting a simple CRUD application.
This series is split into 6 parts:
- A simple Hello World app
- Rendering HTML templates.
- Building a scaleable file structure.
- Configuring a database.
- Handling user login and registration.
- Adding CRUD (Create, Read, Update, Delete) functionality.
Part 3: Building a Scalable File Structure.
Let’s go ahead and set up a more robust file structure.
This structure give us 3 main directories:
- Backend: Houses all our Python files that handle routing, CRUD actions, and form validation.
- Static: Houses all our image, JS, and CSS files. These will be stored on the client side in their browsers cache.
- Templates: Houses all our HTML files.
Within the backend directory there are 3 .py files and a sub-directory, also with 3 .py files.
- config.py: This will set up our app and our database.
- forms.py: This will create all the flask forms.
- index.py: This will handle all the requests and routing.
- CRUD/create.py: This will contain all of our functions that create database objects.
- CRUD/update.py: This will contain all of our functions that update database objects.
- CRUD/delete.py: This will contain all of our functions that delete database objects.
Now let’s move our app configuration code to our config.py file and our routes to the index.py file.
First we will move this code to the config.py file.
from flask import Flask
app = Flask(__name__)
Next, we will add an argument to the line where we create the instance of the Flask class.
from flask import Flask
app = Flask(__name__, template_folder='../templates')
Since we are going to be putting our routes in our index.py file within the ‘backend’ directory this will tell flask where to look for our HTML templates within our new file structure.
Then we will move this code to the index.py file.
from config import app
from flask import Flask, email@example.com('/')
Now our app.py file is just:
if __name__ == '__main__': app.run(host="localhost", port=8000)
Lastly, we will update our imports in our app.py file to access the new files we made.
from config import appif __name__ == '__main__': app.run(host="localhost", port=8000)
Don’t worry about the specifics of the rest of the files yet. We will be adding to them throughout the rest of the series.
The source code for this part can be found at my GitHub here:
In the next post we will use this new file structure to configure a database for our app.