Welcome to the Flask Tutorials on CodeYourCraft! In this comprehensive guide, we'll walk through the basics of Flask, a powerful Python web framework, and help you build your first web application. By the end of this lesson, you'll have a solid understanding of Flask's structure and be ready to take on more advanced topics. Let's get started! 🚀
Flask is a micro web framework for Python, perfect for building small to medium-sized web applications. It's easy to learn, highly flexible, and comes with a built-in development server, making it ideal for beginners and seasoned developers alike.
To start a Flask project, first, make sure you have Python and Flask installed on your system. You can install Flask using pip:
pip install flaskNext, create a new directory for your project and navigate into it:
mkdir my_flask_app
cd my_flask_appNow, create a new Python file called app.py. In this file, we'll write our Flask code.
Every Flask application starts with creating a Flask web server. To create a server, we first import the Flask module and then create an instance of the Flask class.
from flask import Flask
app = Flask(__name__)Routes in Flask define the URLs that our web application will respond to. By default, Flask listens on the http://127.0.0.1:5000 address. To create a route, we use the @app.route() decorator.
@app.route('/')
def home():
return "Welcome to my Flask app!"Now, let's run our Flask application:
python app.pyYour browser should now open automatically and display "Welcome to my Flask app!" on the screen. 🎉
To handle parameters in our routes, we can access them using the request object. Here's an example of a route that accepts a parameter:
@app.route('/hello/<name>')
def hello(name):
return f"Hello, {name}!"Accessing this route with http://127.0.0.1:5000/hello/Alice will display "Hello, Alice!".
Flask allows you to serve static files like CSS, JavaScript, and images. To serve a static file, create a static directory and place your files inside.
mkdir static
touch app.cssThen, in your app.py, add the following code to make the static directory accessible:
@app.route('/static/<path:filename>')
def send_static(filename):
return send_from_directory('static', filename)Now, you can link to your CSS file in your HTML templates:
<link rel="stylesheet" type="text/css" href="{{ url_for('send_static', filename='app.css') }}">What is the primary purpose of Flask in web development?
That's it for our introduction to Flask! In the next lesson, we'll dive deeper into Flask templates, forms, and routing. Stay tuned! 🤓