This topic provides answers to some frequently asked questions about Alibaba Cloud DSK for Python. This topic aims to help you improve your development efficiency.
Prerequisites
Python 3.7 or later is installed.
Alibaba Cloud APIs are accessible from your network.
Overview
Problems and solutions
How do I handle AccessKey errors?
Problem: The following error message is returned after running code. The error message indicates that the AccessKey pair is not correctly configured.
Alibaba Cloud SDK V2.0: AttributeError: 'NoneType' object has no attribute 'get_access_key_id'.
Alibaba Cloud SDK V1.0: Error:MissingParameter The input parameter "AccessKeyId" that is mandatory for processing this request is not supplied.
Solutions:
Run the following commands to check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%If a valid AccessKey pair is returned, the environment variables are properly configured. If no AccessKey pair or an invalid AccessKey pair is returned, configure the environment variables as required. For more information, see Configure environment variables in Linux, macOS, and Windows.
Check for errors related to the AccessKey pair in the code.
Sample error request:
config = open_api_models.Config( access_key_id=os.environ['yourAccessKeyID'], access_key_secret=os.environ['yourAccessKeySecret'] )Sample success request:
config = open_api_models.Config( access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] )Noteos.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] and os.environ("ALIBABA_CLOUD_ACCESS_KEY_SECRET") specify that the AccessKey ID and AccessKey secret are obtained from the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
ImportantTo prevent security risks, do not write the AccessKey pair in the online code.
What do I do if an SDK fails to be installed?
Make sure that a valid Python version is installed, such as Python 3.x.
Add the
--upgradeoption when you install the SDK by running a pip command. This makes sure that the latest version is installed.
pip install --upgrade <SDK_NAME> If you encounter permission issues during the installation process, such as when you install the SDK in the system directory of Python libraries, you can use the
--useroption to install the SDK in the user directory instead of the system directory.
pip install --user <SDK_NAME> If multiple versions of Python are installed on your PC, make sure that you install an SDK in the Python version that you use. For example, use
python3instead ofpythonin the code and runpip3commands.
What do I do if a module fails to be imported and the ModuleNotFoundError error is reported?
Make sure that an SDK is properly installed. Then, try to import a module in the Python environment.
Start the Python interpreter.
pythonImport a module.
import <SDK_NAME> If no error occurs, the SDK is properly installed. If the ModuleNotFoundError or ImportError error occurs, the SDK is not properly installed.
pip install <SDK_NAME>What do I do if the "AttributeError: 'CredentialModel' object has no attribute 'provider_name'" error message is returned?
This error message indicates an attempt to access the provider_name attribute of the CredentialModel object, but the provider_name attribute does not exist. In most cases, this error is caused by an outdated alibabacloud_credentials package, which results in incompatibility between the class library and the compilation API operations. Possible causes:
Outdated dependency package: The version of the
alibabacloud_credentialspackage is earlier than the version required by theprovider_nameattribute in the code.Dependency conflicts: The incorrect
alibabacloud_credentialsversion is loaded because multiple alibabacloud_credentials packages exist in the project.Incorrect dependency upgrade: After an upgrade, the dependency is not re-installed or the cache is not cleared. As a result, the previous dependency version is still in use.
Solutions:
In the
requirements.txtfile, set the alibabacloud_credentials dependency package to the latest version. Example:alibabacloud_credentials=1.0.1Run the
pip install -r requirements.txt --upgradecommand to upgrade the dependency package.NoteFor more information about all released versions of alibabacloud_credentials, see ChangeLog.txt.
Check for dependency conflicts.
pip list | grep alibabacloud # If multiple dependency versions exist, uninstall the existing versions and install the latest version. Example: pip uninstall alibabacloud_credentials pip install alibabacloud_credentials==1.0.1Clear the cache and the re-install the latest version.
pip cache purge pip install -r requirements.txt --force-reinstall
What do I do if the following error message is returned: code: 400, The input parameter"AccesskeyId" that is mandatory for processing this request is not supplied?
The error message is returned because a request sent to the gateway does not contain an AccessKey ID.
Check whether your AccessKey ID is properly configured when you use the complete sample code downloaded from OpenAPI Explorer. Configure your AccessKey ID and AccessKey secret when you call the main method.

