快速入门:使用 Azure Cosmos DB 的 API for MongoDB 构建 Python 应用Quickstart: Build a Python app using Azure Cosmos DB's API for MongoDB

在本快速入门中,我们使用 Mongo DB API 帐户的 Azure Cosmos DB 或 Azure Cosmos DB 模拟器来运行从 GitHub 克隆的 Python Flask To-Do Web 应用。In this quickstart, you use an Azure Cosmos DB for Mongo DB API account or the Azure Cosmos DB Emulator to run a Python Flask To-Do web app cloned from GitHub. Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities.

先决条件Prerequisites

克隆示例应用程序Clone the sample application

现在,请从 GitHub 克隆 Flask-MongoDB 应用、设置连接字符串并运行该应用。Now let's clone a Flask-MongoDB app from GitHub, set the connection string, and run it. 你会看到以编程方式处理数据是多么容易。You see how easy it is to work with data programmatically.

  1. 打开命令提示符,新建一个名为“git-samples”的文件夹,然后关闭命令提示符。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 运行下列命令,克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/CosmosDB-Flask-Mongo-Sample.git
    
  4. 运行以下命令以安装 python 模块。Run the following command to install the python modules.

    pip install -r .\requirements.txt
    
  5. 在 Visual Studio Code 中打开该文件夹。Open the folder in Visual Studio Code.

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解如何使用代码创建数据库资源,可以查看以下代码片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 否则,可以跳到运行 Web 应用Otherwise, you can skip ahead to Run the web app.

以下代码片段全部摘自 app.py 文件,并对本地 Azure Cosmos DB 模拟器使用连接字符串。The following snippets are all taken from the app.py file and uses the connection string for the local Azure Cosmos DB Emulator. 密码需要进行拆分(如下所示)以适应在其他方面无法解析的正斜杠。The password needs to be split up as seen below to accommodate for the forward slashes that cannot be parsed otherwise.

  • 初始化 MongoDB 客户端、检索数据库,并进行身份验证。Initialize the MongoDB client, retrieve the database, and authenticate.

    client = MongoClient("mongodb://127.0.0.1:10250/?ssl=true") #host uri
    db = client.test    #Select the database
    db.authenticate(name="localhost",password='C2y6yDjf5' + r'/R' + '+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw' + r'/Jw==')
    
  • 检索集合或创建集合(如果不存在)。Retrieve the collection or create it if it does not already exist.

    todos = db.todo #Select the collection
    
  • 创建应用程序Create the app

    app = Flask(__name__)
    title = "TODO with Flask"
    heading = "ToDo Reminder"
    

运行 Web 应用Run the web app

  1. 确保 Azure Cosmos DB 模拟器正在运行。Make sure the Azure Cosmos DB Emulator is running.

  2. 打开终端窗口并使用 cd 切换到保存应用的目录。Open a terminal window and cd to the directory that the app is saved in.

  3. 然后,使用 set FLASK_APP=app.py$env:FLASK_APP = app.py(适用于 PowerShell 编辑器)或 export FLASK_APP=app.py(如果使用的是 Mac)设置 Flask 应用的环境变量。Then set the environment variable for the Flask app with set FLASK_APP=app.py, $env:FLASK_APP = app.py for PowerShell editors, or export FLASK_APP=app.py if you are using a Mac.

  4. 使用 flask run 运行此应用并浏览到 http://127.0.0.1:5000/Run the app with flask run and browse to http://127.0.0.1:5000/.

  5. 添加和删除任务,并查看集合中添加和更改的任务。Add and remove tasks and see them added and changed in the collection.

创建数据库帐户Create a database account

若要针对实时 Azure Cosmos DB 帐户测试代码,请转到 Azure 门户创建一个帐户。If you want to test the code against a live Azure Cosmos DB account, go to the Azure portal to create an account.

  1. 在新浏览器窗口中,登录到 Azure 门户In a new browser window, sign in to the Azure portal.

  2. 在左侧菜单中,选择“创建资源” 。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置 。On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    设置Setting Value 说明Description
    订阅Subscription 你的订阅Your subscription 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    资源组Resource Group 新建Create new

    然后,输入与帐户名称相同的名称。Then enter the same name as Account Name
    选择“新建”。 Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“mongo.cosmos.azure.cn” 。Your account URI will be mongo.cosmos.azure.cn appended to your unique account name.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    APIAPI Azure Cosmos DB for Mongo DB APIAzure Cosmos DB for Mongo DB API API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据库的 Core (SQL)、适用于图形数据库的 Gremlin、适用于文档数据库的 Azure Cosmos DB for Mongo DB API、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB for Mongo DB API for document databases, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“Azure Cosmos DB for Mongo DB API”,因为本快速入门将创建使用 MongoDB 的集合 。Select Azure Cosmos DB for Mongo DB API because in this quickstart you are creating a collection that works with MongoDB.

    了解有关 Azure Cosmos DB for MongoDB API 的详细信息Learn more about Azure Cosmos DB for MongoDB API.
    位置Location 选择离用户最近的区域Select the region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that's closest to your users to give them the fastest access to the data.

    选择“查看 + 创建” 。Select Review+Create. 可以跳过“网络” 和“标记” 部分。You can skip the Network and Tags section.

    Azure Cosmos DB 的“新建帐户”页

  5. 创建帐户需要几分钟时间。The account creation takes a few minutes. 等待门户中显示“祝贺你! Azure Cosmos DB for MongoDB 帐户已准备就绪”页。Wait for the portal to display the Congratulations! Your Azure Cosmos DB for Mongo DB API account is ready page.

    Azure 门户“通知”窗格

更新连接字符串Update your connection string

若要针对实时 Azure Cosmos DB 帐户测试代码,请获取连接字符串信息。To test the code against the live Azure Cosmos DB account, get your connection string information. 然后将其复制到此应用中。Then copy it into the app.

  1. 在 Azure 门户的 Azure Cosmos DB 帐户的左侧导航栏中,选择“连接字符串”,然后选择“读写密钥”。**** ****In your Azure Cosmos DB account in the Azure portal, in the left navigation select Connection String, and then select Read-write Keys. 我们将使用屏幕右侧的复制按钮复制用户名、连接字符串和密码。You'll use the copy buttons on the right side of the screen to copy the username, connection string, and password.

  2. 在根目录中打开 app.py 文件**。Open the app.py file in the root directory.

  3. 从门户中(使用复制按钮)复制“用户名”值,并在 app.py 文件中将其设为“名称”的值**** ******。Copy your username value from the portal (using the copy button) and make it the value of the name in your app.py file.

  4. 然后从门户中复制“连接字符串”值,并在 app.py 文件中将其设为 MongoClient 值**** ****。Then copy your connection string value from the portal and make it the value of the MongoClient in your app.py file.

  5. 最后从门户复制“密码”值,并在 app.py 文件中将其设为“密码”的值**** ******。Finally copy your password value from the portal and make it the value of the password in your app.py file.

现已使用与 Azure Cosmos DB 进行通信所需的所有信息更新应用。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB. 此时,即可像以前一样运行它。You can run it the same way as before.

“部署到 Azure”Deploy to Azure

若要部署此应用,可在 Azure 中创建新的 Web 应用,并使用此 GitHub 存储库分支启用持续部署。To deploy this app, you can create a new web app in Azure and enable continuous deployment with a fork of this GitHub repo. 按照此教程,在 Azure 中使用 GitHub 设置持续部署。Follow this tutorial to set up continuous deployment with GitHub in Azure.

部署到 Azure 时,应删除应用程序密钥并确保以下部分未被注释掉:When deploying to Azure, you should remove your application keys and make sure the section below is not commented out:

client = MongoClient(os.getenv("MONGOURL"))
db = client.test    #Select the database
db.authenticate(name=os.getenv("MONGO_USERNAME"),password=os.getenv("MONGO_PASSWORD"))

然后需要将 MONGOURL、MONGO_PASSWORD 和 MONGO_USERNAME 添加到应用程序设置中。You then need to add your MONGOURL, MONGO_PASSWORD, and MONGO_USERNAME to the application settings. 可参阅此教程了解有关 Azure Web 应用中应用程序设置的详细信息。You can follow this tutorial to learn more about Application Settings in Azure Web Apps.

Note

如果打算将代码存储在 GitHub 或其他源代码管理选项中,请务必从代码中删除连接字符串。If you plan to store your code in GitHub or other source control options, please be sure to remove your connection strings from the code. 可改为使用 Web 应用的应用程序设置进行设置。They can be set with application settings for the web app instead.

在 Azure 门户中查看 SLAReview SLAs in the Azure portal

Azure 门户监视 Cosmos DB 帐户吞吐量、存储、可用性、延迟和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服务级别协议 (SLA) 关联的指标的图表显示与实际性能相比的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此套指标使得监视 SLA 十分透明。This suite of metrics makes monitoring your SLAs transparent.

若要查看指标和 SLA,请执行以下操作:To review metrics and SLAs:

  1. 在 Cosmos DB 帐户的导航菜单中选择“指标” 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 选择一个选项卡,如“延迟” ,然后选择右侧的时间范围。Select a tab such as Latency, and select a timeframe on the right. 比较图表上的“实际” 和“SLA” 线。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 指标套件

  3. 查看其他选项卡上的指标。Review the metrics on the other tabs.

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要删除资源,请执行以下操作:To delete the resources:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。In the Azure portal Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

本快速入门介绍了如何创建 Mongo DB API 帐户的 Azure Cosmos DB,以及如何使用 Azure Cosmos DB 模拟器运行从 GitHub 克隆的 Python Flask To-Do Web 应用。In this quickstart, you learned how to create an Azure Cosmos DB for Mongo DB API account, and use the Azure Cosmos DB Emulator to run a Python Flask To-Do web app cloned from GitHub. 现在可以将其他数据导入 Azure Cosmos DB 帐户了。You can now import additional data to your Azure Cosmos DB account.