前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

使用 Python、FastHTML 和 Uvicorn 构建简单的博客网站



FastHTML 是2024 年 7 月推出的 Python Web 框架,是一个简单但功能强大的框架,允许开发人员使用纯 Python 构建 Web 应用程序。 (不需要复杂的模板引擎)。 FastHTML 轻量级且易于使用,使其成为博客网站等小型项目的绝佳选择。本文将构建一个非常简单的博客应用程序,允许用户创建和查看博客文章,使用 FastHTML 和 SQLite 作为后端,并使用 Uvicorn 在http://127.0.0.1:8000本地运行该应用程序。

项目概况

  1. 设置虚拟环境。
  2. 设置项目结构。
  3. 设置 SQLite 数据库。
  4. 定义博客文章模型和模板。
  5. 编写 FastHTML 应用程序。
  6. 使用 Uvicorn 运行应用程序。

第 1 步:设置虚拟环境

第一步是创建虚拟环境来隔离项目的依赖关系。

创建项目目录

mkdir fasthtml_blog
cd fasthtml_blog

创建虚拟环境

  • 在 macOS/Linux 上:
python3 -m venv venv
  • 在 Windows 上:
python -m venv venv

激活虚拟环境

  • 在 macOS/Linux 上:
source venv/bin/activate
  • 在 Windows 上:
venv\Scripts\activate

激活虚拟环境后,现在就可以安装必要的软件包了。

pip install python-fasthtml uvicorn

第 2 步:设置项目结构

接下来,将为博客应用程序创建目结构。需要一个app/目录来保存应用程序文件和一个 SQLite 数据库文件来存储博客文章。可以使用Python脚本自动生成所需的目录和文件。

用于创建项目结构的 Python 脚本

创建一个名为 create_directory.py 的文件并添加以下代码。

# static file | create_directory.py
import os

# Define the structure
directories = [
    'app'
]

files = [
    'app/__init__.py',
    'app/main.py',
    'app/models.py',
    'app/templates.py',
    'app/database.py'
]

# Create directories
for directory in directories:
    os.makedirs(directory, exist_ok=True)

# Create empty files
for file in files:
    with open(file, 'w') as f:
        pass

print("Directories and files created successfully.")

运行此脚本以设置项目结构。它将创建必要的目录和空文件( main.pymodels.pytemplates.py 、 database_py 和__init__.py )。

项目现在应该如下所示:

fasthtml_blog/
│
├── app/
│   ├── __init__.py
│   ├── database.py
│   ├── main.py
│   ├── models.py
│   ├── templates.py
└── venv/
└── create_directory.py

第 3 步:设置 SQLite 数据库

现在,设置 SQLite 数据库来存储博客文章。我在app/目录中创建一个database.py文件,用于管理与 SQLite 数据库的连接并创建必要的表。

app/database.py

import sqlite3
from contextlib import contextmanager

DATABASE_NAME = 'blog.db'

def create_tables():
    with sqlite3.connect(DATABASE_NAME) as conn:
        conn.execute('''
            CREATE TABLE IF NOT EXISTS blog_posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                content TEXT NOT NULL
            )
        ''')

@contextmanager
def get_db():
    conn = sqlite3.connect(DATABASE_NAME)
    try:
        yield conn
    finally:
        conn.commit()
        conn.close()
  • create_tables()创建blog_posts表(如果尚不存在)。
  • get_db()是一个上下文管理器,提供与 SQLite 数据库的连接。

第 4 步:定义博客文章模型和模板

现在数据库已经设置完毕,需要一个模型来表示博客文章和与数据库交互的函数。在models.py文件中,将定义一个BlogPost类和函数来获取所有帖子并创建新帖子。

app/models.py

from app.database import get_db

class BlogPost:
    def __init__(self, id: int, title: str, content: str):
        self.id = id
        self.title = title
        self.content = content

def get_all_posts():
    with get_db() as conn:
        cursor = conn.execute('SELECT id, title, content FROM blog_posts')
        rows = cursor.fetchall()
        return [BlogPost(id=row[0], title=row[1], content=row[2]) for row in rows]

def create_post(title: str, content: str):
    with get_db() as conn:
        conn.execute('INSERT INTO blog_posts (title, content) VALUES (?, ?)', (title, content))
  • get_all_posts()从数据库中获取所有博客文章。
  • create_post()将新博客文章插入数据库。

Python 中的 HTML 模板

接下来,将创建两个用于呈现博客文章列表的基本模板和一个用于创建新文章的表单。这些将在templates.py文件中定义。

app/templates.py

def blog_list_template(posts):
    return f"""
    
        Blog Posts
        
            

All Blog Posts

    {''.join([f'
  • {post.title}
  • ' for post in posts])}
Create a new post """ def create_post_template(): return """ Create Post

Create a New Blog Post





Back to posts """
  • blog_list_template()呈现所有博客文章的列表。
  • create_post_template()提供了一个用于创建新博客文章的表单。

第 5 步:编写 FastHTML 应用程序

现在,将在main.py文件中将所有内容联系在一起。这是定义路由和处理请求的地方。

app/main.py

from fasthtml import FastHTML
from app.templates import blog_list_template, create_post_template
from app.models import get_all_posts, create_post
from app.database import create_tables

app = FastHTML()

# Create the database tables before starting the app
create_tables()

@app.route("/")
def index():
    posts = get_all_posts()
    return blog_list_template(posts)

@app.route("/create", methods=["GET"])
def create_post_get():
    return create_post_template()

# Define this as an async function to handle form data properly
@app.route("/create", methods=["POST"])
async def create_post_post(request):
    form_data = await request.form()  # Await for the form data
    title = form_data.get("title")
    content = form_data.get("content")
    create_post(title, content)
    return f"

Post '{title}' created! Go back

"

该文件定义了三个主要路由:

  1. GET / :显示所有博客文章的列表。
  2. GET /create :显示用于创建新博客文章的表单。
  3. POST /create :处理表单提交以创建新帖子。

第 6 步:使用 Uvicorn 运行应用程序

FastHTML 不会自动启动服务器。相反,将使用Uvicorn (一个 ASGI 服务器)来为应用程序提供服务。

运行应用程序

要使用 Uvicorn 运行应用程序,请使用以下命令:

uvicorn app.main:app --reload

第 7 步:测试博客网站

  1. 查看所有帖子:导航至http://127.0.0.1:8000/查看博客帖子列表。
  2. 创建新帖子:转到http://127.0.0.1:8000/create添加新博客帖子。提交表单后,将被重定向并显示成功消息。

要在使用 Uvicorn 运行 FastHTML 应用程序时更改默认的8000端口号,可以使用 Uvicorn 命令中的--port选项指定所需的端口。

例如,如果想在端口5000而不是8000上运行应用程序,您可以使用以下命令:

uvicorn app.main:app --reload --port 5000

在此命令中:

  • --port 5000将端口设置为5000 (或您喜欢的任何其他端口号)。

完整命令细分:

  • app.main:app :这将 Uvicorn 指向app/目录中main.py文件中的app对象。
  • --reload :每当您进行代码更改时,这都会自动重新加载服务器。
  • --port 5000 :指定运行应用程序的端口号。

可以将5000替换为您希望应用程序运行的任何其他端口号。运行此命令后,您的应用程序将可以通过http://127.0.0.1:5000/ (或您指定的端口)访问。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言