ubuntu

Ubuntu Python Web开发

小樊
56
2025-10-01 19:05:37
栏目: 编程语言

Ubuntu Python Web Development: A Step-by-Step Guide

Python is a top choice for web development on Ubuntu due to its simplicity and the availability of robust frameworks like Flask, Django, and FastAPI. Below is a structured guide to setting up your environment, choosing a framework, building a basic app, and deploying it with Nginx.

1. Prerequisites: Install Python and pip

Ubuntu typically includes Python 3 pre-installed, but you should verify and update it to the latest version. Run these commands in the terminal:

sudo apt update
sudo apt install python3 python3-pip python3-venv

Check the installation with:

python3 --version  # Should return Python 3.x.x
pip3 --version     # Should return pip x.x.x from Python 3

2. Set Up a Virtual Environment

Virtual environments isolate project dependencies to avoid conflicts. Create and activate one:

python3 -m venv myenv      # Create a virtual environment named "myenv"
source myenv/bin/activate  # Activate the environment (your terminal prompt will change)

Deactivate with deactivate when done.

3. Choose a Web Framework

Select a framework based on your project needs:

Install your chosen framework:

pip3 install Flask          # For Flask
pip3 install Django         # For Django
pip3 install fastapi uvicorn # For FastAPI (uvicorn is the ASGI server)

4. Build a Basic Application

Flask Example

Create a file named app.py and add this code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World from Flask!'

Run the app:

python3 app.py

Visit http://127.0.0.1:5000 in your browser to see the message.

Django Example

Create a project and app:

django-admin startproject myproject  # Create a Django project
cd myproject
python3 manage.py startapp myapp     # Create an app named "myapp"

Register the app in myproject/settings.py by adding myapp to the INSTALLED_APPS list. Run the development server:

python3 manage.py runserver

Visit http://127.0.0.1:8000 to see Django’s welcome page.

FastAPI Example

Create a file named main.py:

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, World from FastAPI!"}

Run the app with Uvicorn:

uvicorn main:app --reload

Visit http://127.0.0.1:8000 to see the JSON response. Use http://127.0.0.1:8000/docs to view auto-generated Swagger UI docs.

5. Deploy to Production with Nginx

For production, use Nginx as a reverse proxy to handle traffic and serve your app securely.

Install Nginx

sudo apt install nginx

Configure Nginx

Edit the default Nginx configuration file:

sudo nano /etc/nginx/sites-available/default

Replace the location / block with this (adjust for your app’s port):

location / {
    proxy_pass http://127.0.0.1:5000;  # For Flask (default port)
    # proxy_pass http://127.0.0.1:8000;  # For Django/development server
    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;
}

Save (Ctrl+O, Enter) and exit (Ctrl+X). Test the configuration:

sudo nginx -t

Restart Nginx to apply changes:

sudo systemctl restart nginx

6. Optional: Use Gunicorn for Production

For better performance, use Gunicorn (a Python WSGI server) instead of running the app directly. Install Gunicorn:

pip3 install gunicorn

Run your Flask app with Gunicorn:

gunicorn -w 3 -b 127.0.0.1:5000 app:app  # 3 workers, bind to localhost:5000

Update the Nginx proxy_pass directive to point to 127.0.0.1:5000 (as shown above).

Key Tips for Success

This guide covers the basics to get you started with Python web development on Ubuntu. From here, you can explore framework-specific features (e.g., Django’s ORM, Flask extensions) or advanced deployment techniques (e.g., Docker, Kubernetes).

0
看了该问题的人还看了