Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Flask Basics

The document provides detailed installation steps for Flask, a lightweight Python web framework, including commands for installation and verification. It outlines key features of Flask such as routing, templates, request handling, and static file management, along with examples of code for each feature. Additionally, it explains the structure of a Flask application and the use of variable rules and URL building for dynamic content handling.

Uploaded by

waliwos724
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Flask Basics

The document provides detailed installation steps for Flask, a lightweight Python web framework, including commands for installation and verification. It outlines key features of Flask such as routing, templates, request handling, and static file management, along with examples of code for each feature. Additionally, it explains the structure of a Flask application and the use of variable rules and URL building for dynamic content handling.

Uploaded by

waliwos724
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

FLASK INSTALLATION STEPS:

Install python with pip


To install Flask, you can use a package manager for Python, such as pip. Here are the steps
to install Flask:

Open a Terminal or Command Prompt:

On Windows, you can use Command Prompt or PowerShell.

On macOS and Linux, use the Terminal.

Install Flask:

Run the following command to install Flask using pip:

pip install Flask

Verify the Installation:

After the installation is complete, you can verify it by checking the Flask version:

flask --version

This should display the installed 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.

Key features and characteristics of Flask include:

Routing:

Feature: Define URL routes and associated view functions.

Flask uses decorators to map URL patterns to Python functions.

Example:

from flask import Flask

app = Flask(__name__)

@app.route('/')

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

def about():

return 'This is the about page.'

if __name__ == '__main__':

app.run(debug=True)

Templates:

Feature: Flask includes a built-in Jinja2 template engine for dynamic content in

HTML. Templates help separate HTML and Python code.

Example: Html code

<!-- templates/index.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{{ title }}</title>

</head>

<body>

<h1>{{ message }}</h1>

</body>

</html>

Python code

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')

def home():

return render_template('index.html', title='Home', message='Welcome to the Home Page')

if __name__ == '__main__':
app.run(debug=True)
Request and Response Handling:

Feature: Handle HTTP requests and generate responses. Flask provides

methods to access request data and generate responses. Example:

pythoncode

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/greet', methods=['POST'])

def greet():

data = request.get_json()

name = data.get('name', 'Guest')

return jsonify({'message': f'Hello, {name}!'})

if __name__ == '__main__':

app.run(debug=True)

Variable Rules:

Feature: Capture variable parts in the URL.

Variable rules allow dynamic URLs.

Example: pythoncode

from flask import Flask

app = Flask(__name__)

@app.route('/user/<username>')

def show_user_profile(username):

return f'User: {username}'

if __name__ == '__main__':

app.run(debug=True)

Static Files:
Feature: Serve static files like CSS, JavaScript, and images.

The url_for function is used to generate URLs for static files.

Example: python code

from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/')

def home():

return render_template('index.html')

if __name__ == '__main__':

app.run(debug=True)

html code

<!-- templates/index.html -->

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>My Flask App</title>

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

</head>

<body>

<h1>Welcome to my Flask App</h1>

</body>

</html>

Redirects:

Feature: Perform redirects to other routes.

The redirect function is used to redirect users to a different route.

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:

Feature: Customize application configuration.

Configuration settings can be stored in a separate configuration file.

Example:

# config.py

class Config:

DEBUG = True

SECRET_KEY = 'mysecretkey'

# app.py

from flask import Flask

app = Flask(__name__)

app.config.from_object('config.Config')

@app.route('/')

def home():

return 'Debug Mode: {}'.format(app.config['DEBUG'])

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

These are some examples that have a fundamental features of Flask.

How flask is a web server

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.

Here's how the typical interaction works:

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.

from flask import Flask

app = Flask(__name__)

@app.route('/')

def home():

return 'Hello, World!'

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.

Basic structure of flask application


A Flask application follows a basic structure that includes directories and files to organize
various components of the application. While Flask is designed to be flexible, and you can
adapt the structure based on our needs, a common and recommended structure includes the
following components:

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.

This package will contain the core of your application.


/your_flask_project
/your_application
__init__.py
routes.py
models.py
templates/
static/
config.py
run.py
__init__.py:
3. The __init__.py file makes the directory a Python package.
It may contain initialization code for your application.
4. routes.py:
∙ This file typica lly contains the route definitions and view functions. ∙ Routes define the
URL patterns, and view functions handle the logic for generating responses.
# routes.py
from flask import render_template
from your_application import app
@app.route('/')
def home():
return render_template('index.html')
5. models.py:
If your application involves data models, database interactions, or business logic, you might
have a models.py file.
This is where you define your data models using an Object-Relational Mapping (ORM) tool
like SQLAlchemy.
# models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
# Model definition here
6. templates/:
The templates directory is where you store your Jinja2 templates for rendering
HTML. Flask expects templates to be located in this directory by default.

/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:

5. Variable Rules in Views:


When defining a view function for a route with variable rules, you can include
parameters in the function signature to receive the captured values.
Example:
@app.route('/user/<username>/<int:user_id>')
def show_user(username, user_id):
return f'User: {username}, ID: {user_id}'
6. Default Values:
You can provide default values for variables in the route pattern.
Example:
@app.route('/user/<username>/<int:user_id>')
def show_user(username, user_id=1):
return f'User: {username}, ID: {user_id}'
Variable rules in Flask provide a flexible way to handle dynamic content and user
input in your web applications by allowing your routes to respond to different patterns of
URLs.

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:

Basic URL Building:

∙ Import the url_for function from the Flask module.


∙ Use url_for by providing the name of the route's view function and any necessary
arguments.
Example:
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
with app.test_request_context():
url = url_for('hello', name='John')
print(url)
The URL for the hello route with the argument name set to 'John' will be generated.
Generating URLs in Templates:

You can use url_for within templates to create dynamic links.


<!-- In a template -->
<a href="{{ url_for('hello', name='Alice') }}">Visit Alice's
profile</a> Redirects and External URLs:

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

<!-- index.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Static Files Example</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>

<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:

Save your changes and run your Flask app.


python app.py
Visit http://127.0.0.1:5000/ in your web browser to see the index page with the static files
properly linked.
Using the static folder and the url_for function helps you organize and serve static files
efficiently in your Flask application. It also allows you to easily update file paths if your
project structure changes.

You might also like