Skip to content

Adding Flask Tutorial #3679

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/Flask/01-Introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
id: introduction-to-flask
title: Introduction to Flask
sidebar_label: Introduction to Flask
sidebar_position: 1
tags: [flask, python, web development]
description: In this tutorial, you will learn about Flask, a lightweight WSGI web application framework written in Python.
---

Flask is a lightweight WSGI web application framework written in Python. It is widely used for building web applications and APIs due to its simplicity and flexibility. Flask is designed to make getting started quick and easy, with the ability to scale up to complex applications. This tutorial will guide you through the basics of Flask, helping you get started with building web applications.

### Key Features of Flask

1. **Lightweight and Modular:** Flask is easy to set up and use, providing the essentials for web development while allowing you to add extensions as needed.

2. **Flexible:** Flask provides a simple interface for routing, templating, and handling requests, giving you the flexibility to customize your application.

3. **Extensible:** Flask supports a wide range of extensions for database integration, form handling, authentication, and more.


### Conclusion

Flask is a powerful and flexible framework for building web applications and APIs. Its simplicity and ease of use make it a popular choice among developers. Understanding the basics of Flask is the first step towards creating robust and scalable web applications.
29 changes: 29 additions & 0 deletions docs/Flask/02-Installing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
id: installing-flask
title: Installing Flask
sidebar_label: Installing Flask
sidebar_position: 2
tags: [flask, python, installation]
description: In this tutorial, you will learn how to install Flask, a lightweight WSGI web application framework written in Python.
---

To start using Flask, you need to install it on your system. Flask can be installed using Python's package manager, pip.

### Prerequisites
**Python:** Ensure you have Python installed on your system. You can download it from the official website.

### Installing Flask
1. **Using pip:**
Open your terminal or command prompt and run the following command:
```
pip install Flask
```
2. **Verifying Installation:**
To verify that Flask is installed correctly, you can run:
```
python -m flask --version
```

### Conclusion

Installing Flask is a straightforward process using pip. Once installed, you can start building your web applications and exploring the various features and functionalities that Flask offers.
43 changes: 43 additions & 0 deletions docs/Flask/03-SettingUp-newProject.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
id: setting-up-a-new-flask-project
title: Setting up a New Flask Project
sidebar_label: Setting up a New Flask Project
sidebar_position: 3
tags: [flask, python, project setup]
description: In this tutorial, you will learn how to set up a new Flask project.
---

Setting up a new Flask project involves creating a basic project structure and initializing the Flask application.

### Project Structure

1. **Create a Project Directory:**
mkdir my_flask_app
cd my_flask_app

2. **Create a Virtual Environment:**
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`

3. **Install Flask:**
pip install Flask

### Initializing the Flask Application

**Create `app.py`:**
```python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

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

### Conclusion

Flask is a powerful and flexible framework for building web applications and APIs. Its simplicity and ease of use make it a popular choice among developers. Understanding the basics of Flask is the first step towards creating robust and scalable web applications.
50 changes: 50 additions & 0 deletions docs/Flask/04-Routing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
id: flask-routing-and-request-handling
title: Flask Routing and Request Handling
sidebar_label: Flask Routing and Request Handling
sidebar_position: 4
tags: [flask, python, routing, request handling]
description: In this tutorial, you will learn about routing and request handling in Flask.
---

Routing in Flask is used to map URLs to functions (views). Each view function is responsible for handling requests to a specific URL.

### Defining Routes
Routes are defined using the `@app.route` decorator. Here's a simple example:
```python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

@app.route('/about')
def about():
return "About Page"

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

### Handling Requests
Flask provides support for handling different types of HTTP requests. By default, routes handle `GET` requests, but you can specify other methods like `POST`, `PUT`, `DELETE`, etc.
```python
from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
data = request.form['data']
return f"Received: {data}"

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

### Conclusion

Understanding routing and request handling in Flask is crucial for creating dynamic web applications. By defining routes and handling different types of requests, you can build responsive and interactive web applications.

50 changes: 50 additions & 0 deletions docs/Flask/05-Templates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
id: using-templates-with-jinja2
title: Using Templates with Jinja2
sidebar_label: Using Templates with Jinja2
sidebar_position: 5
tags: [flask, python, templates, jinja2]
description: In this tutorial, you will learn about using templates with Jinja2 in Flask.
---

Flask uses the Jinja2 templating engine to render HTML templates. This allows you to create dynamic web pages by embedding Python code within HTML.

### Creating a Template
1. **Create a Templates Directory:**
mkdir templates

2. **Create `index.html`:**

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask App</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</body>
</html>
```

### Rendering the Template
**Update `app.py:`**
```python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
return render_template('index.html', title="Welcome to Flask", message="This is a dynamic web page.")

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

### Conclusion

Using templates with Jinja2 in Flask allows you to create dynamic and reusable web pages. By rendering templates, you can pass data from your Flask application to the HTML templates, making your web application more interactive and efficient.

76 changes: 76 additions & 0 deletions docs/Flask/06-HandlingForms.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
id: handling-forms-and-user-input
title: Handling Forms and User Input
sidebar_label: Handling Forms and User Input
sidebar_position: 6
tags: [flask, python, forms, user input]
description: In this tutorial, you will learn how to handle forms and user input in Flask.
---

Flask is a lightweight WSGI web application framework written in Python. It is widely used for building web applications and APIs due to its simplicity and flexibility. Flask is designed to make getting started quick and easy, with the ability to scale up to complex applications. This tutorial will guide you through the basics of Flask, helping you get started with building web applications.

### Handling forms and user input is a common requirement in web applications. Flask-WTF is an extension that integrates Flask with WTForms to provide form handling and validation.

### Installing Flask-WTF
First, you need to install Flask-WTF:

pip install Flask-WTF

### Creating a Simple Form
1. **Create `forms.py`:**

```python
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
```

2. **Update `app.py`:**
```python
from flask import Flask, render_template, redirect, url_for
from forms import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
name = form.name.data
return redirect(url_for('success', name=name))
return render_template('index.html', form=form)

@app.route('/success/<name>')
def success(name):
return f"Hello, {name}!"

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

3. **Create `templates/index.html`:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Form</title>
</head>
<body>
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name }}
{{ form.submit }}
</form>
</body>
</html>
```

### Conclusion

Handling forms and user input in Flask is straightforward with Flask-WTF. This integration allows you to create forms, validate user input, and process form data efficiently.
70 changes: 70 additions & 0 deletions docs/Flask/07-Database.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
id: working-with-databases
title: Working with Databases (SQLAlchemy)
sidebar_label: Working with Databases (SQLAlchemy)
sidebar_position: 7
tags: [flask, python, databases, sqlalchemy]
description: In this tutorial, you will learn how to work with databases using SQLAlchemy in Flask.
---

Flask-SQLAlchemy is an extension that simplifies database interactions in Flask applications. It provides an ORM (Object Relational Mapper) for managing database records as Python objects.

### Installing Flask-SQLAlchemy
First, install Flask-SQLAlchemy:
```sh
pip install Flask-SQLAlchemy
```

### Setting Up the Database
1. **Update `app.py:`**

```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), nullable=False, unique=True)

def __repr__(self):
return f"User('{self.username}')"

@app.route('/')
def index():
return "Welcome to Flask-SQLAlchemy"

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

2. **Creating the Database:**
```python
>>> from app import db
>>> db.create_all()
```

### Performing CRUD Operations

1. **Adding Records:**

```python
from app import db, User
user1 = User(username='john_doe')
db.session.add(user1)
db.session.commit()
```

2. **Querying Records:**

```python
users = User.query.all()
print(users)
```

### Conclusion

Working with databases in Flask is made easy with Flask-SQLAlchemy. It provides an ORM to interact with the database using Python objects, allowing for efficient and organized database management.
Loading
Loading