This readme will guide you through setting up a basic Flask application with user authentication. We'll cover important concepts about Flask, templates, and SQL.
-
Install MySQL:
brew install mysql brew services start mysql mysql_secure_installation
-
Create a virtual environment and activate it:
python -m venv venv source venv/bin/activate
-
Install required packages:
pip install -r requirements.txt
-
Log in to MySQL:
mysql -u root -p
-
Create the database and user:
CREATE DATABASE flask_app_db; USE flask_app_db; CREATE USER 'flask_user'@'localhost' IDENTIFIED BY '1234'; GRANT ALL PRIVILEGES ON flask_app_db.* TO 'flask_user'@'localhost'; FLUSH PRIVILEGES;
Our Flask app consists of several files:
main.py
: The core of our Flask application- Templates:
base.html
: The base template that other templates extendhome.html
: The home pagelogin.html
: The login pageregister.html
: The registration pagedashboard.html
: The user dashboard
- Flask: A micro web framework for Python
- Jinja2 Templates: Flask's templating engine for dynamic HTML
- SQLAlchemy: An ORM (Object-Relational Mapping) for database operations
- Flask-SQLAlchemy: Flask extension for easy SQLAlchemy integration
- Werkzeug: Provides security features like password hashing
This file sets up the Flask application, defines routes, and handles user authentication:
- We use
Flask-SQLAlchemy
to interact with our MySQL database - The
User
model defines our database schema - Routes are defined for home, register, login, dashboard, and logout
- We use
werkzeug.security
for password hashing
base.html
: Contains the basic structure of our HTML, including navigationhome.html
,login.html
,register.html
: Extendbase.html
and provide specific contentdashboard.html
: Shows user-specific information and allows attribute updates
- Routing:
@app.route()
decorator maps URLs to functions - Request Handling:
request.method
andrequest.form
for form data - Sessions:
session
object for maintaining user state - Flash Messages:
flash()
for user feedback - Redirects:
redirect()
andurl_for()
for navigation
- Ensure your virtual environment is activated
- Run the Flask application:
python flask_app.py
- Open a web browser and navigate to
http://localhost:5000