0% found this document useful (0 votes)
14 views35 pages

Flaskmega Python

Uploaded by

Tayamika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views35 pages

Flaskmega Python

Uploaded by

Tayamika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Flask Mega

Status In progress

Note: to find out if python is installed on your windows


machine go to the terminal and type python/python3.

Microblog/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── config.py # <-- Now in the correct place
│ └── templates/
│ └── index.html
├── venv/
└── microblog.py
#current structure

topic 1 (project directory, flask, and virtual space)

1. Creating the Project Directory


First, you need a place to store your project files. In your case, you created the
Microblog project under:
Path:

C:\Users\tayam\OneDrive\Documents\Projects\Microblog

How you did it:


You either created the folder manually or by running:

Flask Mega 1
mkdir C:\Users\tayam\OneDrive\Documents\Projects\Microblog
cd C:\Users\tayam\OneDrive\Documents\Projects\Microblog

2. Setting Up a Virtual Environment


Python virtual environments let you isolate your project’s dependencies (like
Flask) so that they don’t interfere with other projects on your computer.
How you did it:

python -m venv venv

This creates a venv/ folder inside your Microblog directory, which contains
a separate installation of Python and pip.

Activating the virtual environment:


On Windows, you run:

venv\Scripts\activate

When the virtual environment is activated, your prompt changes to:


(venv) C:\Users\tayam\OneDrive\Documents\Projects\Microblog>

This means any Python commands you run will only affect this
environment.

3. Installing Flask
With the virtual environment activated, you installed the Flask web framework:

pip install flask

Flask Mega 2
Flask was downloaded and installed inside the venv/ folder.

This ensures Flask is available only for this project.

4. Creating the app/ Package


Next, you created a package called app/ . In Python, a package is a folder with
an __init__.py file. Packages group related modules (Python files) together.

How you did it:

mkdir app

5. Writing app/__init__.py
In app/__init__.py , you initialized your Flask app.

from flask import Flask

app = Flask(__name__)

from app import routes

Explanation:

1. app = Flask(__name__)

Creates a new Flask application instance.

The __name__ variable tells Flask the name of the current Python module.

2. from app import routes

Flask Mega 3
This imports the routes.py file (you’ll see it next).
Placing the import at the bottom prevents circular imports, which happen
when two files depend on each other.

6. Writing app/routes.py
In app/routes.py , you defined your first route (or URL) using a view function.

Content:

from app import app

@app.route('/')
@app.route('/index')
def index():
return "Hello, World!"

Explanation:

@app.route('/')

This tells Flask to run the index() function whenever someone visits the /

URL.

@app.route('/index')

This also maps the /index URL to the same index() function.

return "Hello, World!"

When a user visits either / or /index , the browser displays the "Hello,
World!" message.

7. Creating microblog.py
The microblog.py file acts as the entry point for your application. It contains:

Content:

Flask Mega 4
python
Copy code
from app import app

This imports the app instance from the app package, which you created in
app/__init__.py .

8. Setting the FLASK_APP Environment Variable


Before running your Flask app, Flask needs to know where the application
instance is. You set this using the FLASK_APP environment variable.

Command:

bash
Copy code
set FLASK_APP=microblog.py

On Windows, the set command temporarily sets the variable for your current
terminal session.

You can verify it by typing:

bash
Copy code
echo %FLASK_APP%

9. Running the Flask App


Now, you started your Flask web server:

Command:

Flask Mega 5
bash
Copy code
flask run

The output should look like this:

csharp
Copy code
* Running on http://127.0.0.1:5000/ (Press CTRL+C to qui
t)

Explanation:

http://127.0.0.1:5000/ or http://localhost:5000/

This is the local address of your web server.

Flask listens for requests on port 5000. When you visit the URL in a
browser, it runs the index() function and displays "Hello, World!".

10. Stopping the Server


When you’re done testing, press CTRL + C in the terminal to stop the Flask
server.

11. Project Directory Structure


Here’s the complete structure of your project:

bash
Copy code
Microblog/
venv/ # Virtual environment
app/ # Application package
__init__.py # Initializes the Flask app

Flask Mega 6
routes.py # Handles the URLs
microblog.py # Entry point for the app

Summary
1. Created a virtual environment:
python -m venv venv

2. Activated the virtual environment:


venv\Scripts\activate

3. Installed Flask:
pip install flask

4. Created the app/ package and wrote the initial Flask setup in __init__.py .

5. Defined routes in app/routes.py .

6. Created microblog.py as the entry point for the app.

7. Set the FLASK_APP environment variable:


set FLASK_APP=microblog.py

8. Ran the Flask app:


flask run

When you visited http://localhost:5000/, you saw the "Hello, World!"


message!

tutorial 1 in simpler terms


Absolutely, Tayamika! Let’s break it down even more simply and clearly so it all
clicks.

What You Did:


You’re building a basic Flask web application. Here’s what each step really
means, explained in simple terms.

1. Create a Folder for Your Project

Flask Mega 7
You need somewhere to store your code and files for the app.

Think of it like a special drawer where all related documents stay together.
You either created the folder manually or did this from the terminal:

bash
Copy code
mkdir Microblog
cd Microblog

Now you are inside your project folder, ready to write code!

2. Set Up a Virtual Environment


A virtual environment is like a “mini-computer” inside your computer.
Why do this?
It keeps the tools (like Flask) you install for this project separate from other
projects. Without this, different projects could mess each other up by using
different versions of the same tools.
How you did it:

bash
Copy code
python -m venv venv

This made a new venv/ folder inside your project.

Now you need to turn on this environment (kind of like booting a mini-
computer):

bash
Copy code

Flask Mega 8
venv\Scripts\activate

You’ll see (venv) appear at the beginning of the command line, meaning
the virtual environment is active. Anything you install now will only affect
this project.

3. Install Flask
Flask is the tool that makes it easy to create websites with Python.
You installed Flask inside your virtual environment by running:

bash
Copy code
pip install flask

Now your project has Flask, and you’re ready to build a small website!

4. Create a Folder for Your Code


You made a folder called app . This will hold your main code.

bash
Copy code
mkdir app

Every Python project has files and folders that organize the code. You’ll use
the app/ folder to group all the things your site needs to work.

5. Write __init__.py to Start the App


Inside the app/ folder, you created a file called __init__.py .

This file tells Python how to start your website.


Here’s what the code does:

Flask Mega 9
python
Copy code
from flask import Flask

app = Flask(__name__) # Creates your web app

from app import routes # Tells the app where the pages ar
e

Think of app like the “brain” of your website.


It starts the app with Flask(__name__) , and then tells it to look for the web pages
in a file called routes.py .

6. Create a routes.py File for Web Pages


In app/routes.py , you defined what your website will show to visitors.

python
Copy code
from app import app

@app.route('/')
@app.route('/index')
def index():
return "Hello, World!"

Let’s break this down:

1. @app.route('/')

This makes the home page ( / ) of your website. When someone opens
your site in a browser, they’ll land here.

2. @app.route('/index')

Flask Mega 10
This creates another page ( /index ). It will show the same thing as the
home page.

3. return "Hello, World!"

When someone visits / or /index , the page will display the message
"Hello, World!"

7. Create microblog.py (the Entry Point)


You created a file called microblog.py . Think of it as the power button for your
site—it’s the file you run to start everything.
Here’s what it does:

python
Copy code
from app import app

It grabs the app you made in __init__.py so you can run it.

8. Tell Flask What to Run


You need to tell Flask which app to start. You did this by setting an
environment variable:

bash
Copy code
set FLASK_APP=microblog.py

This command tells Flask to look for the app inside the microblog.py file.

9. Run Your Website!


Now it’s time to start your web server and see your site in action.
You ran:

Flask Mega 11
bash
Copy code
flask run

