5.3. Accessing the Database from the Python Code

Within your UPF routine, you may need to access the Mechanical APDL database in read/write mode.

In the Python code, you can create a connection with the DB server. This command must be called only once, so you can protect the call based on the value of a static variable:

import grpc
import sys
from mapdl import *

firstcall = 1

class MapdlUserService(MapdlUser_pb2_grpc.MapdlUserServiceServicer):
    

#   ###############################################################
    def UserMat( self, request, context):
        
        global firstcall
        
        if firstcall == 1:
            print( ">> Connection to the MAPDL DB Server\n")
            db.start()
            firstcall = 0

        # continuation of the python function
        # …

Once the DB connection has been initialized, you can access the database of the Mechanical APDL instance in read/write mode.

A subset of the functions documented in Accessing the Mechanical APDL Database have been exposed and can be called from the Python code. Below is a list of those functions:

Supported Database Access Functions
db.start() Initializes the connection with a running Mechanical APDL instance. The DB Server is automatically started in Mechanical APDL if a /UPF command with a python file has been detected.
db.stop() Closes the connection with the DB Server.
db.ndnext(next) Equivalent to the function described in Function ndnext (Getting the Next Node Number)
db.ndinqr(ind, key) Equivalent to the function described in Function ndinqr (Getting Information About a Node)
db.getnod(inod) Equivalent to the function described in Function getnod (Getting a Nodal Point)
db.putnod(inod, x, y, z) Equivalent to the function described in Function putnod (Storing a Node)
db.elnext(ielm) Equivalent to the function described in Function elnext (Getting the Number of the Next Element)
db.getelem(ielm) Equivalent to the function described in Function elmget (Getting an Element's Attributes and Nodes)
db.get_ElmInfo(inquire) Equivalent to the function get_ElmInfo described in Accessing Solution and Material Data
db.get_ElmData(kchar, elemId, kMatRecPt, ncomp, vect) Equivalent to the function get_ElmData described in Accessing Solution and Material Data
db.putElmData(inquire, elemId, kIntg, nvect, vect) Equivalent to the function put_ElmData described in Accessing Solution and Material Data