1
Current Location:
>
Web Development
Introduction to Python Web Development: Start Your First Website with Flask
2024-11-26 10:48:11   read:14

Origin

I still remember my first encounter with web development. It was during college when I saw a classmate build a forum website using Django, and I was filled with admiration. At that time, I only knew how to write simple data processing scripts in Python and was clueless about web development. After years of learning and practice, I deeply appreciate Python's power in web development. Today, let's start exploring the mysteries of Python web development, beginning with the basic Flask framework.

Framework Selection

Why start with Flask? This brings us to Python's two mainstream web frameworks. Django is a comprehensive framework offering complete web development solutions. However, for beginners, Django has a steeper learning curve and relatively complex configuration. In contrast, Flask is a lightweight micro-framework with a simple core and flexible extensions. As its slogan says: "Web development, one drop at a time."

In my opinion, Flask is particularly suitable for beginners for the following reasons:

  1. Few core concepts, easy to grasp
  2. Clear code structure, easy to understand
  3. Features can be added gradually as needed
  4. Suitable for small applications and API services

Getting Started

Let's start building our first Flask application. First, we need to install Flask:

pip install flask

Next, create the simplest application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, Web Developer!'

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

Would you like me to explain this code?

Deep Dive

When you run this program, Flask starts a local server listening on port 5000 by default. Open your browser and visit http://127.0.0.1:5000/ to see the welcome message "Hello, Web Developer!"

These seemingly simple lines of code actually involve multiple core web development concepts. Let's analyze them:

  1. Routing System Flask uses decorators (@app.route) to define URL routes. For example:
@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {username}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post {post_id}'
  1. Template Rendering In actual development, we usually don't return strings directly but HTML pages. Flask uses the Jinja2 template engine:
from flask import render_template

@app.route('/hello/<name>')
def hello_template(name):
    return render_template('hello.html', name=name)

Corresponding hello.html template:

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>
  1. Handling Form Data Web applications need form handling, and Flask provides an elegant solution:
from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # Handle login logic
        return f'Welcome {username}'
    return render_template('login.html')

Practical Application

Instead of just theory, let's create a practical project. We'll create a simple todo application with the following features:

  1. Display todo list
  2. Add new todos
  3. Mark items as completed
  4. Delete todos

First, create the data model:

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    completed = db.Column(db.Boolean, default=False)

Implement the main routes and view functions:

@app.route('/')
def index():
    todos = Todo.query.all()
    return render_template('index.html', todos=todos)

@app.route('/add', methods=['POST'])
def add():
    title = request.form.get('title')
    if title:
        todo = Todo(title=title)
        db.session.add(todo)
        db.session.commit()
    return redirect(url_for('index'))

@app.route('/complete/<int:id>')
def complete(id):
    todo = Todo.query.get_or_404(id)
    todo.completed = not todo.completed
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/delete/<int:id>')
def delete(id):
    todo = Todo.query.get_or_404(id)
    db.session.delete(todo)
    db.session.commit()
    return redirect(url_for('index'))

Advanced Topics

Once you've mastered Flask basics, you can try some advanced topics:

  1. RESTful API Design Modern web applications often need to provide API interfaces. Flask can easily implement RESTful APIs:
from flask import jsonify

@app.route('/api/todos')
def get_todos():
    todos = Todo.query.all()
    return jsonify([{
        'id': todo.id,
        'title': todo.title,
        'completed': todo.completed
    } for todo in todos])
  1. User Authentication Real applications often need login functionality. Flask-Login extension provides a complete user authentication solution:
from flask_login import LoginManager, UserMixin

login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password_hash = db.Column(db.String(120))
  1. Database Migration As applications evolve, database structures may need to change. Flask-Migrate provides database migration support:
from flask_migrate import Migrate

migrate = Migrate(app, db)

Deployment

After development, the application needs to be deployed to a production environment. Here are several key points to note:

  1. Use Production-Grade Servers In production environments, we typically use WSGI servers like Gunicorn or uWSGI:
gunicorn -w 4 -b 127.0.0.1:8000 app:app
  1. Configuration Management Different environments (development, testing, production) should use different configurations:
class Config:
    SECRET_KEY = 'dev'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///todo.db'

class ProductionConfig(Config):
    SECRET_KEY = os.environ.get('SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
  1. Error Handling Error handling is particularly important in production environments:
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

Future Outlook

Web development is a constantly evolving field. With technological advancement, we see many new trends:

  1. API-First Development Modern web applications increasingly favor separated frontend and backend architecture, with the backend primarily providing API services. Flask's lightweight nature makes it particularly suitable for building API services.

  2. Asynchronous Support Python 3.7's introduction of asyncio provides better support for asynchronous programming. Flask is actively adapting to this trend:

from flask import Flask
from asyncio import sleep

app = Flask(__name__)

@app.route('/async')
async def async_request():
    await sleep(1)
    return 'Async Request Completed'
  1. Container Deployment Docker's popularity has standardized application deployment. A typical Dockerfile might look like this:
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "app:app"]

Insights

Reflecting on my web development learning journey, here are some insights to share:

  1. Start with Small Projects Don't try to build complex applications at first. Start with small projects and gradually add features to maintain learning enthusiasm.

  2. Value Fundamental Knowledge While frameworks can handle many details, the importance of fundamental knowledge like HTTP protocols and database design cannot be overlooked.

  3. Keep Practicing The best way to learn web development is through hands-on projects. I suggest applying each new concept you learn in practical projects.

  4. Focus on Security Web applications face various security threats. Always remember to validate input, prevent SQL injection, use HTTPS, and follow other security practices.

Conclusion

Python web development is a field full of opportunities and challenges. Starting from the simplest Flask application, you can gradually master more advanced features and eventually build complex web applications.

Remember, every professional web developer started with a simple "Hello, World!" The important thing is to maintain enthusiasm for learning, keep practicing, and exploring.

Which framework do you think better suits your project needs, Flask or Django? Feel free to share your thoughts and experiences in the comments.

>Related articles