Learn Flask - Clean Architecture
In our last experiment, we have seen that it's fairly easy to create a single page app with Flask. But, in any other project, we will have different pages and url to use.
Here is the architecture I love.
Let's go !
Let's make sure flask is there (type this in terminal):
pip3 install flask
(type this in terminal)
For this first episode, our code will mainly be in a package.
Let's create our package flask_app
:
mkdir flask_app
Then let's create one python file in the same directory as flask_app
:
touch worker.py
We are not gonna write code into those right now.
Now I will put the path to the file we are talking about just before the codeblock balise
exemple:
/flask_app/__init__.py
int_instance = 1 # don't put that in your code
Then, we will need to import flask and create a instance of the Flask
class
/flask_app/__init__.py
from flask import Flask
app = Flask(__name__)
Create a new file in flask_app
:
touch flask_app/views.py
In flask_app/views.py
import the app
instance from __init__.py
, with flask, we don't have to worry about circular import on this particular case. So:
flask_app/views.py
from flask_app import app
# let's add some route
#basic endpoint
@app.route('/')
def index():
return 'hello world!'
# in case of 404 http error, send the error
@app.errorhandler(404)
def error_handler_404(error):
return str(error)
Then we have to import our views back into __init__.py
/flask_app/__init__.py
from flask import Flask
app = Flask(__name__)
from flask_app import views
Now let's head back to worker.py
previously created.
# import Flask instance
from flask_app import app
if __name__ == "__main__":
app.run()
Run flask_app.py
with this
export FLASK_ENV=development
export FLASK_APP=flask_app
flask run
Then visit http://127.0.0.1:5000/ on your browser !
Don't forget, you can find this code here !
You made it to the end, bravo! If you have any questions, don't forget to ask. See you next time! If you spot a grammar or vocabulary mistake, please let me know in the comments.
You will be able to find a good part of the articles in this account in this repository.
To go directly to the section you are currently viewing click here.