How to use Flask in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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
run()
method.
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 (http://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.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