FastAPI使用MySQL

FastAPI是一个现代的、高性能的Web框架,使用Python编写,具有快速、易于使用和易于维护的特点。MySQL是一个流行的关系型数据库管理系统,广泛用于各种Web应用程序。本文将介绍如何在FastAPI中使用MySQL数据库,包括安装必要的库、连接数据库、执行SQL查询等操作。

安装依赖库

在开始之前,我们需要安装两个主要的依赖库:fastapimysql-connector-python。可以使用pip命令来安装这些库:

$ pip install fastapi
$ pip install mysql-connector-python

连接数据库

首先,我们需要在FastAPI应用程序的主文件中导入FastAPImysql.connector库,并创建一个app实例,作为我们的主要应用程序。

# main.py

from fastapi import FastAPI
import mysql.connector

app = FastAPI()

然后,我们需要编写一个函数来连接到MySQL数据库。我们将使用mysql.connector库提供的connect()函数来建立与数据库的连接。在这个函数中,我们需要提供数据库的主机、用户名、密码和数据库名称。

# main.py

...

def connect_to_database():
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="root",
            password="password",
            database="mydatabase"
        )
        return connection
    except mysql.connector.Error as e:
        print("Error connecting to MySQL database:", e)

执行SQL查询

现在我们已经建立了与MySQL数据库的连接,接下来我们可以编写一些函数来执行SQL查询并返回结果。

# main.py

...

def execute_query(query):
    try:
        connection = connect_to_database()
        cursor = connection.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        connection.close()
        return result
    except mysql.connector.Error as e:
        print("Error executing SQL query:", e)

在上面的代码中,我们定义了一个execute_query()函数,它接受一个SQL查询字符串作为参数,并使用cursor.execute()方法执行查询。然后,我们使用cursor.fetchall()方法获取查询结果,并关闭游标和数据库连接。

使用FastAPI路由

现在我们已经准备好使用MySQL数据库了,我们可以在FastAPI应用程序中定义一些路由,以便我们可以通过HTTP请求来执行SQL查询并返回结果。

# main.py

...

@app.get("/users")
def get_users():
    query = "SELECT * FROM users"
    result = execute_query(query)
    return {"users": result}

在上面的代码中,我们定义了一个GET请求的路由/users,它调用了get_users()函数来执行查询SELECT * FROM users并返回结果。

测试应用程序

现在,我们可以使用uvicorn命令运行FastAPI应用程序,并在浏览器中访问http://localhost:8000/users来测试我们的应用程序。

$ uvicorn main:app --reload

当我们访问http://localhost:8000/users时,我们将获得一个JSON响应,其中包含从MySQL数据库中获取的用户数据。

{
  "users": [
    {
      "id": 1,
      "name": "John Doe",
      "email": "john.doe@example.com"
    },
    {
      "id": 2,
      "name": "Jane Smith",
      "email": "jane.smith@example.com"
    },
    ...
  ]
}

总结

在本文中,我们学习了如何在FastAPI中使用MySQL数据库。我们首先安装了必要的依赖库,然后创建了一个函数来连接到MySQL数据库。接下来,我们编写了一个函数来执行SQL查询,并在FastAPI应用程序中定义了一些路由来测试我们的应用程序。通过这些步骤,我们可以轻松地在FastAPI中使用MySQL数据库,并编写强大的Web应用程序。

sequenceDiagram
    participant User
    participant FastAPI
    participant MySQL

    User->>FastAPI: 发送HTTP请求
    FastAPI->>MySQL: 执行SQL查询
    MySQL-->>FastAPI: 返回查询结果
    FastAPI-->>User: 返回JSON响应
stateDiagram
    [*] --> 连接到MySQL数据库
    连