From 8b4307b05ae78a28732c1a7984eccdbcd5296188 Mon Sep 17 00:00:00 2001 From: sjain1909 Date: Sat, 20 Jul 2024 23:12:16 +0530 Subject: [PATCH] Adding Flask Tutorial ## Fixing Issue #3627 ## Description This pull request adds a comprehensive Flask tutorial to the documentation. The tutorial covers the basics of setting up a Flask application, routing, templates, and integrating with a database. It also includes examples and step-by-step instructions to help beginners understand and build their own Flask applications. ## Type of PR - [ ] Bug fix - [x] Feature enhancement - [ ] Documentation update - [ ] Security enhancement - [ ] Other (specify): _______________ ## Checklist - [x] I have performed a self-review of my code. - [x] I have read and followed the Contribution Guidelines. - [x] I have tested the changes thoroughly before submitting this pull request. - [x] I have provided relevant issue numbers, screenshots, and videos after making the changes. - [x] I have commented my code, particularly in hard-to-understand areas. - [x] I have followed the code style guidelines of this project. - [x] I have checked for any existing open issues that my pull request may address. - [x] I have ensured that my changes do not break any existing functionality. - [x] Each contributor is allowed to create a maximum of 4 issues per day. This helps us manage and address issues efficiently. - [x] I have read the resources for guidance listed below. - [x] I have followed security best practices in my code changes. ## Additional Context This Flask tutorial includes: - Setting up a Flask application environment. - Creating and handling routes. - Using templates for dynamic content rendering. - Integrating with a database using SQLAlchemy. - Step-by-step instructions and examples for beginners. ## Resources for Guidance Please read the following resources before submitting your contribution: - [x] [Code Harbor Hub Community Features](https://www.codeharborhub.live/community/features) - [x] [Markdown Guide](https://www.markdownguide.org/) --- docs/Flask/01-Introduction.md | 23 ++++++ docs/Flask/02-Installing.md | 29 ++++++++ docs/Flask/03-SettingUp-newProject.md | 43 +++++++++++ docs/Flask/04-Routing.md | 50 +++++++++++++ docs/Flask/05-Templates.md | 50 +++++++++++++ docs/Flask/06-HandlingForms.md | 76 +++++++++++++++++++ docs/Flask/07-Database.md | 70 +++++++++++++++++ docs/Flask/08-Blueprints.md | 52 +++++++++++++ docs/Flask/09-Error-and-Debugging.md | 66 +++++++++++++++++ docs/Flask/10.Deployment.md | 103 ++++++++++++++++++++++++++ docs/Flask/_category_.json | 8 ++ 11 files changed, 570 insertions(+) create mode 100644 docs/Flask/01-Introduction.md create mode 100644 docs/Flask/02-Installing.md create mode 100644 docs/Flask/03-SettingUp-newProject.md create mode 100644 docs/Flask/04-Routing.md create mode 100644 docs/Flask/05-Templates.md create mode 100644 docs/Flask/06-HandlingForms.md create mode 100644 docs/Flask/07-Database.md create mode 100644 docs/Flask/08-Blueprints.md create mode 100644 docs/Flask/09-Error-and-Debugging.md create mode 100644 docs/Flask/10.Deployment.md create mode 100644 docs/Flask/_category_.json diff --git a/docs/Flask/01-Introduction.md b/docs/Flask/01-Introduction.md new file mode 100644 index 000000000..94558b420 --- /dev/null +++ b/docs/Flask/01-Introduction.md @@ -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. \ No newline at end of file diff --git a/docs/Flask/02-Installing.md b/docs/Flask/02-Installing.md new file mode 100644 index 000000000..90e6de48a --- /dev/null +++ b/docs/Flask/02-Installing.md @@ -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. \ No newline at end of file diff --git a/docs/Flask/03-SettingUp-newProject.md b/docs/Flask/03-SettingUp-newProject.md new file mode 100644 index 000000000..80884bad8 --- /dev/null +++ b/docs/Flask/03-SettingUp-newProject.md @@ -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. \ No newline at end of file diff --git a/docs/Flask/04-Routing.md b/docs/Flask/04-Routing.md new file mode 100644 index 000000000..e453bb628 --- /dev/null +++ b/docs/Flask/04-Routing.md @@ -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. + diff --git a/docs/Flask/05-Templates.md b/docs/Flask/05-Templates.md new file mode 100644 index 000000000..f18b37971 --- /dev/null +++ b/docs/Flask/05-Templates.md @@ -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 + + + + + Flask App + + +

