Flask in Python

Flask is a lightweight and versatile web framework for Python, known for its simplicity and ease of use in building web applications. With its minimalistic design, it provides just what you need to quickly get a web server up and running. Let's dive into the basics of setting up a Flask application.

Installation of Flask in Python

First things first, let's ensure Flask is installed. You can install it via pip.

pip install Flask   # Windows
pip3 install Flask  #Macos

Creating a Simple Flask App

Let's create a simple Flask application that displays a "Hello, World!" message.

Create a file named main.py and add the following code.

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

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

This code does the following.

  • Initializes a Flask app.
  • Defines a route ('/') that triggers the hello() function when someone visits the root URL.
  • The hello() function returns 'Hello, World!' when the route is accessed.

Running the Flask App

To run the Flask app, execute the following command in your terminal.

python main.py    #Windows
python3 main.py   #Macos

This will start the Flask development server on http://127.0.0.1:5000/ by default. Open a web browser and go to this URL. You should see 'Hello, World!' displayed on the page.

Dynamic Routing

Flask allows for dynamic routing, where URLs can contain variable parts. Let's modify our app to take a user's name as input and display a personalized message.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

@app.route('/api/users')
def get_users():
    return jsonify('Have a look at all these users'), 200

@app.route('/api/getauser/<user_id>')
def getauser(user_id):
    return jsonify(f'Have a look at this specific user that you requested : {user_id}'), 200

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

Conclusion

Flask's simplicity and flexibility make it an excellent choice for developing web applications in Python. This article covers the basics to get you started, but Flask offers much more, including template rendering, handling forms, interacting with databases, and more. I will keep adding more article around Flask in python.

Explore the Flask documentation (Flask Documentation) and its vast ecosystem to discover the full potential of this powerful web framework.

Happy coding with Flask.


Similar Articles