What do I do if the following error message is returned: Tea.exceptions.TeaException: Error: SignatureDoesNotMatch.MissingHeader code: 400, The specified signed header "accept;connection;content-type;host;user-agent;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version" is not found?
The error message is returned because the Connection header is set to close to implement short-lived connections when you call a service in self-signed mode. However, the signature method V3 is incompatible with this setting, which results in an error.
You can fix this error by using the following setting: config.signature_algorithm = 'v2'.
What do I do if the following error message is returned: Tea.exceptions.TeaException: Connection aborted?
The error message is returned because the request interval is longer than expected. The server keeps a persistent connection only for 30 seconds, whereas the client keeps the connection persistently. In this case, the server closes the connection after 30 seconds. If the client initiates a request after 30 seconds, a request failure occurs.
Set the Connection header to close to implement short-lived connections.
Configure a retry mechanism to ensure that a call is initiated within 30 seconds.
A retry mechanism may cause multiple operations if a request is sent and processed multiple times. Therefore, we recommend that you configure a retry mechanism for requests that are initiated to perform query operations, but not for requests that are initiated to perform create, delete, or modify operations.
What do I do if an API call timed out and the "requests.exceptions.Timeout" or "requests.exceptions.ConnectionError" error message is returned?
An API call timeout may be caused by multiple factors. The following section describes the common causes and the corresponding solutions.
Network connection issues
Cause: The request cannot reach the server because the network connection between the client and server fails or the network is unstable.
Solutions:
Run the ping or curl command to test the connectivity between the on-premises host and the endpoint of the cloud service. For example, run the ping dysmsapi.aliyuncs.com or curl -v https://dysmsapi.aliyuncs.com command to test the connectivity between your on-premises host and the endpoint of the Short Message Service (SMS) API.
If the command times out or does not receive a response, check for blocking policies on your on-premises firewall or routers.
If a response is returned, we recommend that you specify a proper timeout period to prevent request failures caused by improper timeout configurations. For more information, see Configure a timeout period. Sample code:
# The timeout period takes effect only for requests that use RuntimeOptions. runtimeOptions = RuntimeOptions( connect_timeout=5000 # Configure the timeout period for connection requests. Unit: milliseconds. )
Cause 2: Extended period of time for processing the request
Cause: The time for processing the API request exceeds the specified read timeout period.
Solution: Extend the timeout period for the API response. For more information, see Configure a timeout period. For example, you can configure the read timeout parameter to extend the read timeout period. Sample code:
# The timeout period takes effect only for requests that use RuntimeOptions.
runtimeOptions = RuntimeOptions(
read_timeout=10000, # Configure the timeout period for read requests. Unit: milliseconds.
)What do I do if the "-bash: python3: command not found" error message is returned in Linux?
If you have installed Python, this error message may be returned because symbolic links are not properly configured.
When a user accesses a symbolic link, the user actually accesses the file to which the symbolic link points. For example, when you use Python 3, you actually use the Python 3.12 interpreter.
Run the
which python3 pip3command to check whether symbolic links exist in the system. If symbolic links exist, delete the symbolic links.
rm -rf /usr/bin/python3 /usr/bin/pip3Create symbolic links again. Find the installation directory of Python, access the bin directory, and then find pip3.12 and python3.12. Run the following commands to create symbolic links:
sudo ln -s /usr/local/python3/bin/python3.12 /usr/bin/python3
sudo ln -s /usr/local/python3/bin/pip3.12 /usr/bin/pip3What do I do if the "Invalid parameters" or "MissingRequiredParameter" error is reported when I call an API operation?
In this example, the SendSms operation of Short Message Service (SMS) is used.
Log on to OpenAPI Explorer. Go to the API debugging page of the Alibaba Cloud service that you want to call. Find the API operation that you want to call.
Check whether all required parameters such as PhoneNumbers and SignName are specified in the constructed request object. In this example, the
SendSmsRequestobject is used.Verify that all the required parameters are specified based on the API reference.
Make sure that the values of the required parameters are valid. For example, check whether mobile numbers are specified in valid formats.
Before the SDK sends an API request, the SDK automatically verifies the parameters. If one or more required parameters are not specified, an error such as
MissingRequiredParameteris reported. For example, if the PhoneNumbers parameter is not specified, the "MissingPhoneNumbers: code: 400" error is reported. In this case, specify the parameter based on the error message.

send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
# The mobile numbers to which you want to send a text message.
phone_numbers='<YOUR_VALUE>',
# The name of the SMS signature.
sign_name='<YOUR_VALUE>',
# The code of the SMS template.
template_code='<YOUR_VALUE>',
# The variables of the SMS template. Specify the value in the JSON format. Example: {"code":"1234","name":"1234","time":"1234"}.
template_param='{"code":"1234","name":"1234","time":"1234"}'
)What do I do if an API operation fails to be called and the "Tea.exceptions.UnretryableException" error is reported?
Check whether the region that you specify supports the service that you want to call. In this example, SMS is used. You can go to the homepage of SMS in OpenAPI Explorer and view the endpoints of SMS in various regions. Make sure that you specify a valid endpoint.

