Flaskmega Python
Flaskmega Python
Status In progress
Microblog/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── config.py # <-- Now in the correct place
│ └── templates/
│ └── index.html
├── venv/
└── microblog.py
#current structure
C:\Users\tayam\OneDrive\Documents\Projects\Microblog
Flask Mega 1
mkdir C:\Users\tayam\OneDrive\Documents\Projects\Microblog
cd C:\Users\tayam\OneDrive\Documents\Projects\Microblog
This creates a venv/ folder inside your Microblog directory, which contains
a separate installation of Python and pip.
venv\Scripts\activate
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:
Flask Mega 2
Flask was downloaded and installed inside the venv/ folder.
mkdir app
5. Writing app/__init__.py
In app/__init__.py , you initialized your Flask app.
app = Flask(__name__)
Explanation:
1. app = Flask(__name__)
The __name__ variable tells Flask the name of the current Python module.
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:
@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.
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 .
Command:
bash
Copy code
set FLASK_APP=microblog.py
On Windows, the set command temporarily sets the variable for your current
terminal session.
bash
Copy code
echo %FLASK_APP%
Command:
Flask Mega 5
bash
Copy code
flask run
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/
Flask listens for requests on port 5000. When you visit the URL in a
browser, it runs the index() function and displays "Hello, World!".
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
3. Installed Flask:
pip install flask
4. Created the app/ package and wrote the initial Flask setup in __init__.py .
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!
bash
Copy code
python -m venv venv
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!
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.
Flask Mega 9
python
Copy code
from flask import Flask
from app import routes # Tells the app where the pages ar
e
python
Copy code
from app import app
@app.route('/')
@app.route('/index')
def index():
return "Hello, World!"
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.
When someone visits / or /index , the page will display the message
"Hello, World!"
python
Copy code
from app import app
It grabs the app you made in __init__.py so you can run it.
bash
Copy code
set FLASK_APP=microblog.py
This command tells Flask to look for the app inside the microblog.py file.
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/.
mathematica
Copy code
CTRL + C
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
python
Copy code
user = {'username': 'Miguel'}
Explanation:
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.
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.
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:
html
Copy code
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog!</title>
{% endif %}
Explanation:
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:
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.
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
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.
Home
Profile
About
Contact
Login/Logout
The navigation bar allows users to easily access different parts of your
application.
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.
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.
<div>
Microblog:
<a href="/index">Home</a> |
<a href="/about">About</a> |
<a href="/profile">Profile</a> |
<a href="/logout">Logout</a>
</div>
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
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!
Form Validation: Ensures that the data submitted by users meets certain
criteria (e.g., required fields, valid email format).
Convenient Form Rendering: Easily create and render forms using Python
classes.
(venv) C:\Users\tayam\OneDrive\Documents\Projects\Microblo
g\microblog>pip install flask-wtf
Explanation:
Flask configuration
Flask Mega 23
Step 2: Create the forms.py Module
1. Navigate to the app directory of your project.
bash
Copy code
cd C:\Users\tayam\OneDrive\Documents\Projects\Microblog
\app
echo. > forms.py
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')
Flask Mega 24
FlaskForm is imported from flask_wtf , which allows you to create forms
in Flask.
LoginForm Class:
Fields:
{% 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 %}
your application.
URL and render the login form for users to interact with.
Flask Mega 26
Code Explanation:
@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:
LoginForm : This is your custom form class that defines the structure of
the login form.
Route Declaration:
Function Logic:
title : This variable is set to "Sign In" to be used as the page title.
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:
<a href="/login">Login</a> : This link directs users to the login page you
just created.
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.
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
Let’s break down this section about receiving form data in your Flask
application and understand each part clearly.
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.
if form.validate_on_submit():
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.
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:
The use of with here creates a temporary variable messages to hold the
results within that block.
Final Testing
Testing the Form:
Flask Mega 31
Why Use Configuration?
1. Separation of Concerns: Keeping configuration separate from application
logic improves readability and maintainability.
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.
You can create the config.py file manually using a text editor or by
using the terminal.
cd C:\\Users\\tayam\\OneDrive\\Documents\\Projects\\Mic
roblog\\app
echo. > config.py
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.
app = Flask(__name__)
app.config.from_object(Config)
from config import Config : Imports the Config class from your config.py
file.
Flask Mega 33
Environment Variables: This practice makes it easier to manage sensitive
information like secret keys, especially when deploying to production
environments.
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!
Flask Mega 34
Flask Mega 35