pydocumentdb CosmosDb Python如何向同一文档添加多个条目

2024-10-03 13:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用pydocumentdb库在Cosmo Db和Python中为同一文档添加多个条目

我以为用CreateDocuments函数是可能的

只需输入一个条目即可创建文档

def GetSalesOrder(document_id):
    # notice new fields have been added to the sales order
    order2 = {'id' : document_id,
            'account_number' : 'Account2',
            'purchase_order_number' : 'PO15428132599',
            'order_date' : datetime.date(2005,7,11).strftime('%c'),
            'due_date' : datetime.date(2005,7,21).strftime('%c'),
            'shipped_date' : datetime.date(2005,7,15).strftime('%c'),
            'subtotal' : 6107.0820,
            'tax_amount' : 586.1203,
            'freight' : 183.1626,
            'discount_amt' : 1982.872,
            'total_due' : 4893.3929,
            'items' : [
                {'order_qty' : 3,
                 'product_code' : 'A-123',      # notice how in item details we no longer reference a ProductId
                 'product_name' : 'Product 1',  # instead we have decided to denormalise our schema and include 
                 'currency_symbol' : '$',       # the Product details relevant to the Order on to the Order directly
                 'currecny_code' : 'USD',       # this is a typical refactor that happens in the course of an application
                 'unit_price' : 17.1,           # that would have previously required schema changes and data migrations etc.
                 'line_price' : 5.7
                }
                ],
            'ttl' : 60 * 60 * 24 * 30
            }

    return order2



coll_link = database_link + '/colls/sales' 

print('\n1.2 Creating collection\n')

collection = client.CreateCollection(database_link,
            { 'id': "sales" })

print('\n1.2 Creating document\n')           
sales_order = DocumentManagement.GetSalesOrder("SalesOrder")
client.CreateDocument(coll_link, sales_order)

然后,我尝试在同一文档中使用不同的条目重用此代码,但我的程序失败,原因是:

^{pr2}$

谢谢你的帮助

失败的完整代码

import pydocumentdb.documents as documents
import pydocumentdb.document_client as document_client
import pydocumentdb.errors as errors
import datetime

import config as cfg

HOST = cfg.settings['host']
MASTER_KEY = cfg.settings['master_rw_key']
DATABASE_ID = cfg.settings['database_id']
COLLECTION_ID = cfg.settings['collection_id']

database_link = 'dbs/' + DATABASE_ID
collection_link = database_link + '/colls/' + COLLECTION_ID

class IDisposable:
    """ A context manager to automatically close an object with a close method
    in a with statement. """

    def __init__(self, obj):
        self.obj = obj

    def __enter__(self):
        return self.obj # bound to target

    def __exit__(self, exception_type, exception_val, trace):
        # extra cleanup in here
        self = None

class DocumentManagement:

    @staticmethod
    def CreateDocuments(client): 
        coll_link = database_link + '/colls/sales' 

        print('\n1.2 Creating collection\n')

        collection = client.CreateCollection(database_link,
                    { 'id': "sales" })

        print('\n1.2 Creating document\n')           
        sales_order = DocumentManagement.GetSalesOrder("SalesOrder")
        client.CreateDocument(coll_link, sales_order)

    @staticmethod
    def AddEntry(client):
        coll_link = database_link + '/colls/sales' #+ '/docs/SalesOrder' 
        print('\n1.2 Creating row\n')           
        sales_order = DocumentManagement.GetSalesOrder2("SalesOrder")
        client.CreateDocument(coll_link, sales_order)

    @staticmethod
    def CreateStoredProcedure(client): 
        coll_link = database_link + '/colls/sales' 
        sproc1 = {
                    'id': 'countDocuments',
                    'body': (
                        'function () {' +
                        '    var collection = getContext().getCollection(); '  +

                        '    collection.queryDocuments(' +
                        '        collection.getSelfLink(),' +
                        '        \'SELECT VALUE COUNT(SalesOrder.id) FROM SalesOrder\',' +
                        '        function(error, result) {' +
                        '            if (error) throw error;' +

                        '            var count = result[0];' +

                        '            getContext().getResponse().setBody(count);' +
                        '        }' +
                        '        );' +
                        '    }'
                    )

                }
        print('\n1.2 Creating sproc\n') 
        retrieved_sproc = client.CreateStoredProcedure(coll_link, sproc1)

    @staticmethod
    def CountEntries(client):
        coll_link = database_link + '/colls/sales' 
        sproc_link = coll_link + '/sprocs/countDocuments'

        print('\n1.2 Counting rows\n')           
        #sales_order = DocumentManagement.getSalesOrder2("SalesOrder")
        #client.CreateDocument(coll_link, sales_order)   
        params = {}    

        options = {} 
        options['enableCrossPartitionQuery'] = True

        result = client.ExecuteStoredProcedure(sproc_link, params, options)
        print(result)          


    @staticmethod
    def DeleteCollection(client):

        coll_link = database_link + '/colls/sales' 

        print('\n1.2 Delete collection\n')
        client.DeleteCollection(coll_link)

    @staticmethod
    def DeleteDocument(client, doc_id):
        coll_link = database_link + '/colls/sales' 

        print('\n1.2 Deleting Document by Id\n')
        doc_link = coll_link + '/docs/' + doc_id

        client.DeleteDocument(doc_link)


    @staticmethod
    def GetSalesOrder(document_id):
        # notice new fields have been added to the sales order
        order2 = {'id' : document_id,
                'account_number' : 'Account2',
                'purchase_order_number' : 'PO15428132599',
                'order_date' : datetime.date(2005,7,11).strftime('%c'),
                'due_date' : datetime.date(2005,7,21).strftime('%c'),
                'shipped_date' : datetime.date(2005,7,15).strftime('%c'),
                'subtotal' : 6107.0820,
                'tax_amount' : 586.1203,
                'freight' : 183.1626,
                'discount_amt' : 1982.872,
                'total_due' : 4893.3929,
                'items' : [
                    {'order_qty' : 3,
                     'product_code' : 'A-123',      # notice how in item details we no longer reference a ProductId
                     'product_name' : 'Product 1',  # instead we have decided to denormalise our schema and include 
                     'currency_symbol' : '$',       # the Product details relevant to the Order on to the Order directly
                     'currecny_code' : 'USD',       # this is a typical refactor that happens in the course of an application
                     'unit_price' : 17.1,           # that would have previously required schema changes and data migrations etc.
                     'line_price' : 5.7
                    }
                    ],
                'ttl' : 60 * 60 * 24 * 30
                }

        return order2

    @staticmethod
    def GetSalesOrder2(document_id):
        order = {'id' : document_id, 'account_number' : 'Account3',#
                                'purchase_order_number' : 'PO15428132601',
                                'order_date' : datetime.date(2005,7,11).strftime('%c'),
                                'due_date' : datetime.date(2005,7,21).strftime('%c'),
                                'shipped_date' : datetime.date(2005,7,15).strftime('%c'),
                                'subtotal' : 6107.0820,
                                'tax_amount' : 586.1203,
                                'freight' : 183.1626,
                                'discount_amt' : 1982.872,
                                'total_due' : 4893.3929,
                                'items' : [
                                    {'order_qty' : 3,
                                     'product_code' : 'A-123',      # notice how in item details we no longer reference a ProductId
                                     'product_name' : 'Product 1',  # instead we have decided to denormalise our schema and include 
                                     'currency_symbol' : '$',       # the Product details relevant to the Order on to the Order directly
                                     'currecny_code' : 'USD',       # this is a typical refactor that happens in the course of an application
                                     'unit_price' : 17.1,           # that would have previously required schema changes and data migrations etc.
                                     'line_price' : 5.7
                                    }
                                    ],
                                'ttl' : 60 * 60 * 24 * 30
                                }

def run_sample():
    with IDisposable(document_client.DocumentClient(HOST, {'masterKey': MASTER_KEY} )) as client:
        try:
            DocumentManagement.CreateDocuments(client)
            DocumentManagement.CreateStoredProcedure(client)
            DocumentManagement.CountEntries(client)
            DocumentManagement.AddEntry(client)
            DocumentManagement.CountEntries(client)

            DocumentManagement.DeleteDocument(client,'SalesOrder')
            DocumentManagement.DeleteCollection(client)


        except errors.HTTPFailure as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))

        finally:
            print("\nrun_sample done")

if __name__ == '__main__':
    try:
        run_sample()

    except Exception as e:
            print("Top level Error: args:{0}, message:N/A".format(e.args))

Tags: thetoclientiddatetimedatedeflink
1条回答
网友
1楼 · 发布于 2024-10-03 13:28:10

代码失败的原因是您的GetSalesOrder2方法没有返回任何内容(或者换句话说,返回一个undefined对象)。如果仔细看,它缺少return语句。请将此方法更改为:

  def GetSalesOrder2(document_id):
      order = {'id' : document_id, 'account_number' : 'Account3',#
                              'purchase_order_number' : 'PO15428132601',
                              'order_date' : datetime.date(2005,7,11).strftime('%c'),
                              'due_date' : datetime.date(2005,7,21).strftime('%c'),
                              'shipped_date' : datetime.date(2005,7,15).strftime('%c'),
                              'subtotal' : 6107.0820,
                              'tax_amount' : 586.1203,
                              'freight' : 183.1626,
                              'discount_amt' : 1982.872,
                              'total_due' : 4893.3929,
                              'items' : [
                                  {'order_qty' : 3,
                                   'product_code' : 'A-123',      # notice how in item details we no longer reference a ProductId
                                   'product_name' : 'Product 1',  # instead we have decided to denormalise our schema and include 
                                   'currency_symbol' : '$',       # the Product details relevant to the Order on to the Order directly
                                   'currecny_code' : 'USD',       # this is a typical refactor that happens in the course of an application
                                   'unit_price' : 17.1,           # that would have previously required schema changes and data migrations etc.
                                   'line_price' : 5.7
                                  }
                                  ],
                              'ttl' : 60 * 60 * 24 * 30
                              }

      return order

此外,集合中的每个文档都需要有一个唯一的id,因此请为此文档定义一个不同的id。在

相关问题 更多 >