{{ title }}

+

{{ message }}

+ + +``` + +### 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. + diff --git a/docs/Flask/06-HandlingForms.md b/docs/Flask/06-HandlingForms.md new file mode 100644 index 000000000..fc14f036b --- /dev/null +++ b/docs/Flask/06-HandlingForms.md @@ -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/') +def success(name): + return f"Hello, {name}!" + +if __name__ == '__main__': + app.run(debug=True) +``` + +3. **Create `templates/index.html`:** +```html + + + + + Flask Form + + +
+ {{ form.hidden_tag() }} + {{ form.name.label }} {{ form.name }} + {{ form.submit }} +
+ + +``` + +### 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. \ No newline at end of file diff --git a/docs/Flask/07-Database.md b/docs/Flask/07-Database.md new file mode 100644 index 000000000..7b651f5b3 --- /dev/null +++ b/docs/Flask/07-Database.md @@ -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. \ No newline at end of file diff --git a/docs/Flask/08-Blueprints.md b/docs/Flask/08-Blueprints.md new file mode 100644 index 000000000..a62a1f467 --- /dev/null +++ b/docs/Flask/08-Blueprints.md @@ -0,0 +1,52 @@ +--- +id: flask-blueprints-and-application-structure +title: Flask Blueprints and Application Structure +sidebar_label: Flask Blueprints and Application Structure +sidebar_position: 8 +tags: [flask, python, blueprints, application structure] +description: In this tutorial, you will learn about Flask Blueprints and how to structure your application. +--- + +Flask Blueprints allow you to organize your application into smaller, reusable components. This is especially useful for larger applications. + +### Setting Up Blueprints + +1. **Create a Blueprint:** + +```python +# myapp/blueprints/main.py +from flask import Blueprint, render_template + +main = Blueprint('main', __name__) + +@main.route('/') +def home(): + return render_template('index.html') +``` + +2. **Register the Blueprint:** + +```python +from flask import Flask +from blueprints.main import main + +app = Flask(__name__) +app.register_blueprint(main) + +if __name__ == '__main__': + app.run(debug=True) +``` + +### Project Structure + +myapp/ +├── app.py +├── blueprints/ +│ └── main.py +├── templates/ +│ └── index.html +└── static/ + +### Conclusion + +Using Flask Blueprints helps in organizing your application into modular components, making the application structure more manageable and reusable. diff --git a/docs/Flask/09-Error-and-Debugging.md b/docs/Flask/09-Error-and-Debugging.md new file mode 100644 index 000000000..aab24ffcf --- /dev/null +++ b/docs/Flask/09-Error-and-Debugging.md @@ -0,0 +1,66 @@ +--- +id: error-handling-and-debugging +title: Error Handling and Debugging +sidebar_label: Error Handling and Debugging +sidebar_position: 9 +tags: [flask, python, error handling, debugging] +description: In this tutorial, you will learn about error handling and debugging in Flask. +--- + +Handling errors gracefully and debugging effectively are crucial for developing robust Flask applications. + +### Handling Errors +1. **Custom Error Pages:** + +```python +from flask import Flask, render_template + +app = Flask(__name__) + +@app.errorhandler(404) +def page_not_found(e): + return render_template('404.html'), 404 + +if __name__ == '__main__': + app.run(debug=True) +``` + +2. **Creating `404.html`:** + +```html + + + + + Page Not Found + + +

404 - Page Not Found

+

The page you are looking for does not exist.