Flask started your site and told you it’s available at:

arduino
Copy code
http://127.0.0.1:5000/

This means your website is now running locally (only on your computer).
Open a web browser and go to http://127.0.0.1:5000/.

You’ll see "Hello, World!" displayed on the page.

10. Stop the Server


When you’re done testing, you can stop the web server by pressing:

mathematica
Copy code
CTRL + C

This shuts down the website running on your computer.

11. Your Project So Far


Here’s what your project structure looks like now:

bash
Copy code
Microblog/
venv/ # Virtual environment (holds Flask and

Flask Mega 12
dependencies)
app/ # Your main code folder
__init__.py # Starts the app
routes.py # Defines web pages (routes)
microblog.py # The file that starts everything

Topic 2 templates

Step 1: Understanding Templates


Templates are files that define the layout of your web pages, allowing you to
separate your application’s presentation from its logic. In Flask, these
templates are usually written in HTML and can include dynamic content using
placeholders and control structures provided by Jinja2, the templating engine
Flask uses.

Step 2: Creating a Mock User


You created a mock user using a Python dictionary to simulate user data:

python
Copy code
user = {'username': 'Miguel'}

Explanation:

This mock object allows you to work on the application without


implementing a full user system yet. It acts as a stand-in for actual user
data.

Step 3: Initial View Function


You began by returning a simple HTML page directly from your view function:

python
Copy code

Flask Mega 13
from app import app

@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
return '''
<html>
<head>
<title>Home Page - Microblog</title>
</head>
<body>
<h1>Hello, ''' + user['username'] + '''!</h1>
</body>
</html>'''

Explanation:

This method hard-coded the HTML response within the view function.
While it works for simple cases, it becomes impractical as your application
grows because you'd have to repeat HTML in multiple functions and
manage it directly in your Python code.

Step 4: Introducing Templates


To manage your HTML more efficiently, you created a templates directory:

mkdir app/templates

Explanation:

This directory will hold all your HTML template files. By keeping templates
separate, you can easily modify the presentation without changing the
logic.

Flask Mega 14
Step 5: Creating the Main Template
You created your first template, index.html :

html
Copy code
<!doctype html>
<html>
<head>
<title>{{ title }} - Microblog</title>
</head>
<body>
<h1>Hello, {{ user.username }}!</h1>
</body>
</html>

Explanation:

In this file, you use placeholders ( {{ ... }} ) for dynamic content. When
rendering the template, Jinja2 will replace these placeholders with actual
values from the view function.

Step 6: Simplifying the View Function


You updated your view function to use the render_template() function:

python
Copy code
from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
return render_template('index.html', title='Home', use

Flask Mega 15
r=user)

Explanation:

This significantly simplifies your view function. The render_template()


function takes care of rendering the index.html template and fills in the
placeholders with the provided variables ( title and user ).

Step 7: Adding Conditional Logic to the Template


You added conditional statements to handle different scenarios for the title:

html
Copy code
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog!</title>
{% endif %}

Explanation:

This allows the template to dynamically adjust based on whether a title is


provided. If no title is supplied, it defaults to "Welcome to Microblog!".

Step 8: Adding Mock Posts


You introduced mock posts to simulate blog content:

python
Copy code
posts = [
{'author': {'username': 'John'}, 'body': 'Beautiful da
y in Portland!'},
{'author': {'username': 'Susan'}, 'body': 'The Avenger
s movie was so cool!'}

Flask Mega 16
]

Explanation:

This creates a list of dictionaries representing posts, allowing you to test


how the application displays multiple entries.

Step 9: Rendering Posts in the Template


You updated your index.html to include a loop that renders each post:

html
Copy code
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body
}}</b></p></div>
{% endfor %}

Explanation:

Using a for loop, the template can dynamically display any number of
posts. The template adapts to whatever data you pass, showing all
available posts.

Step 10: Implementing Template Inheritance


To avoid repeating common HTML structures, you created a base.html

template:

html
Copy code
<!doctype html>
<html>
<head>
{% if title %}

Flask Mega 17
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>

Explanation:

This template contains the common layout for all pages. The {% block
content %} section allows derived templates to insert their unique content

without duplicating the entire layout.

Step 11: Modifying index.html to Use Inheritance


You simplified your index.html to extend from base.html :

html
Copy code
{% extends "base.html" %}

{% block content %}
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.bo
dy }}</b></p></div>
{% endfor %}
{% endblock %}

Explanation:

Flask Mega 18
By extending base.html , you eliminate redundancy. Now, any changes to
the layout can be made in one place (the base template), and all derived
templates will inherit those changes.

Summary
By following these steps, you built a structured and scalable Flask application.
You separated the application logic from the presentation using templates,
making it easier to manage your code as the application grows. Templates
allow for dynamic content rendering, conditional logic, and iteration, enabling
you to create a flexible user interface. Template inheritance further enhances
this by reducing code duplication across your HTML files.

Topic 2 more on template inheritance


Let’s break down the navigation bar part of your Flask application and how it
fits into the concept of template inheritance. This will help clarify its purpose
and how you can implement it effectively.

What is a Navigation Bar?


A navigation bar (or navbar) is a common feature in web applications. It
typically contains links to important sections of the site, such as:

Home

Profile

About

Contact

Login/Logout

The navigation bar allows users to easily access different parts of your
application.

Why Use Template Inheritance for the Navigation Bar?


In a web application, you often want to have the same layout (including the
navigation bar) on multiple pages. Instead of rewriting the HTML for the
navigation bar in every single template, you can define it once in a base
template. Other templates will then inherit from this base template.

Flask Mega 19
Step 1: Create the Base Template
You created a base.html file that contains the common structure for all pages,
including the navigation bar. Here’s how you defined it:

<!doctype html>
<html>
<head>
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog!</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>

Explanation:

Title Logic: The title of the page changes based on what you pass to it
from the view function.

Navigation Bar: The line <div>Microblog: <a href="/index">Home</a></div>


represents a simple navigation bar. You can add more links here as
needed.

Content Block: The {% block content %}{% endblock %} is a placeholder where


the specific content for each page will go. This allows derived templates
(like index.html ) to inject their unique content while keeping the overall
structure intact.

Step 2: Extend the Base Template in Your Other Templates


Now, in your index.html (or any other template you create), you extend
base.html :

Flask Mega 20
{% extends "base.html" %}

{% block content %}
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.bo
dy }}</b></p></div>
{% endfor %}
{% endblock %}

Explanation:

Extending Base Template: The line {% extends "base.html" %} tells Flask that
this template is based on base.html . It will use the structure defined in
base.html .

Inserting Unique Content: The {% block content %} section is where you put
the unique content for the index.html page. This content is rendered in
place of the {% block content %}{% endblock %} from the base template.

Example of Adding More Links to the Navigation Bar


You can easily enhance the navigation bar by adding more links. Here’s an
example:

<div>
Microblog:
<a href="/index">Home</a> |
<a href="/about">About</a> |
<a href="/profile">Profile</a> |
<a href="/logout">Logout</a>
</div>

Final Look of the Base Template


Your base.html might look like this after adding more links:

Flask Mega 21
<!doctype html>
<html>
<head>
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog!</title>
{% endif %}
</head>
<body>
<div>
Microblog:
<a href="/index">Home</a> |
<a href="/about">About</a> |
<a href="/profile">Profile</a> |
<a href="/logout">Logout</a>
</div>
<hr>
{% block content %}{% endblock %}
</body>
</html>

Summary
Navigation Bar Purpose: Provides easy access to different sections of
your application.

Template Inheritance: Allows you to define the navigation bar once in the
template and reuse it across different pages, maintaining a
base.html

consistent look and feel.

Customization: You can easily add, remove, or modify links in the


navigation bar by editing the base.html file.

This way, any time you create a new template that extends base.html , it will
automatically include the navigation bar, ensuring a cohesive user experience
throughout your application.

Flask Mega 22
If you have any more questions or need further clarification, feel free to ask!

Topic 3 (user Login Forms, Flask-WTF)

Step 1: Understanding Flask-WTF


Flask-WTF is an extension for Flask that simplifies the handling of web forms.
It provides features like:

Form Validation: Ensures that the data submitted by users meets certain
criteria (e.g., required fields, valid email format).

CSRF Protection: Helps protect against Cross-Site Request Forgery


attacks.

Convenient Form Rendering: Easily create and render forms using Python
classes.

Step 2: Installing Flask-WTF


You installed Flask-WTF using pip, which is the package manager for Python.
Here’s the command you ran:

(venv) C:\Users\tayam\OneDrive\Documents\Projects\Microblo
g\microblog>pip install flask-wtf

Explanation:

(venv)indicates that you’re working within a virtual environment. This is a


good practice, as it keeps your project dependencies isolated from other
projects on your system.

tells pip to download and install the Flask-WTF


pip install flask-wtf

package from the Python Package Index (PyPI).

Flask configuration

User Login Form


The Flask-WTF extension uses Python classes to represent web forms. A form
class simply defines the fields of the form as class variables.

Flask Mega 23
Step 2: Create the forms.py Module
1. Navigate to the app directory of your project.

2. Create a new file named forms.py .


Using Command Prompt:

bash
Copy code
cd C:\Users\tayam\OneDrive\Documents\Projects\Microblog
\app
echo. > forms.py

Step 3: Define the LoginForm Class


Open forms.py in your text editor and add the following code:

python
Copy code
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanFie
ld, SubmitField
from wtforms.validators import DataRequired

class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataReq
uired()])
password = PasswordField('Password', validators=[DataR
equired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')

Explanation of the Code:


Imports:

Flask Mega 24
FlaskForm is imported from flask_wtf , which allows you to create forms
in Flask.

Field types ( StringField , PasswordField , BooleanField , SubmitField ) are


imported from wtforms .

DataRequired is a validator that ensures the field is not left empty.

LoginForm Class:

Fields:

username : A text field for entering the username.

password : A password field for entering the password.

remember_me : A checkbox for the "Remember Me" option.

submit : A button for submitting the form.

Validators: The DataRequired validator ensures that the username and


password fields are filled out before submission.

Step 4: Add the HTML Template Code


1. Open login.html in your text editor (like Visual Studio Code). (create this in
the templates folder)

2. Copy and paste the following code into login.html :

{% extends "base.html" %}

{% block content %}
<h1>Sign In</h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}
</p>
<p>

Flask Mega 25
{{ form.password.label }}<br>
{{ form.password(size=32) }}
</p>
<p>{{ form.remember_me() }} {{ form.remember_m
e.label }}</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}

Explanation of the Code


Template Inheritance: The {% extends "base.html" %}line allows you to
inherit the layout defined in base.html , maintaining a consistent look across

your application.

Form Rendering: The form uses Flask-WTF to automatically generate the


HTML for the fields:

{{ form.hidden_tag() }} adds a hidden CSRF token field for security.

{{ form.username.label }} and {{ form.username(size=32) }} render the label


and input field for the username.

Similarly, for the password and the "Remember Me" checkbox.

Form Submission: The action attribute is set to an empty string, meaning


the form will submit to the same URL it was rendered from. The
method="post" indicates that the form will send data via a POST request,

which is more secure for sensitive information like passwords.

No Browser Validation: The novalidate attribute prevents the browser from


validating the form fields, allowing Flask to handle validation.

1. Creating the Login View Function


The main goal of the login view function is to handle requests to the /login

URL and render the login form for users to interact with.

Flask Mega 26
Code Explanation:

from flask import render_template


from app import app
from app.forms import LoginForm

