Flask Basics
1. Routing in Flask
Routing in Flask refers to the process of mapping URLs to specific functions in your application. This allows users to access different parts of your web application by navigating to different URLs.
For example, if you want to create a homepage for your website, you can define a route for the root URL ("/") and associate it with a function that returns the content of the homepage.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the Homepage!' if __name__ == '__main__': app.run()
In this example, the @app.route('/')
decorator maps the root URL to the home()
function, which returns the string "Welcome to the Homepage!" when accessed.
2. Templates in Flask
Templates in Flask allow you to separate the presentation logic from the business logic. This is achieved using the Jinja2 templating engine, which enables you to create dynamic HTML pages by embedding Python code within HTML.
For instance, you can create a template file named index.html
and use it to render dynamic content. The template can include placeholders for variables, loops, and conditional statements.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html', title='Home', message='Welcome to our site!') if __name__ == '__main__': app.run()
In this example, the render_template()
function is used to render the index.html
template. The template can then use the title
and message
variables to display dynamic content.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>{{ message }}</h1> </body> </html>
Here, the {{ title }}
and {{ message }}
placeholders will be replaced with the values passed from the render_template()
function.