+ + +``` + +### Debugging +1. **Using the Debugger:** +Set debug=True in your app.run() to enable the debugger: + +```python +if __name__ == '__main__': + app.run(debug=True) +``` + +2. **Logging Errors:** +```python +import logging +from logging.handlers import RotatingFileHandler + +if not app.debug: + handler = RotatingFileHandler('error.log', maxBytes=10000, backupCount=1) + handler.setLevel(logging.ERROR) + app.logger.addHandler(handler) +``` + +### 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. \ No newline at end of file diff --git a/docs/Flask/10.Deployment.md b/docs/Flask/10.Deployment.md new file mode 100644 index 000000000..67ddbd749 --- /dev/null +++ b/docs/Flask/10.Deployment.md @@ -0,0 +1,103 @@ +--- +id: deployment-options-and-best-practices +title: Deployment Options and Best Practices +sidebar_label: Deployment Options and Best Practices +sidebar_position: 10 +tags: [flask, python, deployment, best practices] +description: In this tutorial, you will learn about deployment options and best practices for Flask applications. +--- + +Deploying Flask applications to production requires careful planning and following best practices to ensure reliability and scalability. + + +### Deployment Options +1. **Using WSGI Servers:** + +- **Gunicorn:** +Gunicorn is a Python WSGI HTTP Server for UNIX. It's a pre-fork worker model, which means it forks multiple worker processes to handle requests. +```sh +pip install gunicorn +gunicorn -w 4 app:app +``` + +- **uWSGI:** +uWSGI is a versatile WSGI server with lots of features. It is capable of serving Python web applications through the WSGI interface. +```sh +pip install uwsgi +uwsgi --http :5000 --wsgi-file app.py --callable app +``` + +2. **Platform as a Service (PaaS):** + +- **Heroku:** +Heroku is a cloud platform that lets companies build, deliver, monitor, and scale apps. It's the fastest way to go from idea to URL, bypassing all those infrastructure headaches. +```sh +heroku create +git push heroku main +heroku open +``` + +3. **Containerization:** + +- **Docker:** +Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all parts it needs, such as libraries and other dependencies, and ship it all out as one package. + +```dockerfile +FROM python:3.8-slim +WORKDIR /app +COPY . /app +RUN pip install -r requirements.txt +CMD ["gunicorn", "-w", "4", "app:app"] +``` + +### Best Practices +1. **Use Environment Variables:** +Store configuration and secrets in environment variables rather than hardcoding them in your code. + +```python +import os +SECRET_KEY = os.getenv('SECRET_KEY', 'default_secret_key') +``` + +2. **Enable Logging:** +Proper logging is essential for monitoring and troubleshooting your application. + +```python +import logging +from logging.handlers import RotatingFileHandler + +if not app.debug: + handler = RotatingFileHandler('error.log', maxBytes=10000, backupCount=1) + handler.setLevel(logging.ERROR) + app.logger.addHandler(handler) +``` + +3. **Use a Reverse Proxy:** +Use a reverse proxy server (e.g., Nginx) in front of your Flask application to handle client requests and serve static files efficiently. + +``` +server { + listen 80; + server_name example.com; + + location / { + proxy_pass http://127.0.0.1:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` +4. **Automate Deployments:** +Use CI/CD pipelines to automate the deployment process, ensuring consistency and reducing the potential for human error. + +5. **Security Considerations:** + +- Always use HTTPS to encrypt data between the client and server. +- Regularly update your dependencies to patch security vulnerabilities. +- Implement proper input validation and sanitization to prevent common attacks like SQL injection and XSS. + +### Conclusion + +Deploying Flask applications requires careful consideration of various deployment options and best practices. By using WSGI servers, PaaS platforms, or containerization, and following best practices such as using environment variables, enabling logging, using a reverse proxy, automating deployments, and prioritizing security, you can ensure your Flask application is robust, scalable, and secure. \ No newline at end of file diff --git a/docs/Flask/_category_.json b/docs/Flask/_category_.json new file mode 100644 index 000000000..da6dd51c5 --- /dev/null +++ b/docs/Flask/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Flask", + "position": 29, + "link": { + "type": "generated-index", + "description": " In this tutorial, you'll learn about Flask, a lightweight and flexible web application framework in Python, and understand its core concepts and features." + } +} \ No newline at end of file