當前位置: 首頁>>代碼示例>>Python>>正文


Python TableService.create_table方法代碼示例

本文整理匯總了Python中azure.storage.TableService.create_table方法的典型用法代碼示例。如果您正苦於以下問題:Python TableService.create_table方法的具體用法?Python TableService.create_table怎麽用?Python TableService.create_table使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在azure.storage.TableService的用法示例。


在下文中一共展示了TableService.create_table方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
def main(argv=None):
#we created four azureML service endpoints to maximize parallelism.
#the program is invoked with one parameter: a number between 0 and 3 that select the
#end point that is used.
#you need to create at least one endpoint
#you also need your stream namespace to listen for events
#and you need a table service to store the results
    endpoints=[]
    url = 'the original service endpoint url'
    api_key = 'the original service key'
    endpoints.extend([[url, api_key]])
    url2 = 'a second enpoint url'
    api_key2 = 'the key for the second'
    endpoints.extend([[url2, api_key2]])
    url3 = 'the third endpoint url'
    api_key3 = 'the key for the third'
    endpoints.extend([[url3, api_key3]])
    url4 = 'the fourth endpint url'
    api_key4 = 'the key for the fourth'
    endpoints.extend([[url4, api_key4]])
        
    if argv is None: 
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
        bus_service = ServiceBusService(
            service_namespace='your stream',
            shared_access_key_name='listenpolicy',
            shared_access_key_value='your access key')
            
        #next set up the table service
        table_service = TableService(account_name='your table account', account_key='account key')
        table_service.create_table('scimlevents')
        hostname = socket.gethostname()      
        
        if len(args)< 1:
            print "need the endpoint number"
            return 2
        
        endpointid = int(args[0])
        url = endpoints[endpointid][0]
        api_key = endpoints[endpointid][1]
        print url
        print api_key
        print "starting with endpoint "+str(endpointid)
        while True:
            print "running"            
            processevents(table_service, hostname, bus_service, url, api_key)
        print "all done."
開發者ID:dbgannon,項目名稱:eventstreams,代碼行數:54,代碼來源:pull-events-from-eventhub-through-queue.py

示例2: main

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
 
        #next set up the table service
        table_service = TableService(account_name='azure table', account_key='long account key for this storage service')
        table_service.create_table('name of table')
        hostname = socket.gethostname()
        quename = gettopic()
        processevents(quename, table_service, hostname)
        print "all done."
開發者ID:dbgannon,項目名稱:dcos,代碼行數:18,代碼來源:generic-worker.py

示例3: do_step

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
def do_step(context):

    settings = context.meta['settings']

    # Prepare the containers
    storage_account_name = settings["STORAGE-ACCOUNT-NAME"]
    storage_access_key = settings["STORAGE-ACCESS-KEY"]
    blob_service = BlobService(storage_account_name, storage_access_key)
    blob_service.create_container('bosh')
    blob_service.create_container(container_name='stemcell', x_ms_blob_public_access='blob')

    # Prepare the table for storing meta datas of storage account and stemcells
    table_service = TableService(storage_account_name, storage_access_key)
    table_service.create_table('stemcells')

    context.meta['settings'] = settings
    return context
開發者ID:KundanaP,項目名稱:bosh-azure-template,代碼行數:19,代碼來源:prep_containers_and_tables.py

示例4: __init__

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
class conobj:
        def __init__(self,pikaIP, rabbitid, rabbitpasswd, TableAccountName, TableKey ):
                self.ipad = socket.gethostname()
                self.pikaIP = pikaIP
                self.creds = pika.PlainCredentials(rabbitid, rabbitpasswd)
                self.connec = pika.BlockingConnection(pika.ConnectionParameters(pikaIP, 5672,'/',self.creds))
                self.chan = self.connec.channel()
                self.chan.queue_declare(queue='hello', auto_delete=False, exclusive=False)
                self.table_service = TableService(account_name=TableAccountName, account_key=TableKey)
                self.table_service.create_table('sciml')
                self.chan.basic_publish(exchange='',
                        routing_key='hello',
                        body='start up newest server at address '+self.ipad)
                self.chan.cancel()
                self.connec.close()
                self.chan = None

        def recon(self):
                #this is the slow method.   but reliable.
                try:
                        self.connec = pika.BlockingConnection(pika.ConnectionParameters(self.pikaIP, 5672,'/',self.creds))
                        self.chan = self.connec.channel()
                        self.chan.queue_declare(queue='hello', auto_delete=False, exclusive=False)
                except:
                        self.fullrecon()
        
        def fullrecon(self):
                if self.chan is not None:
                        self.chan.cancel()
                #self.connec.close()
                time.sleep(2.0)
                print "reconnecting to rabbitmq"
                self.connec = pika.BlockingConnection(pika.ConnectionParameters(self.pikaIP, 5672,'/',self.creds))
                self.chan = self.connec.channel()
                self.chan.queue_declare(queue='hello', auto_delete=False, exclusive=False)
                self.chan.basic_publish(exchange='', routing_key='hello',
                body='reconnecting to rabbitmq')
        
        def decon(self):
                if self.chan is not None:
                        #self.chan.basic_publish(exchange='',
                        #        routing_key='hello',
                        #        body='disconect from address '+self.ipad)
                        self.chan.cancel()
                        self.connec.close()
                        self.chan = None
開發者ID:dbgannon,項目名稱:sciml,代碼行數:48,代碼來源:scimlservice.py

示例5: __init__

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
class AzureDataServices:
    _partition = 'presence'

    def __init__(self, table):
        self._partition = table
        with open('azure.txt') as f:
            lines = f.readlines()
        acc = lines[0].strip()
        key = lines[1].strip()
        self._table_service = TableService(account_name=acc, account_key=key)
    
    def create_table(self):
        """
        Creates azure storage table
        """
        self._table_service.create_table(self._partition)

    def insert_data(self, task):
        """
        Insert the object to azure
        """
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        task.PartitionKey = self._partition
        task.RowKey = t

        self._table_service.insert_entity(self._partition, task)

    def insert_presence(self, p):
        """
        Uploads value to azure table storage
        """
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        task = Entity()
        task.PartitionKey = self._partition
        task.RowKey = t

        task.users_arrived = ','.join(map(str, p.users_arrived)) 
        task.users_left = ','.join(map(str, p.users_left)) 

        self._table_service.insert_entity(self._partition, task)

    def get_presence(self):
        tasks = self._table_service.query_entities(self._partition, "PartitionKey eq 'presence'")
        return tasks
開發者ID:kovacsbalu,項目名稱:HomeAutomatization,代碼行數:46,代碼來源:AzureDataServices.py

示例6: TableService

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
from azure.storage import TableService, Entity
from flask.json import dumps
import datetime

table_name = 'testtable'
doc_partition = 'docs'

table_service = TableService(account_name = "docdash", account_key = "2f5QoMeIsCOsT6aitQqbcoH/ydSFnqwCxQIPpE0JEtQJR0o9Frqzc9btgLVZ9Y8wbhd7CRj9Q//X8qWku8fl3w==")
table_service.create_table(table_name)

def add_data_to_doc(docid, data, time):
    ensure_doc(docid)
    e = Entity()
    e.PartitionKey = docid
    e.RowKey = "{:015}".format(int(time))
    e.charcount = data["charcount"]
    table_service.insert_or_replace_entity(table_name, e.PartitionKey, e.RowKey, e)

def ensure_doc(docid):
    table_service.insert_or_replace_entity(table_name, doc_partition, docid, dict())

def get_data_for_doc(docid):
    timevalues = table_service.query_entities(table_name, "PartitionKey eq '" + docid + "'")
    data = []
    for timevalue in timevalues:
        data.append([datetime.datetime.utcfromtimestamp(int(timevalue.RowKey)), timevalue.charcount])
    return data

def get_time_created(docid):
    try:
        doc = table_service.get_entity(table_name, doc_partition, docid)
開發者ID:saunders77,項目名稱:docdashboard,代碼行數:33,代碼來源:storage.py

示例7: get_connection_string_and_create_table

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
def get_connection_string_and_create_table():
	global table_service
	table_service = TableService(account_name = ac_name,account_key=primary_key)
	#table_service.delete_table(table_name = table_name) #TO BE USED IF THE TABLE NEEDS TO BE DELETED
	table_service.create_table(table=table_name)
開發者ID:KateiRen,項目名稱:AzureTempLogger,代碼行數:7,代碼來源:AzureLogger.py

示例8: BlobService

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
username = settings["username"]
home_dir = os.path.join("/home", username)
install_log = os.path.join(home_dir, "install.log")

# Prepare the containers
storage_account_name = settings["STORAGE-ACCOUNT-NAME"]
storage_access_key = settings["STORAGE-ACCESS-KEY"]
blob_service = BlobService(storage_account_name, storage_access_key)
blob_service.create_container('bosh')
blob_service.create_container(container_name='stemcell',
    x_ms_blob_public_access='blob'
)

# Prepare the table for storing meta datas of storage account and stemcells
table_service = TableService(storage_account_name, storage_access_key)
table_service.create_table('stemcells')

# Generate the private key and certificate
call("sh create_cert.sh", shell=True)
call("cp bosh.key ./bosh/bosh", shell=True)
with open ('bosh_cert.pem', 'r') as tmpfile:
    ssh_cert = tmpfile.read()
ssh_cert = "|\n" + ssh_cert
ssh_cert="\n        ".join([line for line in ssh_cert.split('\n')])

# Render the yml template for bosh-init
bosh_template = 'bosh.yml'
if os.path.exists(bosh_template):
    with open (bosh_template, 'r') as tmpfile:
        contents = tmpfile.read()
    for k in ["RESOURCE-GROUP-NAME", "STORAGE-ACCESS-KEY", "STORAGE-ACCOUNT-NAME", "SUBNET-NAME", "SUBNET-NAME-FOR-CF", "SUBSCRIPTION-ID", "VNET-NAME", "TENANT-ID", "CLIENT-ID", "CLIENT-SECRET"]:
開發者ID:AritroMukherjee,項目名稱:azure-quickstart-templates,代碼行數:33,代碼來源:setup_devbox.py

示例9: Azure

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]

#.........這裏部分代碼省略.........

            import copy, alxlib.node.info

            dict = copy.deepcopy(self.msg_template)
            dict["from"] = format(socket.gethostname())
            dict["from-ip"] = alxlib.node.info.Info().get_ip()
            dict["to"] = to
            dict["reply-to-id"] = replyToId
            dict["cmd"] = "pong"
            dict['creation-time'] = str(self.get_timestamp_now())

            self.msg_send(dict)

        except:
            logging.critical(_("Message creation failure"))


    #helper

    def get_time(self, timestamp):
        try:
            return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
        except:
            return ""

    def get_timestamp_now(self):
        return time.time()

    #table

    def tbl_update(self, name, p, r, d):
        try:
            d["updatetime"] = str(self.get_timestamp_now())
            self.tbl.create_table(name)
            self.tbl.insert_or_merge_entity(name, p, r, d)
        except Exception as e:
            logging.critical("Error update_tbl {0}".format(e))


    def tbl_row_query(self, name, q, n=1000, next_partition_key_=None, next_row_key_=None):
        try:
            self.tbl.create_table(name)

            rows = self.tbl.query_entities(name, filter=q, top=n,
                                           next_partition_key=next_partition_key_,
                                           next_row_key=next_row_key_)
            return rows
        except Exception as e:
            return None

    def entity2dict(self, e):
        try:
            keys = dir(e)
            d = {}
            for key in keys:
                d[key] = getattr(e, key, "")
            return d
        except:
            return None

    def update_net(self):
        try:
            info = Info().get_all()
            self.tbl_update(self.tbl_name, self.tbl_net, info["hostname"], info)
        except:
            logging.warning("Error update_net")
開發者ID:gomes-,項目名稱:alx,代碼行數:70,代碼來源:azure.py

示例10: AzureJobStore

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]

#.........這裏部分代碼省略.........
        jobStoreFileID = self._newFileID(sharedFileName)
        return self.getPublicUrl(jobStoreFileID)

    def _newJobID(self):
        # raw UUIDs don't work for Azure property names because the '-' character is disallowed.
        return str(uuid.uuid4()).replace('-', '_')

    # A dummy job ID under which all shared files are stored.
    sharedFileJobID = uuid.UUID('891f7db6-e4d9-4221-a58e-ab6cc4395f94')

    def _newFileID(self, sharedFileName=None):
        if sharedFileName is None:
            ret = str(uuid.uuid4())
        else:
            ret = str(uuid.uuid5(self.sharedFileJobID, str(sharedFileName)))
        return ret.replace('-', '_')

    def _associateFileWithJob(self, jobStoreFileID, jobStoreID=None):
        if jobStoreID is not None:
            self.jobFileIDs.insert_entity(entity={'PartitionKey': jobStoreID,
                                                  'RowKey': jobStoreFileID})

    def _dissociateFileFromJob(self, jobStoreFileID):
        entities = self.jobFileIDs.query_entities(filter="RowKey eq '%s'" % jobStoreFileID)
        if entities:
            assert len(entities) == 1
            jobStoreID = entities[0].PartitionKey
            self.jobFileIDs.delete_entity(partition_key=jobStoreID, row_key=jobStoreFileID)

    def _getOrCreateTable(self, tableName):
        # This will not fail if the table already exists.
        for attempt in retry_on_error():
            with attempt:
                self.tableService.create_table(tableName)
        return AzureTable(self.tableService, tableName)

    def _getOrCreateBlobContainer(self, containerName):
        for attempt in retry_on_error():
            with attempt:
                self.blobService.create_container(containerName)
        return AzureBlobContainer(self.blobService, containerName)

    def _sanitizeTableName(self, tableName):
        """
        Azure table names must start with a letter and be alphanumeric.

        This will never cause a collision if uuids are used, but
        otherwise may not be safe.
        """
        return 'a' + filter(lambda x: x.isalnum(), tableName)

    # Maximum bytes that can be in any block of an Azure block blob
    # https://github.com/Azure/azure-storage-python/blob/4c7666e05a9556c10154508335738ee44d7cb104/azure/storage/blob/blobservice.py#L106
    _maxAzureBlockBytes = 4 * 1024 * 1024

    @contextmanager
    def _uploadStream(self, jobStoreFileID, container, checkForModification=False, encrypted=None):
        """
        :param encrypted: True to enforce encryption (will raise exception unless key is set),
        False to prevent encryption or None to encrypt if key is set.
        """
        if checkForModification:
            try:
                expectedVersion = container.get_blob_properties(blob_name=jobStoreFileID)['etag']
            except WindowsAzureMissingResourceError:
                expectedVersion = None
開發者ID:kellrott,項目名稱:toil,代碼行數:70,代碼來源:azureJobStore.py

示例11: TableServiceTest

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
class TableServiceTest(AzureTestCase):

    def setUp(self):
        self.tc = TableService(account_name=credentials.getStorageServicesName(), 
                                   account_key=credentials.getStorageServicesKey())

        proxy_host = credentials.getProxyHost()
        proxy_port = credentials.getProxyPort()
        if proxy_host:
            self.tc.set_proxy(proxy_host, proxy_port)

        __uid = getUniqueTestRunID()
        table_base_name = u'testtable%s' % (__uid)
        self.table_name = getUniqueNameBasedOnCurrentTime(table_base_name)     
        self.additional_table_names = []
    
    def tearDown(self):
        self.cleanup()
        return super(TableServiceTest, self).tearDown()

    def cleanup(self):
        try:
            self.tc.delete_table(self.table_name)
        except: pass

        for name in self.additional_table_names:
            try:
                self.tc.delete_table(name)
            except: pass

    #--Helpers-----------------------------------------------------------------
    def _create_table(self, table_name):
        '''
        Creates a table with the specified name.
        '''
        self.tc.create_table(table_name, True)

    def _create_table_with_default_entities(self, table_name, entity_count):
        '''
        Creates a table with the specified name and adds entities with the 
        default set of values. PartitionKey is set to 'MyPartition' and RowKey 
        is set to a unique counter value starting at 1 (as a string).
        '''
        entities = []
        self._create_table(table_name)
        for i in range(1, entity_count + 1):
            entities.append(self.tc.insert_entity(table_name, self._create_default_entity_dict('MyPartition', str(i))))
        return entities

    def _create_default_entity_class(self, partition, row):
        '''
        Creates a class-based entity with fixed values, using all
        of the supported data types.
        '''
        # TODO: Edm.Binary and null
        entity = Entity()
        entity.PartitionKey = partition
        entity.RowKey = row
        entity.age = 39
        entity.sex = 'male'
        entity.married = True
        entity.deceased = False
        entity.optional = None
        entity.ratio = 3.1
        entity.large = 9333111000
        entity.Birthday = datetime(1973,10,04)
        entity.birthday = datetime(1970,10,04)
        entity.binary = None
        entity.other = EntityProperty('Edm.Int64', 20)
        entity.clsid = EntityProperty('Edm.Guid', 'c9da6455-213d-42c9-9a79-3e9149a57833')
        return entity

    def _create_default_entity_dict(self, partition, row):
        '''
        Creates a dictionary-based entity with fixed values, using all
        of the supported data types.
        '''
        # TODO: Edm.Binary and null
        return {'PartitionKey':partition, 
                'RowKey':row, 
                'age':39, 
                'sex':'male', 
                'married':True, 
                'deceased':False, 
                'optional':None, 
                'ratio':3.1, 
                'large':9333111000, 
                'Birthday':datetime(1973,10,04),
                'birthday':datetime(1970,10,04),
                'binary':EntityProperty('Edm.Binary', None),
                'other':EntityProperty('Edm.Int64', 20),
                'clsid':EntityProperty('Edm.Guid', 'c9da6455-213d-42c9-9a79-3e9149a57833')}

    def _create_updated_entity_dict(self, partition, row):
        '''
        Creates a dictionary-based entity with fixed values, with a
        different set of values than the default entity. It
        adds fields, changes field values, changes field types,
        and removes fields when compared to the default entity.
        '''
#.........這裏部分代碼省略.........
開發者ID:Bunkerbewohner,項目名稱:azure-sdk-for-python,代碼行數:103,代碼來源:test_tableservice.py

示例12: TableService

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
import azurecfg
from azure.storage import TableService, Entity

table_service = TableService(
    account_name=azurecfg.table_storage['account_name'],
    account_key=azurecfg.table_storage['account_key']
)

table_service.create_table('atd')
開發者ID:nikolaplejic,項目名稱:atdazure.py,代碼行數:11,代碼來源:azuretable.py

示例13: TableService

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import Context
from azure.storage import TableService      
from django.views.decorators.csrf import csrf_exempt
                  
account_name = 'demostorageabc'
account_key = 'AdIC+CU33zVWVDd8P6TSZgVODG8F5+hkyQuhKtuw9WrhaZqOxWbS8O9oFWcTCkLeu6x6gnjuMPepyENqhrLMOw=='

table_service = TableService(account_name=account_name, account_key=account_key)
table_service.create_table('mytasks')

@csrf_exempt
def list_tasks(request): 
    entities = table_service.query_entities('mytasks', '', 'name,category,date,complete')    
    html = render_to_string('tableservice/task.html', Context({'entities':entities}))
    return HttpResponse(html)

@csrf_exempt
def add_task(request):
    from datetime import date as d
    name = request.POST['name']
    category = request.POST['category']
    date = str(d.today())
    table_service.insert_entity('mytasks', {'PartitionKey':name+category, 'RowKey':date, 'name':name, 'category':category, 'date':date, 'complete':'No'}) 
    entities = table_service.query_entities('mytasks', '', 'name,category,date,complete')
    html = render_to_string('tableservice/task.html', Context({'entities':entities}))
    return HttpResponse(html)

@csrf_exempt
def update_task(request):
開發者ID:Wilo,項目名稱:Charla-Azure-BootCamp-2014,代碼行數:33,代碼來源:views.py

示例14: TableService

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
#coding:utf8

from azure.storage import TableService, Entity 

table_service = TableService(account_name='portalvhdspbrd34f2fnbl',
account_key='y48JkXg+VcHQRCgsylJf4xV4Fd0AuJNkQKSwGhAR+BppHnFhkI+UHPOS/oYaTo0rqFCGQkEBW+thNFZNB9W8yg==')

table_service.create_table('Customer')

table_service.create_table('Order')
開發者ID:freshmenyuan,項目名稱:PointOfSale,代碼行數:12,代碼來源:createTable.py

示例15: Repository

# 需要導入模塊: from azure.storage import TableService [as 別名]
# 或者: from azure.storage.TableService import create_table [as 別名]
class Repository(object):
    """Azure Table Storage repository."""
    def __init__(self, settings):
        """Initializes the repository with the specified settings dict.
        Required settings are:
         - STORAGE_NAME
         - STORAGE_KEY
         - STORAGE_TABLE_POLL
         - STORAGE_TABLE_CHOICE
        """
        self.name = 'Azure Table Storage'
        self.storage_name = settings['STORAGE_NAME']
        self.storage_key = settings['STORAGE_KEY']
        self.poll_table = settings['STORAGE_TABLE_POLL']
        self.choice_table = settings['STORAGE_TABLE_CHOICE']

        self.svc = TableService(self.storage_name, self.storage_key)
        self.svc.create_table(self.poll_table)
        self.svc.create_table(self.choice_table)

    def get_polls(self):
        """Returns all the polls from the repository."""
        poll_entities = self.svc.query_entities(self.poll_table)
        polls = [_poll_from_entity(entity) for entity in poll_entities]
        return polls

    def get_poll(self, poll_key):
        """Returns a poll from the repository."""
        try:
            partition, row = _key_to_partition_and_row(poll_key)
            poll_entity = self.svc.get_entity(self.poll_table, partition, row)
            choice_entities = self.svc.query_entities(
                self.choice_table,
                "PollPartitionKey eq '{0}' and PollRowKey eq '{1}'" \
                    .format(partition, row)
            )

            poll = _poll_from_entity(poll_entity)
            poll.choices = [_choice_from_entity(choice_entity)
                            for choice_entity in choice_entities]
            return poll
        except WindowsAzureMissingResourceError:
            raise PollNotFound()

    def increment_vote(self, poll_key, choice_key):
        """Increment the choice vote count for the specified poll."""
        try:
            partition, row = _key_to_partition_and_row(choice_key)
            entity = self.svc.get_entity(self.choice_table, partition, row)
            entity.Votes += 1
            self.svc.update_entity(self.choice_table, partition, row, entity)
        except WindowsAzureMissingResourceError:
            raise PollNotFound()

    def add_sample_polls(self):
        """Adds a set of polls from data stored in a samples.json file."""
        poll_partition = '2014'
        poll_row = 0
        choice_partition = '2014'
        choice_row = 0

        for sample_poll in _load_samples_json():
            poll_entity = {
                'PartitionKey': poll_partition,
                'RowKey': str(poll_row),
                'Text': sample_poll['text'],
            }
            self.svc.insert_entity(self.poll_table, poll_entity)

            for sample_choice in sample_poll['choices']:
                choice_entity = {
                    'PartitionKey': choice_partition,
                    'RowKey': str(choice_row),
                    'Text': sample_choice,
                    'Votes': 0,
                    'PollPartitionKey': poll_partition,
                    'PollRowKey': str(poll_row),
                }
                self.svc.insert_entity(self.choice_table, choice_entity)
                choice_row += 1

            poll_row += 1
開發者ID:CloudeXpert,項目名稱:PTVS,代碼行數:84,代碼來源:azuretablestorage.py


注:本文中的azure.storage.TableService.create_table方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。