杰瑞科技汇

Python如何实现Web界面交互?

Of course! Building a web interface with Python is a very common and powerful task. The "web interface" can mean several things, so I'll break down the most popular approaches with clear examples and recommendations.

Python如何实现Web界面交互?-图1
(图片来源网络,侵删)

Summary of Approaches

Approach Description Best For Key Libraries/Frameworks
Frameworks Full-stack solutions where you write Python code to handle both the backend logic and the frontend is generated from templates. Building complete, database-driven web applications from scratch. Django, Flask
API + Frontend You write a Python backend that exposes data via an API (usually JSON). A separate frontend (built with JavaScript/HTML/CSS) calls this API to display data. Modern, interactive web apps (SPAs), mobile apps, or when you have separate frontend/backend teams. FastAPI, Flask (for backend); React, Vue, Svelte (for frontend)
Web Scraping Programmatically visiting websites and extracting data from them. This is about consuming web interfaces, not creating them. Data collection, monitoring competitors, automating tasks on websites. Requests, Beautiful Soup, Selenium
GUI on the Web Creating a graphical user interface (GUI) that you run locally but access through a web browser. Sharing desktop applications with non-technical users or running headlessly on a server. PyWebIO, Dash

Frameworks (The All-in-One Approach)

This is the most traditional way to build a web app with Python. You write one application that handles everything.

A. Django: The "Batteries-Included" Framework

Django is high-level and encourages rapid development and a clean, pragmatic design. It comes with a lot of built-in features (an admin panel, ORM, authentication system) so you don't have to make as many decisions.

When to use Django:

  • You need to build a complex database-driven website quickly.
  • You want a robust, secure, and scalable application.
  • You appreciate having an admin interface for free.

Simple Django Example:

Python如何实现Web界面交互?-图2
(图片来源网络,侵删)
  1. Install Django:

    pip install django
  2. Start a project:

    django-admin startproject myproject
    cd myproject
    python manage.py startapp myapp
  3. Define a View (the logic): In myapp/views.py, add:

    from django.http import HttpResponse
    def hello(request):
        return HttpResponse("<h1>Hello, Django World!</h1>")
  4. Define a URL: In myapp/urls.py (create this file):

    Python如何实现Web界面交互?-图3
    (图片来源网络,侵删)
    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.hello, name='hello'),
    ]
  5. Include the app's URLs in the main project: In myproject/urls.py:

    from django.contrib import admin
    from django.urls import path, include
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('myapp/', include('myapp.urls')), # Add this line
    ]
  6. Run the server:

    python manage.py runserver

    Now, visit http://127.0.0.1:8000/myapp/ in your browser.

B. Flask: The "Micro" Framework

Flask is more lightweight and flexible. It gives you the core tools you need and lets you choose your own libraries for database, form validation, etc. It's great for smaller projects or APIs.

When to use Flask:

  • You are building a smaller, simpler website.
  • You want more control over your components.
  • You are primarily building an API.

Simple Flask Example:

  1. Install Flask:

    pip install Flask
  2. Create an app.py file:

    from flask import Flask
    # Create a Flask web server instance
    app = Flask(__name__)
    # Define a route and a view function
    @app.route('/')
    def hello():
        return '<h1>Hello, Flask World!</h1>'
    if __name__ == '__main__':
        # Run the app on the local development server
        app.run(debug=True)
  3. Run the server:

    python app.py

    Visit http://127.0.0.1:5000/ in your browser.


API + Frontend (The Modern Approach)

This is the most common architecture for modern web applications. Your Python code acts as a data server, and your user interface is built with JavaScript.

How it works:

  1. Python Backend (API): A Flask or FastAPI application that defines "endpoints." When the frontend requests an endpoint, the Python code runs some logic (e.g., queries a database) and returns data in a standard format like JSON.

  2. Frontend (JavaScript): A set of HTML, CSS, and JavaScript files that run in the user's browser. JavaScript code (e.g., using fetch) calls the API endpoints to get data and dynamically updates the HTML to display it.

Simple FastAPI Example (Backend):

FastAPI is perfect for this because it's designed to build APIs quickly and automatically generates interactive documentation.

  1. Install FastAPI and Uvicorn (the server):

    pip install "fastapi[all]"
  2. Create main.py:

    from fastapi import FastAPI
    from pydantic import BaseModel
    app = FastAPI()
    # A simple model for the data we'll receive
    class Item(BaseModel):
        name: str
        description: str | None = None
        price: float
        tax: float | None = None
    @app.get("/")
    def read_root():
        return {"message": "Hello, World from FastAPI!"}
    @app.post("/items/")
    def create_item(item: Item):
        # In a real app, you would save this to a database
        return {"message": f"Item '{item.name}' created successfully!", "item": item}
  3. Run the server:

    uvicorn main:app --reload

    Visit http://127.0.0.1:8000/docs to see the interactive API documentation built by FastAPI.

Simple Frontend Example (HTML/JavaScript):

Create a file named index.html in a new folder (e.g., static).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">My Web App</title>
</head>
<body>
    <h1>My Awesome App</h1>
    <div id="api-data">Loading data from API...</div>
    <script>
        // Use the fetch API to call our backend
        fetch('http://127.0.0.1:8000/')
            .then(response => response.json())
            .then(data => {
                // Update the page with the data from the API
                document.getElementById('api-data').innerText = data.message;
            })
            .catch(error => {
                document.getElementById('api-data').innerText = 'Error fetching data.';
                console.error('Error:', error);
            });
    </script>
</body>
</html>

Now, open index.html in your browser. It will call the FastAPI backend and display the message.


Web Scraping (Consuming Web Interfaces)

This is about extracting data from existing websites.

Simple Example with requests and Beautiful Soup:

Let's get the titles of the latest news from Hacker News.

  1. Install libraries:

    pip install requests beautifulsoup4
  2. Create a scraper script:

    import requests
    from bs4 import BeautifulSoup
    # The URL of the site we want to scrape
    url = 'https://news.ycombinator.com'
    try:
        # Fetch the HTML content of the page
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)
        # Parse the HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        # Find all the story links (they have a class 'titlelink')
        story_links = soup.find_all('a', class_='titlelink')
        print("Top Stories on Hacker News:")
        for i, link in enumerate(story_links):
            title = link.text
            print(f"{i+1}. {title}")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching the URL: {e}")
    except Exception as e:
        print(f"An error occurred: {e}")

GUI on the Web (PyWebIO & Dash)

分享:
扫描分享到社交APP
上一篇
下一篇