Flask is a popular micro web framework for building web applications in Python. It provides a simple and lightweight way to create web applications, APIs and handle HTTP requests and responses.
Here are the basic steps to use Flask in Python:
- Install Flask by running
pip install Flask
- Import the flask module and create a Flask application instance.
from flask import Flask app = Flask(__name__)
- Define the routes and the corresponding functions to handle the request/response.
@app.route("/") def hello(): return "Hello, World!"
- Run the application by calling the
if __name__ == "__main__": app.run()
Here's an example of a simple Flask application that listens on the root route (
'/') and returns a simple text message:
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" if __name__ == "__main__": app.run()
The above code will start the server at default address (https://127.0.0.1:5000/) and when you visit the root route, it will return the text "Hello, World!".
Flask provides many useful features, such as support for handling different request methods, handling templates and serving static files, handling cookies and sessions, and more. It's also very easy to set up and use, and it's a great choice for building small to medium-sized web applications and web APIs.