Python | Introduction to Web development using Flask

Python | Introduction to Web development using Flask

Flask is a micro web framework written in Python. The term "micro" denotes that Flask aims to keep the core of the application simple but extensible. Flask doesn't come with built-in tools like form validation or a database abstraction layer but provides support to add such tools as needed.

Here's a brief introduction to web development using Flask:

Installation:

To get started, you need to install Flask. This can be done using pip:

pip install Flask 

Basic Application:

Here's a simple Flask application:

from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' 

If you save the above code as app.py and run it:

python app.py 

Visiting http://127.0.0.1:5000/ in your web browser will display "Hello, World!"

Routes and Views:

In Flask, you define routes using the @app.route() decorator above a function. The function that is associated with a route is called a view function. When the route is visited, the associated view function is executed and its return value is sent to the client as a response.

For example:

@app.route('/about') def about(): return 'About Page' 

Templates:

Flask integrates with Jinja2 for templates, allowing you to return dynamic HTML content from your routes.

For instance:

  • Create a folder named templates in your project directory.
  • Inside the templates folder, create a file named index.html with the following content:
<!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome, {{ name }}!</h1> </body> </html> 
  • In your Flask application:
from flask import render_template @app.route('/welcome/<name>') def welcome(name): return render_template('index.html', name=name) 

Visiting http://127.0.0.1:5000/welcome/John will display "Welcome, John!" using the template.

Static Files:

If you want to serve static files (like CSS or JavaScript), place them in a folder named static in your project directory. You can then reference them in your templates or routes using url_for('static', filename='filename.ext').

Extensions:

Flask has a rich ecosystem of extensions, from form handling (e.g., Flask-WTF) to database integrations (e.g., Flask-SQLAlchemy). You can extend the functionality of your Flask app using these extensions.

Conclusion:

This is a very basic introduction to Flask. Flask's simplicity, combined with its extensibility, makes it a popular choice for both beginners and experienced developers looking to create web applications in Python.


More Tags

stm32f0 image-uploading bundler pylint flutter-packages cumulative-sum if-statement uiimageview asyncstorage ios6

More Programming Guides

Other Guides

More Programming Examples