What do I do if the following error message is returned: File "/usr/local/python3/lib/python3.6/site-packages/alibabacloud_slb20140515/client.py", line 4, in <module> from Tea.core import TeaCore ModuleNotFoundError: No module named 'Tea'?
The error message is returned because the pip version is outdated. In this case, the installed dependencies are incomplete or specific dependencies are deleted. You can update pip and run the pip install <Installation package> command to fix this error. For example, run the pip install alibabacloud-tea command to install the Tea module.
When this error occurs, the system may run the pip install tea command to install an irrelevant package. You can check the organization or individual that releases the package in the Python Package Index (PyPI) repository and consider whether to delete the package.
Question 13: What do I do if the following error message is returned: Command "python setup.py egg_info" failed with error code 1 in xxx?
The error message is returned because the Python or pip version is outdated, or the required libraries or packages are not installed. As a result, the SDK cannot work as expected.
Solution
Check the current Python version.
Run the
python -Vorpython3 -Vcommand to check the current Python version. If the Python version is earlier than 3.7, perform the following steps to update Python. You can go to the Python official website to obtain the download URL of the latest Python version and installation instructions.If the Python version is 3.7 or later, the possible cause is that the
pipversion is outdated. Run thepip3 install --upgrade pip setuptoolscommand to update pip to the latest version. Then, try to run the Python code again.Check and install the required libraries.
If the Python version is 3.7 or later and the issue persists after
pipis updated, the possible cause is that related libraries are not installed. In some cases, if the specified libraries are not installed, other libraries fail to be installed. For example, if you want to installnumpy, you must install related math libraries such asblasandlapack. If you want to installlxml, you must installlibxml2-devandlibxslt1-dev.Run the following commands to install regular libraries. In this example,
lxmlandnumpyare used.sudo yum install libxml2-dev libxslt1-dev -y sudo yum install blas-devel lapack-devel -yNotePython packages are modules or libraries that are designed to enhance and extend Python. Python packages provide additional tools and methods to help developers complete specific tasks in a convenient and efficient manner. The packages that are required are determined by the requirements of the specified project that you are developing.
Question 14: What do I do if the "HTTPSConnectionPool(host='ocr-api.cn-hangzhou.aliyuncs.com', port=443): Max retries exceeded with url: /?Country=Vietnam (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:2418)')))" error message is returned?
In most cases, this error is caused by SSL/TLS handshake failures. Possible causes:
The SSL/TLS versions used by the server and the client are incompatible.
The SSL certificate on the on-premises device contains errors. For example, the SSL certificate has expired or the certificate chain is incomplete.
SSL handshakes fail due to network configuration errors.
Solutions:
Check the SSL/TLS versions: Make sure that the Python environment on the on-premises device supports the SSL/TLS version that the server uses for communication. In some cases, the server supports only TLS 1.2.
import ssl import urllib3 # Create an SSL context and use TLS 1.2. ssl_context = ssl.create_urllib3_context(ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv3, ssl.OP_NO_TLSv1, ssl.OP_NO_TLSv1_1) # Initialize the urllib3 pool manager. http = urllib3.PoolManager(context=ssl_context) # Send the request. response = http.request('GET', 'https://ocr-api.cn-hangzhou.aliyuncs.com/?Country=Vietnam')Check for
Pythonenvironment issues:Make sure that the
sslmodule and the version of theurllib3library are compatible with the Python version.Use a virtual environment to re-install Python and Python dependencies:
python -m venv myenv source myenv/bin/activate pip install requests urllib3 pyOpenSSLCheck for network configuration errors.
Make sure that the firewall on the on-premises device allows traffic to the HTTPS port (port 443).
If a proxy is used, make sure that the proxy configurations are correct.
import requests # Use a proxy. proxies = { 'http': 'http://your-proxy-server:port', 'https': 'https://your-proxy-server:port' } response = requests.get( 'https://ocr-api.cn-hangzhou.aliyuncs.com/?Country=Vietnam', proxies=proxies )Update the
requestsandurllib3libraries to solve the issue.pip install --upgrade requests urllib3If the issue persists after the update, the issue may be caused by the environment certificate. Configure the following parameters to ignore the certificate and adjust the timeout period:
# Disable certificate verification. runtimeOptions = RuntimeOptions( ignore_ssl=True # Disable SSL certificate verification. By default, SSL certificate verification is enabled. ) # Adjust the timeout period. runtimeOptions = RuntimeOptions( read_timeout=xxx, # The timeout period for read requests. Unit: milliseconds. connect_timeout=xxx # The timeout period for connection requests. Unit: milliseconds. )If the issue persists after SSL certificate verification is disabled, set the
PYTHONHTTPSVERIFYenvironment variable to0to disable SSL certificate verification.export PYTHONHTTPSVERIFY=0 # Disable HTTPS verification.Check the SSL certificate on the on-premises machine: Make sure that the SSL certificate on the on-premises machine is up to date and complete. You can use a tool, such as
certbot, to update and install certificates.sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --email yo**@email.com
Basic errors of Python
Error message | Cause | Solution |
SyntaxError | The code contains a syntax error, such as a spelling error, a missing colon, or unpaired parentheses. | Check the code and make sure that the syntax is valid. Use the syntax highlighting feature of an integrated development environment (IDE) or an editor to help you find syntax errors. |
NameError | The variable or function to be used is undefined. | Make sure that the name of the variable or function is valid and the variable or function has been properly defined or imported in the code. |
TypeError | The operation or function is incompatible with the type of the object to be applied. | Check the data types in the code and make sure that the operation or function is applicable to the type of the object to be applied. You can also use type conversion functions to resolve the type mismatch issue. |
IndexError | The specified index does not exist in the list, tuple, or string. | Make sure that the index is within the valid range of the object. You can use conditional statements or exception handling to check the validity of an index, or use built-in index checking functions such as len(). |
ValueError | A parameter value in the function is invalid. | Make sure that the parameter values specified in the function meet relevant requirements. You can use conditional statements or exception handling to verify the validity of parameter values. |
FileNotFoundError | The file to be opened or accessed does not exist. | Make sure that the specified file path is valid and check whether the file exists. You can use conditional statements or exception handling to handle the issue that a file does not exist. |
ZeroDivisionError | The divisor is zero. | Before you perform a division operation, make sure that the divisor is not zero. You can use conditional statements or exception handling to check the value of the divisor and make sure that the divisor is not zero. |
FloatingPointError | A floating-point number calculation leads to an infinity or not a number (NaN) result. | Make sure that the values involved in the floating-point number calculation are within the valid range. You can use value checking functions to verify the validity of the values and take appropriate measures if exceptions occur. |
OverflowError | A numerical calculation leads to a result that is beyond the value range of the current data type. | Check the data type used in the numerical calculation and make sure that the data type can represent the value range of the calculation result. If you need to handle large numerical values, you can use appropriate data types or third-party libraries. |
BufferError | The data to be read or written exceeds the size of the buffer. The buffer to be accessed does not exist. The operation on the buffer results in an out-of-memory or out-of-bounds error. | Check the size of the buffer and make sure that the amount of data to be read or written does not exceed the size of the buffer. You can use conditional statements or exception handling to verify the amount of data and take appropriate measures if the data exceeds the size of the buffer. |
EOFError | An empty file or the end of a file is read. | Check the content of the file and make sure that data can be read from the file. If the file is empty or the end of the file is read, an EOFError exception is thrown. You can use conditional statements or exception handling to check the content of a file and take appropriate measures if the file is empty or the end of the file is read. |
SDK errors of Python
Error message | Cause | Solution |
aliyunsdkcore.acs_exception.exceptions.ClientException: SDK.InvalidParameter The parameter region_id not match with ^[a-zA-Z0-9_-]+$ | The format of the region_id parameter for client initialization is invalid. | Enter a string in the cn-<Region> format. |
SDK.InvalidRegionId | The core package of an earlier version fails to identify the endpoint. | Update the aliyun-python-sdk-core package to the latest version and specify a valid region ID. |
SDK.ServerUnreachable | A network error occurred. | In the latest SDK version, this error is replaced by a specific error, such as SDK.HttpError. Update the aliyun-python-sdk-core package to the latest version. |
SDK.MissingEndpointsFiler | No endpoint filter is configured. | Configure an endpoint filter and make sure that it can work properly. |
SDK.UnknownServerError | An unknown server error occurred. | Send the request again. |
SDK.InvalidSessionExpiration | The session expiration time is invalid. | Check the session expiration time and make sure that it is valid. If a session expires, you must update the session or obtain a session credential again. |
SDK.NotSupport | The feature is not supported. | Make sure that the SDK version that you use supports the required features. |
SDK.EndpointResolvingError | An error occurred while resolving the endpoint. | Check the endpoint resolution logic and make sure that valid endpoints can be correctly resolved and obtained. |
SDK.InvalidServerResponse | The response returned by the server is invalid. | Check the content of the response returned by the server and make sure that the response meets the requirements of Alibaba Cloud services. You can view the content of the response to obtain more information and adjust the content based on your business requirements. |
RequiredArgumentException | One or more required parameters are not specified. | Check the required parameters and make sure that their values are valid. |
UnretryableException | A network error occurred. | 1. Check whether the specified endpoint is valid. 2. Run the ping or curl command to check the network connectivity. |
Technical support
The solutions to the preceding issues can help you better use Alibaba Cloud SDKs. If you encounter other issues when you use Alibaba Cloud SDKs, contact Alibaba Cloud technical support by using the following method: