This time, we will see how to operate Azure Cosmos DB from Python with reference to the quick start.
First of all Latest Python installation-> https://www.python.org/ Perform a Python installation in Visual Studio Code. Installing Python in VS Code is optional, but it's very useful because you can mess with Python directly in VS Code and there are various shortcuts. https://marketplace.visualstudio.com/items?itemName=ms-python.python#overview
Clone the code from GitHub published by Microsoft.
git clone https://github.com/Azure-Samples/azure-cosmos-db-python-getting-started.git
Open the Visual Studio Terminal and navigate to the cloned local directory.
Deploy Azure Cosmos DB. This time we'll create a simple Cosmos DB, so we'll deploy it from the Azure CLI.
az cosmosdb create --name <account-name> --resource-group <resource-group-name>
Once created, run the following command from the Azure CLI to get the Endpoint and Key.
az cosmosdb keys list --name <account-name> --resource-group <resource-group-name>
az cosmosdb show --name <account-name> --resource-group <resource-group-name>
Execute the following code from the Visual Studio terminal that goes to the corresponding directory.
python cosmos_get_started.py
Then the following is output.
Read item with id Smith_d457f895-3756-49cd-a629-e7708d7ed252. Operation consumed 1 request units
Read item with id Johnson_3bd2aa16-742f-4aed-9a95-3adc548a94e3. Operation consumed 1 request units
Read item with id Wakefield_c73aa98d-7104-4b01-a3da-4946081575ff. Operation consumed 1 request units
Query returned 2 items. Operation consumed 3.09 request units
When I checked the Portal page, I was able to confirm that I was able to operate Cosmos DB.
I was a little addicted to this time when the following error occurred.
Traceback (most recent call last):
File "cosmos_get_started.py", line 1, in <module>
from azure.cosmos import exceptions, CosmosClient, PartitionKey
ImportError: cannot import name 'exceptions' from 'azure.cosmos' (...\lib\site-packages\azure\cosmos\__init__.py)
This error is caused by an incorrect installation of the Azure Cosmos DB SDK. If you have the -perp version of the Azure Cosmos SDK installed, you will run into this error. The solution is a workaround as described in the Python documentation below.
https://pypi.org/project/azure-cosmosdb-table/ (Reference source) https://docs.microsoft.com/ja-jp/azure/cosmos-db/table-sdk-python
Also, the following page describes the correct installation method of the Python SDK, so it will be helpful to take a look!
https://github.com/Azure/azure-cosmos-table-python/tree/master/azure-cosmosdb-table
Recommended Posts