@app.route('/login')
def login():
form = LoginForm() # Create an instance of the LoginF
orm
return render_template('login.html', title='Sign In',
form=form) # Render the login template with the form

Imports:

render_template : This function is used to render an HTML template and


pass data to it.

app : Your Flask application instance.

LoginForm : This is your custom form class that defines the structure of
the login form.

Route Declaration:

@app.route('/login') : This decorator tells Flask to trigger the login

function whenever a user navigates to /login in the browser.

Function Logic:

form = LoginForm() : This line creates an instance of the LoginForm class,


which contains all the fields needed for the login form (username,
password, remember me checkbox, and submit button).

: This line renders the


return render_template(...) login.html template and
passes two variables to it:

title : This variable is set to "Sign In" to be used as the page title.

form : This variable contains the LoginForm instance so that it can be


displayed in the template.

Flask Mega 27
2. Adding Login Link to the Navigation Bar
To make the login form accessible, you need to add a link to the login page in
your base template's navigation bar.
Code Explanation:

<div>
Microblog:
<a href="/index">Home</a>
<a href="/login">Login</a>
</div>

HTML Structure:

This snippet is part of your base.html template.

The <div> element contains links to different parts of your application.

<a href="/index">Home</a> : This is a link to the home page of your


application.

<a href="/login">Login</a> : This link directs users to the login page you
just created.

3. Running the Application


After adding the new route and updating the navigation bar, you can run your
Flask application to see the changes.

Accessing the Login Form:

Open your web browser and navigate to http://localhost:5000/ .

Click on the "Login" link in the navigation bar. This should take you to
the /login URL, where you'll see the rendered login form.

Receiving Form Data


If you try to press the submit button the browser is going to display a
"Method Not Allowed" error. This is because the login view function from
the previous section does one half of the job so far. It can display the form

Flask Mega 28
on a web page, but it has no logic to process data submitted by the user
yet. This is another area where Flask-WTF makes the job really easy. Here
is an updated version of the view function that accepts and validates the
data submitted by the user:
app/routes.py: Receiving login credentials

from flask import render_template, flash, redirect

@app.route('/login', methods=['GET', 'POST'])


def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for user {}, remember_me
={}'.format(
form.username.data, form.remember_me.data))
return redirect('/index')
return render_template('login.html', title='Sign I
n', form=form)

Let’s break down this section about receiving form data in your Flask
application and understand each part clearly.

Overview of the Updated Login View Function


1. Allowing POST Requests:

The line @app.route('/login', methods=['GET', 'POST']) tells Flask that this


view function can handle both GET and POST requests.

GET requests are typically for retrieving data (like displaying a form),
while POST requests are used for sending data to the server (like
submitting a form).

2. Form Instantiation:

form = LoginForm()

Flask Mega 29
This creates an instance of the LoginForm class that you defined earlier.
This instance will be used to both display the form and to process any
data submitted.

3. Validating Submitted Data:

if form.validate_on_submit():

The method validate_on_submit() does two things:

It checks if the request method is POST (indicating that the form


was submitted).

It validates the form fields based on the rules you set (e.g.,
DataRequired checks that fields are not empty).

If the validation is successful, it returns True , and the code inside the if
statement will execute.

4. Processing Valid Data:

flash('Login requested for user {}, remember_me={}'.for


mat(form.username.data, form.remember_me.data))
return redirect('/index')

The flash() function stores a message in the session, which can be


displayed to the user on the next page they visit. Here, it shows the
username and whether the "remember me" option was checked.

The redirect('/index') function tells the application to navigate to the


/index page after successfully processing the form.

5. Rendering the Template:

return render_template('login.html', title='Sign In', f


orm=form)

If the form validation fails (e.g., if required fields are empty), it returns
the login form again, allowing the user to correct their input.

Flask Mega 30
Updating the Base Template
To show flashed messages to the user, you updated the base.html template.
Here’s how it works:

1. Displaying Flashed Messages:

{% with messages = get_flashed_messages() %}


{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}

The get_flashed_messages() function retrieves all the messages that have


been flashed.

If there are any messages, it creates an unordered list ( <ul> ) where


each message is displayed as a list item ( <li> ).

The use of with here creates a temporary variable messages to hold the
results within that block.

Final Testing
Testing the Form:

After implementing these changes, you should run your application


and test the login form by submitting it with empty fields. You should
see the validation errors due to the DataRequired validators. When valid
data is entered, you should see a success message on the next page.

Topic 3 (Flask configuration)


configuring your Flask application using a separate configuration class. This
approach is beneficial because it keeps your configuration organized and
allows for easier modifications later. Let’s break down what you’ve learned and
how to implement it step by step.

Flask Mega 31
Why Use Configuration?
1. Separation of Concerns: Keeping configuration separate from application
logic improves readability and maintainability.

2. Environment Flexibility: You can easily change configuration settings for


different environments (development, testing, production) without
modifying the core application code.

Let's break down the configuration process for your Flask application step by
step, based on what you've provided. This guide assumes you're creating a
separate configuration file and properly integrating it into your Flask app.

Step-by-Step Guide to Setting Up Configuration in Flask


1. Create the config.py File:

Navigate to the app directory of your Flask project (where your


__init__.py and routes.py are located).

You can create the config.py file manually using a text editor or by
using the terminal.

Using Command Prompt:

cd C:\\Users\\tayam\\OneDrive\\Documents\\Projects\\Mic
roblog\\app
echo. > config.py

This command creates an empty config.py file in the app directory.

2. Edit the config.py File:


Open
config.py in your text editor and add the following code:

import os

class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-w
ill-never-guess'

Flask Mega 32
This code defines a Config class that sets up a secret key for your Flask
application. It first checks if there’s an environment variable named
SECRET_KEY ; if not, it defaults to a hardcoded string.

3. Modify __init__.py to Load Configuration:


Now, you'll want to tell your Flask application to use the configuration
class you just created. Open
__init__.py in the app directory and modify it to look like this:

from flask import Flask


from config import Config

app = Flask(__name__)
app.config.from_object(Config)

from app import routes

Here’s what each part does:

from config import Config : Imports the Config class from your config.py

file.

: Loads the configuration from the


app.config.from_object(Config) Config

class, making it available in app.config .

4. Verify the Configuration:


To check that the configuration is working correctly, you can open a
Python shell in your project directory and run the following commands:

from microblog import app


print(app.config['SECRET_KEY'])

If everything is set up correctly, it should output 'you-will-never-guess' (or


whatever value you set).

Why Use Configuration Files?


Separation of Concerns: Keeping your configuration in a separate file
allows you to manage settings independently from your application logic.

Flask Mega 33
Environment Variables: This practice makes it easier to manage sensitive
information like secret keys, especially when deploying to production
environments.

Flexibility: You can easily switch configurations for development, testing,


and production by creating different configuration classes or files.

Summary of Your Project Structure


After following these steps, your project structure should look like this:

Microblog/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── config.py # Your configuration file
│ └── templates/
│ └── index.html
├── venv/
└── microblog.py

With this setup, you can now manage your Flask application's configuration
more effectively! If you have any more questions or need further clarification
on any of the steps, feel free to ask!

1. Add More Configuration Variables: As your application grows, you can


add more configuration options in the Config class, like database settings,
debug mode, etc.

2. The SECRET_KEY configuration variable that I added as the only configuration


item is an important part in most Flask applications. Flask and some of its
extensions use the value of the secret key as a cryptographic key, useful
to generate signatures or tokens. The Flask-WTF extension uses it to
protect web forms against a nasty attack called Cross-Site Request
Forgery or CSRF (pronounced "seasurf"). As its name implies, the secret
key is supposed to be secret, as the strength of the tokens and signatures
generated with it depends on no person outside the trusted maintainers of
the application knowing it.

Flask Mega 34
Flask Mega 35

You might also like