Skip to main content

Flask course for beginners


Important Topics in Flask

  1. Routing

    Flask uses the concept of routing to determine which function to call based on the URL requested by the client. A simple example would be mapping the root URL '/' to a function that returns the home page of a website. The routing mechanism can also include dynamic parts in the URL to capture values and pass them as arguments to the handling function.

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return "Hello, World!"
    
    @app.route('/greet/<name>')
    def greet(name):
        return f"Hello, {name}!"
    
    if __name__ == '__main__':
        app.run()
    
  2. Templates

    Flask uses the Jinja2 templating engine to generate dynamic HTML content. This allows you to separate the presentation logic from the Python code that generates the data. A template can include variables, loops, and control structures, which get evaluated and replaced with actual values when the template is rendered.

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/greet/<name>')
    def greet(name):
        return render_template('greet.html', name=name)
    
    if __name__ == '__main__':
        app.run()
    
    

    In this example, the render_template function from the flask module is used to render HTML templates. The first route maps to the root URL '/' and returns the template index.html. The second route maps to the URL '/greet/<name>' and includes a dynamic component <name> in the URL. The function greet takes the name as an argument and passes it to the template greet.html.

    The templates are stored in a templates folder in the same directory as the application code. Here's an example of the index.html template:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Index</title>
    </head>
    <body>
      <h1>Hello, World!</h1>
    </body>
    </html>
    
    

    And here's an example of the greet.html template:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Greet</title>
    </head>
    <body>
      <h1>Hello, {{ name }}!</h1>
    </body>
    </html>
    
    

    In the templates, placeholders surrounded by double curly braces (e.g. {{ name }}) are replaced with values passed to the template. In this example, the greet route passes a name argument to the greet.html template, which is used to replace the {{ name }} placeholder in the template.

  3. Forms

    HTML forms allow users to input data, which can then be processed by a Flask application. Flask provides a convenient way to handle form submissions, validate user input, and extract data from the form fields.

    Forms are an essential part of many web applications, as they allow users to input and submit data. Flask provides support for handling forms through the WTForms library.

    Here's a simple example of using forms in Flask:

    from flask import Flask, render_template, request
    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    
    class NameForm(FlaskForm):
        name = StringField('What is your name?')
        submit = SubmitField('Submit')
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = NameForm()
        if form.validate_on_submit():
            name = form.name.data
            return f'Hello, {name}!'
        return render_template('index.html', form=form)
    
    if __name__ == '__main__':
        app.run()
    

    In this example, a form class NameForm is defined, which inherits from FlaskForm and contains a single text field and a submit button. The form is then passed to the template index.html, where it is rendered.

    When the form is submitted, the index view checks if the form data is valid (e.g. the name field is not empty), and if it is, the name is extracted from the form and displayed.

    Here's an example of the index.html template:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Index</title>
    </head>
    <body>
      <h1>Enter your name:</h1>
      <form method="post">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name }}
        {{ form.submit }}
      </form>
    </body>
    </html>
    

    In this template, the form is rendered using the form object passed from the view. The hidden_tag method is used to include a CSRF token in the form, to protect against cross-site request forgery attacks. The label, name, and submit attributes of the form are used to render the form elements.

  4. Database Integration

    Flask supports a variety of databases, including relational databases such as MySQL and PostgreSQL, and NoSQL databases such as MongoDB. The Flask-SQLAlchemy extension provides a high-level, Object-Relational Mapping (ORM) interface to the database, allowing you to interact with the database using Python code instead of writing raw SQL queries.

  5. Session and Cookies

    Sessions allow you to store data specific to a user across multiple requests. Flask uses cookies to persist the session data on the client side. Cookies are small text files stored on the client's device, while the session data is stored on the server.

  6. Error Handling

    Flask provides a mechanism for handling errors that occur during the processing of a request. For example, you can catch exceptions raised in your code and return a custom error page to the user. Logging errors can also be useful for debugging and keeping track of problems in production.

  7. Security

    Web applications are vulnerable to various security threats, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). Flask provides several tools and best practices for protecting against these and other security threats, such as input validation and escaping user-generated content.

  8. Deployment

    Flask applications can be deployed on various production environments, such as web servers, cloud platforms, and containerized environments. Deployment options include using a platform-as-a-service (PaaS) provider like Heroku, deploying to a virtual machine on a cloud provider such as Amazon Web Services (AWS), or using a container orchestration platform such as Kubernetes.

Comments