{"id":27156641,"url":"https://github.com/saumyajeet-varma/learn-flask","last_synced_at":"2026-05-01T19:34:13.159Z","repository":{"id":286859617,"uuid":"962793954","full_name":"Saumyajeet-Varma/Learn-Flask","owner":"Saumyajeet-Varma","description":null,"archived":false,"fork":false,"pushed_at":"2025-04-08T17:33:38.000Z","size":3,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-08T18:34:45.205Z","etag":null,"topics":["flask","python"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Saumyajeet-Varma.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-04-08T17:23:30.000Z","updated_at":"2025-04-08T17:53:57.000Z","dependencies_parsed_at":"2025-04-08T18:45:53.221Z","dependency_job_id":null,"html_url":"https://github.com/Saumyajeet-Varma/Learn-Flask","commit_stats":null,"previous_names":["saumyajeet-varma/learn-flask"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Saumyajeet-Varma%2FLearn-Flask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Saumyajeet-Varma%2FLearn-Flask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Saumyajeet-Varma%2FLearn-Flask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Saumyajeet-Varma%2FLearn-Flask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Saumyajeet-Varma","download_url":"https://codeload.github.com/Saumyajeet-Varma/Learn-Flask/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247924006,"owners_count":21019099,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["flask","python"],"created_at":"2025-04-08T20:31:42.560Z","updated_at":"2026-05-01T19:34:13.151Z","avatar_url":"https://github.com/Saumyajeet-Varma.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Learn Flask\n\n\n\n## Table of Contents\n- [Getting Started](#getting-started)\n- [How to make a Website with Python](#01-how-to-make-a-website-with-python)\n- [HTML Templates](#02-html-templates)\n- [Template Inheritance](#03-template-inheritance)\n- [HTTP Methods](#04-http-methods)\n- [Session](#05-session)\n- [Message Flashing](#06-message-flashing)\n- [Using SQLAlchemy Database](#07-using-sqlalchemy-database)\n- [Handling Static Files](#08-handling-static-files)\n- [Blueprints and handling multiple python files](#09-blueprints-and-handling-multiple-python-files)\n\n\n\n## Getting Started\n\nFlask is a micro web framework written in Python. It's used to build web applications quickly and with minimal code.\n\n- Routing: Define URLs and what happens when someone visits them.\n- Templating: Uses Jinja2 templating engine to render HTML dynamically.\n- Built-in development server \u0026 debugger.\n- RESTful request handling.\n- Easily extendable with plugins (e.g., for databases, authentication, etc.).\n\n### Install Flask\n```bash\npip install flask\n```\n\n### Basic code snippet to create a server using flask\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n# Models and routes\n\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\nVisit [localhost:5000](http://localhost:5000) in your browser.\n\nYou need to restart the server manually for every change to display it in webpage. If you want the server to detect the change and restart itself, you can use a parameter **debug** in **run**.\n```python\napp.run(debug=True)\n```\n\n\n\n## 01) How to make a website with Python\n\nIn this section we'll learn how to create **routes** and **redirection**.\n\n### Routing\n```python\n@app.route(\"/\")\ndef home():\n    return \"\u003ch1\u003eThis is the Homepage\u003c/h1\u003e\"\n```\nYou're telling Flask:\n\u003e \"Hey Flask, when someone visits the root URL /, run the home() function and return whatever it outputs as the response.\"\n\n```python\n@app.route(\"/user/\u003cname\u003e\")  # Dynamic routing\ndef user(name):\n    return f\"Hello {name}\"\n```\n\u003e \u003cvariable_name\u003e is used in dynamic routing in Flask\n\n### Redirection\nFor redirection you need to import redirect and url_for from flask.\n```python\nfrom flask import redirect, url_for\n```\n\n```python\n@app.route(\"/test\")\ndef test():\n    return redirect(url_for(\"home\"))\n```\n\n```python\n@app.route(\"/another-test\")\ndef test():\n    return redirect(url_for(\"user\", name = \"Samm\"))  # Redirection to dynamic routes\n```\n\n\n\n## 02) HTML templates\n\nIn this section we'll learn how to render proper **HTML template**.\n\nCreate a directory in the root folder where your **main.py** is, name that directory **templates**. Inside templates create your HTML files.\n\nJinja (specifically Jinja2) is the template engine that Flask uses under the hood. \u003cbr\u003e\nJinja’s main job is to dynamically generate HTML by embedding Python-like expressions inside your HTML files.\n\nTo render HTML pages, we need **render_template**\n```python\nfrom flask import render_template\n```\n\nHow to use render_template\n```python\n@app.route(\"/\")\ndef home():\n    return render_template(\"index.html\")\n```\nYou're telling Flask:\n\u003e \"Hey Flask, when someone visits the root URL /, run the home() function, and send back the rendered HTML content from the index.html file inside the templates folder as the response.\"\n\nWe can also pass template variables\n```python\n@app.route(\"/user/\u003cname\u003e\")\ndef user(name):\n    return render_template(\"user.html\", name = name, role = \"admin\", x = 10)\n```\n\u003e We can pass any datatype as template variables.\n\nHow to use template variable in HTML\n```html\n\u003ch1\u003eHello {{name}}\u003c/h1\u003e\n\u003ch4\u003eYou are {{role}}\u003c/h4\u003e\n```\n\n```html\n{% for i in range(x) %} \n    {% if i % 2 == 0 %}\n        \u003cp\u003e{{i}}\u003c/p\u003e\n    {% endif %}\n{% endfor %}\n```\n\u003e {{ }} is used to show the value. \u003cbr\u003e {% %} is used to write python code.\n\n\n\n## 03) Template inheritance\n\nIn this section we'll learn the concept of **Template inheritance**.\n\nTemplate inheritance in Flask (via Jinja2) allows you to create a base HTML structure that other templates can extend. This promotes reusability and consistency across your web pages.\n\n### Basic Structure\n1. Create a base template\n```html\n\u003c!-- templates/base.html --\u003e\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003e{% block title %}My Website{% endblock %}\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cheader\u003e\n        \u003ch1\u003eWelcome to My Website\u003c/h1\u003e\n    \u003c/header\u003e\n    \n    \u003cmain\u003e\n        {% block content %}\n        \u003c!-- Child templates inject content here --\u003e\n        {% endblock %}\n    \u003c/main\u003e\n\n    \u003cfooter\u003e\n        \u003cp\u003e\u0026copy; 2025\u003c/p\u003e\n    \u003c/footer\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n2. Extend the base in a child template\n```html\n\u003c!-- templates/home.html --\u003e\n{% extends \"base.html\" %}\n\n{% block title %}Home Page{% endblock %}\n\n{% block content %}\n    \u003cp\u003eThis is the home page content.\u003c/p\u003e\n{% endblock %}\n```\n\n### How it works\n\u003e {% extends \"base.html\" %} tells Jinja to use the layout from base.html. \u003cbr\u003e {% block %} tags in the base file are placeholders that the child templates fill in. \u003cbr\u003e {% block block_name %}  a block name is an identifier you define inside the {% block ... %} tag. It's like a placeholder section in your base template that child templates can override or fill in.\n\n\n\n## 04) HTTP methods\n\nIn this section we'll learn about **HTTP methods** in Flask.\n\nHTTP methods determine the type of request the client sends to the server.\n\n### Common HTTP Methods\n| Method | Use Case |\n|--------|----------|\n| GET    | Retrieve data from the server |\n| POST   | Submit data to the server |\n| PUT    | Update existing data |\n| DELETE | Delete data from the server |\n| PATCH  | Partially update data |\n\nImport request from flask to access the data sent by the client.\n```python\nfrom flask import request\n```\n\n\n### Flask Example with GET and POST\n```python\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n    if request.method == 'POST':\n        name = request.form['name']\n        return f\"Hello, {name}!\"\n    return '''\n        \u003cform method=\"post\"\u003e\n            \u003cinput type=\"text\" name=\"name\" placeholder=\"Enter your name\"\u003e\n            \u003cinput type=\"submit\"\u003e\n        \u003c/form\u003e\n    '''\n```\n\u003e GET shows the form. \u003cbr\u003e POST handles the form submission and greets the user.\n\n\n\n## 05) Session\n\nIn this section we'll learn about **session** in Flask\n\nIn Flask, a session is used to store information across requests for a single user—like login status, user preferences, or shopping cart items. \u003cbr\u003e\nIt’s basically a temporary storage mechanism that persists between different pages/views for the same user.\n\n###  Setup: Set the secret key\n```python\nfrom flask import Flask, session\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key_here'  # needed to use sessions\n```\n\n### Example: Using session to store login info\n```python\nfrom flask import Flask, session, redirect, url_for, request\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key_here'\n\n@app.route('/')\ndef home():\n    if 'username' in session:\n        return f\"Welcome back, {session['username']}!\"\n    return \"You are not logged in. \u003ca href='/login'\u003eLogin\u003c/a\u003e\"\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n    if request.method == 'POST':\n        session['username'] = request.form['username']\n        return redirect(url_for('home'))\n    return '''\n        \u003cform method=\"post\"\u003e\n            \u003cinput type=\"text\" name=\"username\" placeholder=\"Enter name\"\u003e\n            \u003cinput type=\"submit\"\u003e\n        \u003c/form\u003e\n    '''\n\n@app.route('/logout')\ndef logout():\n    session.pop('username', None)\n    return redirect(url_for('home'))\n```\n\n### Useful Session Operations\n| Operation                         | Description                            |\n|----------------------------------|----------------------------------------|\n| `session['key'] = value`         | Set a session value                    |\n| `session.get('key')`             | Get a session value                    |\n| `session.pop('key', None)`       | Remove a specific key from the session |\n| `session.clear()`                | Clear the entire session               |\n\u003e session stores data in dictionary (key-value pair).\n\n### Permanent Session\nBy default, Flask sessions last only until the browser is closed (they are temporary). \u003cbr\u003e\nIf you want a session to persist even after closing the browser, you can make it permanent.\n\nYou just need to set:\n```python\nsession.permanent = True\n```\n\u003e You can also set the duration for how long the session should last. By default it is 31 days\n\n##### Example\n```python\nfrom flask import Flask, session, timedelta\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key_here'\n\n# Set session lifetime (optional)\napp.permanent_session_lifetime = timedelta(days=7)\n\n@app.route('/login')\ndef login():\n    session.permanent = True  # Mark this session as permanent\n    session['user'] = 'Alice'\n    return 'Logged in with a permanent session!'\n\n@app.route('/get')\ndef get():\n    user = session.get('user')\n    return f'Hello, {user}' if user else 'No user logged in.'\n```\n\n\n\n## 06) Message flashing\n\nIn this section we'll learn about **Message Flashing** in Flask.\n\nFlashing is a way to send a message to the next request, usually used to display status messages like:\n- ✅ “You have successfully logged in.”\n- ❌ “Invalid password.”\n- ⚠️ “Please fill all required fields.”\n\n### Example\n```python\nfrom flask import Flask, flash, redirect, render_template, request, session, url_for\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key_here'  # required for flashing\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n    if request.method == 'POST':\n        user = request.form['username']\n        if user == 'admin':\n            flash('Login successful!', 'success')\n            return redirect(url_for('home'))\n        else:\n            flash('Invalid username!', 'error')\n            return redirect(url_for('login'))\n    return render_template('login.html')\n\n@app.route('/home')\ndef home():\n    return render_template('home.html')\n```\n\u003e *flash(message)* - \tStores a message for the next view\n\n###  In Your Template (home.html, login.html, etc.):\n```python\n{% with messages = get_flashed_messages(with_categories=true) %}\n  {% if messages %}\n    \u003cul\u003e\n    {% for category, message in messages %}\n      \u003cli class=\"{{ category }}\"\u003e{{ message }}\u003c/li\u003e\n    {% endfor %}\n    \u003c/ul\u003e\n  {% endif %}\n{% endwith %}\n```\n\n\u003e *get_flashed_messages()* - Retrieves and clears flashed messages\n\n### Flash Message Categories (Optional but useful!)\n| Category   | Purpose                     | Example Usage                            |\n|------------|-----------------------------|-------------------------------------------|\n| `success`  | For positive feedback        | `flash(\"Logged in successfully!\", \"success\")` |\n| `error`    | For error messages           | `flash(\"Invalid password!\", \"error\")`        |\n| `warning`  | For caution or alerts        | `flash(\"Your session is about to expire.\", \"warning\")` |\n| `info`     | For general information      | `flash(\"New feature launched!\", \"info\")`     |\n\n##### Used like this:\n```python\nflash(\"Something went wrong!\", \"error\")\n```\n\n\n\n## 07) Using SQLAlchemy Database\n\nIn this section we'll learn how to integrate **SQLAchemy** with Flask.\n\nTo integrate **SQLAchemy**, we need to install **Flask-SQlAlchemy**\n```bash\npip install flask-sqlalchemy\n```\n\n### Basic setup\n```python\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'  # or PostgreSQL/MySQL URI\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n```\n\n### Defining a model\n```python\nclass User(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    username = db.Column(db.String(80), unique=True, nullable=False)\n    email = db.Column(db.String(120), unique=True, nullable=False)\n\n    def __init__(self, username, email):\n        self.username = username\n        self.email = email\n\n    def __repr__(self):\n        return f'\u003cUser {self.username}\u003e'\n```\n\u003e column_name = db.Column(column_datatype, ...optional_arguements) \u003cbr\u003e\n\u003e `__init__`: You can define an `__init__` method, but you don't need to if you're just assigning attributes that match the model fields. SQLAlchemy auto-generates a default constructor unless you want custom behavior. \u003cbr\u003e\n\u003e `__repr__`: Defines how the object is represented as a string (for debugging/logs).\n\n### Creating a database\n```python\nif __name__ == \"__main__\":\n    with app.app_context():\n        db.create_all()  # Creates tables based on the models\n    app.run()\n```\n\n### CRUD Example\n```python\n# CREATE\nnew_user = User(username='john', email='john@example.com')\ndb.session.add(new_user)\ndb.session.commit()\n\n# READ\nuser = User.query.filter_by(username='john').first()\n\n# UPDATE\nuser.email = 'john.doe@example.com'\ndb.session.commit()\n\n# DELETE\ndb.session.delete(user)\ndb.session.commit()\n```\n\n\n\n## 08) Handling static files\n\nIn this section we'll learn how to handle **static files** in Flask.\n\nWe create a separate folder for static files and name it \"static\":\n\n```md\nyour_project/\n│\n├── main.py\n├── static/\n│   ├── styles/\n│   │   └── style.css\n│   ├── scripts/\n│   │   └── script.js\n│   └── images/\n│       └── logo.png\n│\n├── templates/\n│   └── index.html\n```\n\nNow how to access the static files\n```html\n\u003c!-- CSS files --\u003e\n\u003clink rel=\"stylesheet\" href=\"{{ url_for('static', filename='styles/style.css') }}\"\u003e\n```\n\n```html\n\u003c!-- JavaScript files --\u003e\n\u003cscript src=\"{{ url_for('static', filename='scripts/script.js') }}\"\u003e\u003c/script\u003e\n```\n\n```html\n \u003c!-- Images --\u003e\n\u003cimg src=\"{{ url_for('static', filename='images/logo.png') }}\" alt=\"Logo\"\u003e\n```\n\n\n\n## 09) Blueprints and Handling multiple Python files\n\nIn this section we'll learn about **Blueprints** in Flask.\n\n**Flask Blueprints** are a powerful way to organize your application into modular components, especially helpful as your app grows. Think of blueprints like “mini-apps” that can be plugged into the main Flask app.\n\n### Why Use Blueprints ?\n- Cleaner, modular code\n- Separate concerns (routes, templates, static files)\n- Easy to reuse and scale\n\n### Example Folder Structure with Blueprints\n```md\nyour_project/\n│\n├── main.py\n├── static/\n├── templates/\n│\n├── admin/\n│   ├── admin.py\n│   ├── static/\n│   └── templates/\n```\n\n### Step-by-Step Guide\n\n#### 1. admin/admin.py — Define a Blueprint\n```python\nfrom flask import Blueprint, render_template\n\nadmin = Blueprint(\"admin\", __name__, static_folder=\"static\", template_folder=\"templates\")\n\n@admin.route('/')\ndef admin_page():\n    return render_template('admin_page.html')\n\n```\n\u003e Blueprint(\"blueprint_name\", `__name__`, static_folder=\"path_to_static_folder\", template_folder=\"patgh_to_template_folder\")\n\n#### 2. main.py — Register the Blueprint\n```python\nfrom flask import Flask\nfrom admin.admin import admin\n\napp = Flask(__name__)\napp.register_blueprint(admin, url_prefix=\"/admin\")\n\nif __name__ == '__main__':\n    app.run(debug=True)\n```\n\u003e register_blueprint(\"blueprint_name\", url_prefix=\"/prefix_route\") \u003cbr\u003e *url_prefix is optional*\n\n\u003e For better clarity checkout the code given in the [09 - Blueprints and Handling multiple Python files](https://github.com/Saumyajeet-Varma/Learn-Flask/tree/main/09%20-%20Blueprints%20and%20Handling%20multiple%20Python%20files)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaumyajeet-varma%2Flearn-flask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsaumyajeet-varma%2Flearn-flask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaumyajeet-varma%2Flearn-flask/lists"}