Flask Basics
Flask Basics
Install Flask:
After the installation is complete, you can verify it by checking the Flask version:
flask --version
Flask
Flask is a micro web framework written in Python. It is designed to be lightweight, modular,
and easy to use, providing the essentials for building web applications without imposing too
much structure or dependencies. Flask is classified as a micro-framework because it keeps
the core simple and extensible, allowing developers to choose the components they need
for their specific project.
Routing:
Example:
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, World!'
@app.route('/about')
def about():
if __name__ == '__main__':
app.run(debug=True)
Templates:
Feature: Flask includes a built-in Jinja2 template engine for dynamic content in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
Python code
app = Flask(__name__)
@app.route('/')
def home():
if __name__ == '__main__':
app.run(debug=True)
Request and Response Handling:
pythoncode
app = Flask(__name__)
@app.route('/api/greet', methods=['POST'])
def greet():
data = request.get_json()
if __name__ == '__main__':
app.run(debug=True)
Variable Rules:
Example: pythoncode
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
if __name__ == '__main__':
app.run(debug=True)
Static Files:
Feature: Serve static files like CSS, JavaScript, and images.
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
Redirects:
Example:
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'
@app.route('/redirect_example')
def redirect_example():
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
Configuration:
Example:
# config.py
class Config:
DEBUG = True
SECRET_KEY = 'mysecretkey'
# app.py
app = Flask(__name__)
app.config.from_object('config.Config')
@app.route('/')
def home():
if __name__ == '__main__':
app.run(debug=True)
Flask, on its own, is not a web server. Instead, Flask is a web framework, which means it
provides a set of tools, libraries, and conventions for building web applications in Python.
While Flask handles routing, request handling, and other aspects of web development, it
relies on a web server to handle the actual HTTP communication.
1. Flask Application:
You create a Flask application by defining routes, view functions, and other components.
Flask provides the framework for handling incoming HTTP requests and generating
appropriate responses.
app = Flask(__name__)
@app.route('/')
def home():
if __name__ == '__main__':
app.run(debug=True)
2. WSGI Server:
When you run your Flask application using app.run(), Flask uses a WSGI (Web Server
Gateway Interface) server to handle the communication between your application and the
outside world.
The WSGI server acts as an interface between your Flask application and the web server.
python your_app.py
The built-in development server that comes with Flask is suitable for development, but it is
not recommended for production use. In production, a more robust WSGI server, such as
Gunicorn or uWSGI, is commonly used.
3. Web Server:
∙ The WSGI server communicates with a web server, which is responsible for receiving
incoming HTTP requests from clients (like web browsers) and forwarding them to the
WSGI server.
∙ The web server also takes care of sending the responses generated by the Flask
application back to the clients.
4. Handling Requests and Responses:
∙ When a user accesses your Flask application by visiting a URL, the web server forwards
the request to the WSGI server.
∙ The WSGI server then invokes the appropriate Flask view function based on the
requested URL.
∙ The view function processes the request and returns a response, which is sent back
through the WSGI server and ultimately delivered to the client by the web server.
Flask is a web framework that sits on top of a WSGI server, which, in turn, communicates
with a web server. The combination of Flask, the WSGI server, and the web server allows
you to build and deploy web applications written in Python. Flask abstracts away many of
the complexities of handling HTTP requests and responses, making it easier for developers
to focus on building the core functionality of their web applications.
1. Project Root:
The main directory containing your entire Flask project.
2. Application Package:
Create a Python package (a directory with an __init__.py file) to organize your application's
modules and resources.
/your_flask_project
/your_application
templates/
index.html
7. static/:
The static directory is where you store static files like stylesheets, JavaScript, and images.
Use the url_for('static', filename='...') function to reference these files in your
templates. /your_flask_project
/your_application
static/
css/
style.css
js/
script.js
images/
logo.png
8. config.py:
The config.py file can be used to store configuration settings for your application.
It might contain settings related to the database, security, and other configurations.
# config.py
class Config:
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db'
9. run.py:
The run.py file is used to start your Flask application.
It typically includes code to create the Flask app instance and run it.
# run.py
from your_application import app
if __name__ == '__main__':
app.run()
This is a basic structure, and we can customize it based on the complexity and requirements
of your application.
Variable rules:
Variable rules are used to capture variable parts in the URL, allowing you to create dynamic
routes. Variable rules are specified in the route pattern, and the values captured from the URL
are passed to the corresponding view function as parameters. Here are the key points about
variable rules in Flask:
1. URL Variables:
∙ Variable rules are denoted by <variable_type:variable_name> in the route
pattern.
∙ variable_type specifies the type of the variable (e.g., string, int, float). ∙
variable_name is the name by which you can reference the captured value in your
view function.
Example: @app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
2. Variable Types:
Flask supports different variable types such as string (<string:variable_name>),
integer (<int:variable_name>), and float (<float:variable_name>).
You can customize the type conversion for variables using converters.
Example:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
3. Multiple Variables:
You can have multiple variable rules in a single route pattern.
Example:
@app.route('/path/<variable1>/<variable2>')
def my_function(variable1, variable2):
# Access both variables here
return 'Values: %s, %s' % (variable1, variable2)
4. URL Building:
Flask provides the url_for function to build URLs for your routes, automatically
handling variable values.
Example: url = url_for('show_user_profile', username='john_doe')
Variable Rules in Views:
URL building
URL building is a crucial aspect that allows you to create dynamic URLs for routes defined
in your application. The url_for function is used for this purpose. Here's how you can use
URL building in Flask:
url_for can also be used to generate URLs for redirects or external links.
from flask import Flask, url_for, redirect
app = Flask(__name__)
@app.route('/redirect_example')
def redirect_example():
# Redirect to the 'hello' route with a specific name
return redirect(url_for('hello', name='Bob'))
Static Files:
Use url_for to generate URLs for static files located in the static folder.
<!-- In a template -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> This
example generates a URL for a CSS file named 'style.css' in the static folder.
URL building is a powerful feature in Flask that allows you to create flexible and
maintainable applications by referencing routes and resources using logical names rather than
hardcoding URLs. It ensures consistency and makes it easier to update URLs when needed.
In Flask, static files such as stylesheets, images, and JavaScript files are typically stored in
the static folder. The url_for function is used to generate URLs for these static files. Here's a
clear example and explanation:
Folder Structure:
Ensure that your Flask project has a static folder at the top level. Inside the static folder, you
can organize your static files into subfolders based on their types (e.g., static/css, static/js,
static/images).
Example:plain text
/your_flask_project
/static
/css
style.css
/js
script.js
/images
logo.png
app.py
Using url_for for Static Files:
In your templates or route handlers, you can use the url_for function to generate URLs for
static files. The syntax is url_for('static', filename='path/to/file').
Example:
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Example in a Template:
In your HTML templates, you can use the url_for function to create links to your static files.
Example: html
<body>
<h1>Welcome to my Flask App</h1>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
In this example:
The CSS file is linked using url_for('static', filename='css/style.css').
The image is included using url_for('static', filename='images/logo.png').
The JavaScript file is included using url_for('static', filename='js/script.js').
Run Your Flask App: