View the .ipynb file.

Unicode support in Python 2.7 and 3.4 or later

This example demonstrates Unicode support when using strings in Python 2.7 and 3.4 or later.

Prerequisites

Import required Python packages, and declare the source file as being encoded in UTF-8. This declaration is necessary if you wish to paste symbols from other locations into string literals. The declaration is not necessary if you use any of the supported escape sequences (see below).

[1]:
# -*- coding: utf-8 -*-
import datetime
import GRANTA_MIScriptingToolkit as gdl

Define 4 helper functions to simplify the code. The functions will:

  1. Format the current time (used to set the record name)

  2. Perform a record name search

  3. Perform a data export

  4. Perform a data import

[2]:
# Function 1
def NowString():
    return datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")

# Function 2
def FindRecord(gdlSession, dbKey, tableName, recordName):
    """
    Finds a record by name
    :returns: :py:mod:`SearchResult <GRANTA_MIScriptingToolkit.SearchResult>`
    """
    req = gdl.RecordNameSearchRequest(caseSensitiveNames=False, recordName=recordName, populateGUIDs=True, searchShortNames=True, searchFullNames=True)
    req.table = gdl.TableReference(DBKey=dbKey, name=tableName)
    resp = gdlSession.searchService.RecordNameSearch(req)
    return resp.searchResults[0]

# Function 3
def GetRecordData(session, recordRef, attribs):
    """
    A wrapper for a data Export
    Return a dictionary of record attributes (retrieved from an export), ie, name -> AttributeValue
    """
    exp = session.dataExportService
    req = gdl.GetRecordAttributesByRefRequest()
    req.recordReferences = [recordRef]
    req.attributeReferences = attribs
    resp = exp.GetRecordAttributesByRef(req)
    data = resp.recordData[0]
    return {av.attributeName : av for av in data.attributeValues}

# Function 4
def DoImport(session, recordName, parentRecord, importAttributeValues):
    """
    A wrapper for a data import
    """
    newRecordData = gdl.ImportRecord(recordName=recordName,
                                     existingRecord=parentRecord,
                                     importAttributeValues=importAttributeValues)

    request = gdl.SetRecordAttributesRequest(importRecords=[newRecordData])
    response = session.dataImportService.SetRecordAttributes(request)
    return response.recordsImported[0]

Create a Granta MI session

Import the GRANTA_MIScriptingToolkit package, and create a connection to a Granta MI server.

[3]:
session = gdl.GRANTA_MISession('http://localhost/mi_servicelayer', autoLogon=True)

print("Session created")
Session created

Use data import operations to view Unicode support

There are several ways of writing strings that contain special characters (e.g. symbols, accented letters) in Python, using either Unicode strings or byte strings. Here is a list demonstrating some common syntaxes for doing so:

[4]:
vals = [u'🍌 it is a banana!',                          # Unicode literal (requires UTF-8 source declaration)
        u'\U0001F34C it is a banana!',                 # Unicode codepoint escape sequence
        u'\U0001F34C it is a banana!'.encode("utf-8"), # UTF-8 binary data from Python's "encode" function
        b'\xF0\x9F\x8D\x8C it is a banana!'            # UTF-8 binary data manually typed by an experienced user
    ]

Specify a folder to import new records under.

[5]:
dbkey = "MI_Training"
tableName = "Training Exercise for Import"
target = FindRecord(session, dbkey, tableName, "Metal").recordReference

Import 4 new records into the database. Each of the records you import will contain the same data, even though the input data is written with a different syntax. You can check that the data is identical by viewing the records in MI Viewer, or by exporting the data from the database and checking it using Python.

[6]:
for index, stval in enumerate(vals):
    value = gdl.ShortTextDataType(value=stval)
    attributeRef = gdl.AttributeReference(name="Composition", partialTableReference=gdl.PartialTableReference(tableName=tableName), DBKey=dbkey)
    attribute = gdl.ImportAttributeValue(shortTextDataValue=value, attributeReference=attributeRef)

    importedRecord = DoImport(session, "UnicodeDemo[{0}]-{1}".format(NowString(), index), target, [attribute])

    importedRef = importedRecord.recordReference
    print("New record imported: {0}. You can inspect this record in MI Viewer.".format(importedRecord.shortName))

    data = GetRecordData(session, importedRef, [attributeRef])
    check = (u'🍌 it is a banana!' == data["Composition"].shortTextDataType.value)
    print("Success: {0}".format(check))
New record imported: UnicodeDemo[23/03/2021 16:56:44]-0. You can inspect this record in MI Viewer.
Success: True
New record imported: UnicodeDemo[23/03/2021 16:56:44]-1. You can inspect this record in MI Viewer.
Success: True
New record imported: UnicodeDemo[23/03/2021 16:56:44]-2. You can inspect this record in MI Viewer.
Success: True
New record imported: UnicodeDemo[23/03/2021 16:56:44]-3. You can inspect this record in MI Viewer.
Success: True
[ ]: