201 lines
6.3 KiB
Markdown
201 lines
6.3 KiB
Markdown
I'll help you understand the key points from this Flask tutorial transcript. Let me break down the essential steps to get started with Flask:
|
|
|
|
1. Initial Setup and Installation
|
|
- Install Flask using pip: `pip install flask`
|
|
- Create a basic directory structure:
|
|
- main Python file (e.g., `app.py`)
|
|
- `templates` folder (for HTML files)
|
|
- `static` folder (for JavaScript, CSS, etc.)
|
|
|
|
2. Basic Flask Application Structure
|
|
```python
|
|
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
|
|
|
# Initialize the Flask application
|
|
app = Flask(__name__)
|
|
|
|
# Basic route returning HTML
|
|
@app.route('/')
|
|
def home():
|
|
return render_template('index.html', name="User")
|
|
|
|
# Route with URL parameters
|
|
@app.route('/profile/<username>')
|
|
def profile(username):
|
|
return render_template('index.html', name=username)
|
|
|
|
# Route handling query parameters
|
|
@app.route('/profile')
|
|
def profile_query():
|
|
name = request.args.get('name')
|
|
return render_template('index.html', name=name)
|
|
|
|
# Route returning JSON
|
|
@app.route('/api/data')
|
|
def get_json():
|
|
return jsonify({
|
|
"name": "Tim",
|
|
"coolness": 10
|
|
})
|
|
|
|
# Route demonstrating redirect
|
|
@app.route('/go-home')
|
|
def go_to_home():
|
|
return redirect(url_for('home'))
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, port=8000)
|
|
```
|
|
|
|
|
|
3. Template Setup
|
|
Let's create a basic template structure:
|
|
```python
|
|
<!-- templates/index.html -->
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Flask App</title>
|
|
<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>
|
|
</head>
|
|
<body>
|
|
<div>
|
|
<h1>Hello, {{ name }}!</h1>
|
|
</div>
|
|
|
|
{% block content %}
|
|
<!-- Content will be inserted here by child templates -->
|
|
{% endblock %}
|
|
</body>
|
|
</html>
|
|
|
|
<!-- templates/profile.html -->
|
|
{% extends "index.html" %}
|
|
|
|
{% block content %}
|
|
<h1>This is the profile page!</h1>
|
|
{% endblock %}
|
|
```
|
|
Key Features Explained:
|
|
|
|
1. **Routes and Views**:
|
|
- Use `@app.route('/')` decorator to define URL endpoints
|
|
- Can include variable parts in URLs using `<variable_name>`
|
|
- Support for query parameters using `request.args.get()`
|
|
|
|
2. **Template Rendering**:
|
|
- Use `render_template()` to display HTML pages
|
|
- Pass variables to templates using keyword arguments
|
|
- Access variables in templates using `{{ variable_name }}`
|
|
|
|
3. **Template Inheritance**:
|
|
- Create base templates with `{% block %}` sections
|
|
- Extend base templates using `{% extends "base.html" %}`
|
|
- Override blocks in child templates
|
|
|
|
4. **Static Files**:
|
|
- Place JavaScript, CSS, and other static files in the `static` folder
|
|
- Reference them using `{{ url_for('static', filename='file.js') }}`
|
|
|
|
5. **Debug Mode**:
|
|
- Enable with `debug=True` in `app.run()`
|
|
- Provides automatic reloading and detailed error pages
|
|
|
|
---
|
|
|
|
`Flask` is an essential Python library for web development, offering a lightweight and modular micro web framework for building web applications. It provides the tools, libraries, and technologies to allow developers to build a web application. Flask supports extensions that can add application features as if they were implemented in Flask itself. Here's a concise reference guide for common use cases with `Flask`:
|
|
|
|
```markdown
|
|
# `Flask` Reference Guide
|
|
|
|
## Installation
|
|
```
|
|
pip install Flask
|
|
```
|
|
|
|
## Basic Usage
|
|
|
|
### Creating a Simple Flask Application
|
|
```python
|
|
from flask import Flask
|
|
app = Flask(__name__)
|
|
|
|
@app.route('/')
|
|
def hello_world():
|
|
return 'Hello, World!'
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True)
|
|
```
|
|
This code snippet creates a basic web application that responds with "Hello, World!" when you access the root URL.
|
|
|
|
### Running the Application
|
|
By default, the Flask application will run on `localhost` port `5000`. To run the application, execute the Python script directly, and navigate to `http://127.0.0.1:5000/` in a web browser.
|
|
|
|
## Routing
|
|
Flask allows you to map URLs to Python functions, enabling dynamic content generation based on URL parameters.
|
|
```python
|
|
@app.route('/user/<username>')
|
|
def show_user_profile(username):
|
|
# show the user profile for that user
|
|
return 'User %s' % escape(username)
|
|
```
|
|
|
|
## Templates
|
|
Flask integrates with Jinja2 templating engine, allowing for dynamic content generation in HTML.
|
|
```python
|
|
from flask import render_template
|
|
|
|
@app.route('/hello/<name>')
|
|
def hello(name=None):
|
|
return render_template('hello.html', name=name)
|
|
```
|
|
This will render an HTML template located in the `templates` folder.
|
|
|
|
## Static Files
|
|
Static files such as JavaScript, CSS, and images can be served from the `static` directory.
|
|
```html
|
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
|
```
|
|
|
|
## Request Data
|
|
Access data sent by the client using Flask's `request` object.
|
|
```python
|
|
from flask import request
|
|
|
|
@app.route('/login', methods=['POST'])
|
|
def login():
|
|
username = request.form['username']
|
|
password = request.form['password']
|
|
# Logic for login
|
|
```
|
|
|
|
## Redirects and Errors
|
|
Flask supports redirects and custom error handling.
|
|
```python
|
|
from flask import abort, redirect, url_for
|
|
|
|
@app.route('/redirect')
|
|
def redirect_example():
|
|
return redirect(url_for('hello_world'))
|
|
|
|
@app.errorhandler(404)
|
|
def page_not_found(error):
|
|
return render_template('page_not_found.html'), 404
|
|
```
|
|
|
|
## Flask Extensions
|
|
Flask can be extended with various extensions available in the Flask ecosystem for ORM, form validation, authentication, and more.
|
|
- Flask-SQLAlchemy for ORM.
|
|
- Flask-WTF for forms.
|
|
- Flask-Login for authentication.
|
|
|
|
## Deploying Flask Applications
|
|
Flask applications can be deployed in various ways, including traditional web servers like Apache or Nginx using WSGI, as well as containerized environments like Docker, or platforms like Heroku, AWS Elastic Beanstalk, and Google App Engine.
|
|
|
|
`Flask` is designed to be easy to use and extend, making it suitable for building everything from simple web services to complex web applications. With a strong focus on documentation and community, Flask has become a popular choice among Python developers for web development tasks.
|
|
|
|
|
|
Flask's simplicity and flexibility, allowing for the quick development of web applications with minimal setup, have made it particularly popular in the Python community for both beginners and experienced developers. |