Ashutosh Krishna
Ashutosh Writes

Follow

Ashutosh Writes

Follow
Getting Started With Flask

Getting Started With Flask

Ashutosh Krishna's photo
Ashutosh Krishna
ยทOct 10, 2022ยท

6 min read

Play this article

Introduction

Flask is a simple, easy-to-use microframework for Python that can help build scalable and secure web applications. It's easy to set up and is being supported by a large community. Thus it is considered quite easy to get started with Flask rather than other Python web frameworks like Django. It's also flexible enough, so if you want more functionality, you can add more extensions.

Installation

Before you install Flask, make sure you have Python installed in your system. You can check using the python command as given below:

$ python
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

If you didn't get similar output, download and install Python from here.

Next, we are going to create a virtual environment using virtualenv. Python now ships with a pre-installed virtualenv library. So, to create a virtual environment, you can use the below command:

$ python -m venv env

The above command will create a virtual environment named env. Now, we need to activate the environment using the command:

$ . env/Scripts/activate

To verify if the environment has been activated or not, you can see (env) in your terminal.

After you have activated the environment, you are ready to install Flask with the below pip command:

$ pip install Flask

This will install Flask and few other dependencies that come with it. To check what all has been installed, you can run the below command:

$ pip freeze

# OUTPUT
click==8.0.3
colorama==0.4.4
Flask==2.0.2
itsdangerous==2.0.1
Jinja2==3.0.2
MarkupSafe==2.0.1
Werkzeug==2.0.2

We can also put these all into a requirements.txt file using the command:

$ pip freeze > requirements.txt

Hello World in Flask

If you check the official documentation of Flask, you'll find a minimal application there. But as discussed above, we're not going to follow that. But we are going to write an application that is more extensible and has a good base structure for even larger applications. So, let's dive in.

Our application will exist within a package called core. To convert a usual directory to Python package, we just need to include a __init__.py file. So, let's create our core package first.

$ mkdir core

After that, let's create the __init__.py file inside the core directory:

$ cd core
$ touch __init__.py
$ cd ..

Now that the required file has been created, we can add the following content there:

from flask import Flask

app = Flask(__name__)

In the above Python script, we are first importing the Flask class from the flask module that we have installed. Next, we're creating an object app of class Flask. We use the __name__ argument to indicate the app's module or package so that Flask knows where to find other files such as templates.

Next, we need to create a routes.py file. But what goes inside that file? Inside the routes.py file, we add various routes for our application. The routes are the different URLs that the application implements. These routes are handled by Python functions called view functions. Each view function is mapped with a route using Python decorators. So, within the core package, create a routes.py file and add the following content inside that:

from core import app

@app.route('/')
def say_hello():
    return "Hello World!"

In the above script, we first imported the app object from the core package. Further, we're creating a Python function called say_hello() which just returns a string "Hello World!". This function, or view function, is mapped with a URL "/" using @app.route decorator. It means, whenever someone visits the "/" route, say_hello() method is responsible to handle the request.

Now that we have a route created, let's import it in the a __init__.py file as:

from flask import Flask

app = Flask( __name__ )

from core import routes # Add this line

In the above script, we just imported the routes from core package. The thing that needs to be noticed is, we did this at the bottom of the file and not at the top. This is done just to avoid a common problem of circular imports in Python.

Now, we have done most of the things. We just need a top-level Python script to run the application. So, outside the core package, create a main.py file and add the following content:

from core import app

if __name__ == ' __main__':
    app.run(debug=True)

In the above script, we first imported the app object from the core package. Then inside the Python main method, we are running the app using the run method. By enabling debug mode using debug=True, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.

Warning: The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.

Now, we are ready to run our first application in Flask. And, we can run the server just as we run a Python file using the python main.py command:

$ python main.py
 * Serving Flask app 'core' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 131-151-153
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Once, you run the server, you'll get the above output. You'll find a URL in the last line. If you open that in your browser, you will be welcomed with a Hello World! message.

Hurray! We just created our first application.

Directory and File Structure

To build a web application, we need more than just routes. We need HTML files, static files such as CSS files, Javascript files and images, database models, and other configurations.

  1. config.py file: This file lies outside the core package and contains various configurations such as DEBUG, or database details such as URI.
  2. core/models.py: This is where the models are defined. A model is a representation of a database table in code.
  3. /core/templates: This is the directory where all HTML files will go.
  4. /core/static: This is where static files such as CSS and JavaScript files as well as images usually go.

Configurations

In the config.py file, let's add the following content.

class Config(object):
    SECRET_KEY = 'guess-me'
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True

class ProductionConfig(Config):
    DEBUG = False
    MAIL_DEBUG = False

class StagingConfig(Config):
    DEVELOPMENT = True
    DEBUG = True

class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True

class TestingConfig(Config):
    TESTING = True

In the above script, we have created a Config class and defined various attributes inside that. Also, we have created different child classes(as per different stages of development) that inherit the Config class. Now, we can use these configurations in the a __init__.py file as:

from flask import Flask
from config import DevelopmentConfig # Add this line

app = Flask( __name__ )
app.config.from_object(DevelopmentConfig) # Add this line

from core import routes

Conclusion

So far, we have created a simple Hello World application. Also, we saw how various files are organized to form a good base structure. In the next blog, we'll create a News Application and make use of the static and templates directory there. Till then, stay tuned!

Did you find this article valuable?

Support Ashutosh Krishna by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this