This is the third day of my participation in Gwen Challenge
background
With the cloud service, cloud resources gradually increase. The operation and maintenance of human flesh that needs to be operated in batches through the console is not only inefficient and error-prone, but also cannot be timed.
Tencent Cloud API introduction
At present, many apis of Tencent cloud products have packaged SDK(API 3.0), which provides great convenience and simplicity for calling apis of cloud products, and greatly improves the efficiency of development and operation and maintenance. However, some cloud products do not have a supporting SDK, and such cloud products can only be called by calculating the signature and then concatenating strings.
# Tencent SDK Explorer, packaged SDK and console online call. https://console.cloud.tencent.com/api/explorer # tencent cloud SDK installation, python PIP install tencentcloud - SDK - pythonCopy the code
- An overview of the API
Here are Action, call the API defined operating different Action necessary input parameter of https://cloud.tencent.com/document/api/302/4031Copy the code
- Request structure
Includes: service address, communication protocol, request method, request parameters and character code composition.
- Service address
API supports regional access to the nearest, such as Shanghai regional CVM interface domain address: cvm.ap-shanghai.tencentcloudapi.com, if the call without delay constraint, also don't add address: cvm.tencentcloudapi.com https://cloud.tencent.com/document/api/213/15691Copy the code
- Communication protocol
Most of Tencent cloud API interfaces communicate through HTTPS, providing you with a highly secure communication channel.Copy the code
- Request method
Tencent cloud API supports both POST and GET requestsCopy the code
- Request parameters
Each request of Tencent cloud API needs to specify two types of parameters: public request parameters and interface request parameters.Copy the code
- A character encoding
Tencent cloud API requests and returned results are encoded using UTF-8 character setCopy the code
- Common request parameters
Action: interface name of the operation Region: Region parameter, which identifies the Region instance that you want to operate on. Timestamp: current UNIX Timestamp, which records the time when an API request was made. Nonce: a user can define a random positive integer, which is combined with Timestamp to prevent replay attacks. SecretId: identifies the SecretId requested on the cloud API key. A SecretId corresponds to a unique SecretKey, which will be used to generate the request Signature Signature. Signature: indicates the request Signature, which is used to verify the validity of the request. The value can be calculated based on actual input parameters. # optional parameter SignatureMethod: indicates the SignatureMethod. Currently, HmacSHA256 and HmacSHA1 are supported. The HmacSHA256 algorithm is used to verify signatures only when HmacSHA256 is specified. In other cases, HmacSHA1 is used to verify signatures. Token: Indicates the Token used by the temporary certificate. It must be used together with the temporary key. Long-term keys do not require a Token.Copy the code
- Interface request parameters
Interface request parameters are specific to the interface. Different interfaces support different interface request parameters. Interface request parameters are all lowercase to distinguish them from public request parameters.Copy the code
- Final request form
The concatenation rule for the URL request of Tencent cloud API interface is https:// + request domain name + request path +? (Description in Tencent Cloud CVM) (description in Tencent Cloud CVM) (description in Tencent Cloud CVM) Cvm.api.qcloud.com. For details about the requested domain name, see the description of each interface. Request path: The request path of Tencent cloud API corresponds to the product. Generally, one product corresponds to a fixed path (for example, Tencent Cloud CVM request path is fixed as /v2/index.php). # Final request parameter string: The interface request parameter string includes the common request parameter and the interface request parameter.Copy the code
API request signature
Tencent cloud API will authenticate each access request, that is, each request needs to include Signature information in the common request parameters to verify the user's identity. The signature information is generated by the user's security certificate.Copy the code
Generating a signature string Once you have the security credentials SecretId and SecretKey, you can generate a signature string. The detailed process of generating signature string is as follows:
- Sort parameters
First, all request parameters are sorted lexicographically in ascending order by parameter name. (Lexicographical ascending arrangement is intuitively the same as arranging words in a dictionary, in alphabetical or ascending order in a list of numbers, with the first "letter" considered first, the second "letter" in the same case, and so on.)Copy the code
- Concatenate request string
This step generates the request string. For example, for Action parameters, their name is "Action" and their value is "DescribeInstances", so formatted for Action=DescribeInstances. Then the formatted parameters are concatenated with ampersand (&).Copy the code
- Concatenate the original signature string
This step generates the signature text string. The combination rule of the original signature string is: request method + request host + request path +? Request method: Support POST and GET methods, here use GET request, note that the method is all uppercase. Request host: the host domain name. The request domain name is determined by the product or module of the product to which the interface belongs. The request domain name may be different for different products or modules of different products. For example, the required domain name of the Tencent Cloud CVM (DescribeInstances) is cVM.api.qcloud.com. # Request path: The request path of Tencent cloud API corresponds to the product. Generally, one product corresponds to a fixed path. For example, Tencent Cloud CVM request path is fixed as /v2/index.php. # Request string: The request string generated in the previous step.Copy the code
- Generate signature string
There are two methods for calculating a signature: HmacSHA256 and HmacSHA1 In this step, a signature string is generated based on the signature algorithm (SignatureMethod parameter) that you specify. If SignatureMethod is set to HmacSHA256, HmacSHA256 is used to calculate signatures. In other cases, HmacSHA1 is used to calculate signatures.Copy the code
- Signature string encoding
The generated signature string cannot be directly used as the request parameter. It needs to be URL encoded.Copy the code
Code demo
Import base64,hashlib, HMAC Import Time,random Import requests # API key ID = 'AKIDENN***********4U6' key = 'e6Rac********Jt1' # define the data dictionary according to the request public parameter data = {# Action define the operation (see the API overview), this example uses the cloud resolution 'Action': 'RecordList', 'Region': 'ap-shanghai', 'Nonce': random.randint(10000, 99999), 'SecretId': id, 'Timestamp': int(time.time()), 'domain': 'key1024. Cn'} # request url = 'cns.api.qcloud.com/v2/index.php' interface address # for all request parameters sorting signature_old = 'for I sorted in (data) : Signature_old = signature_old + I + "=" + STR (data[I]) + "&" [:-1] Hmac_str = hmac.new(key.encode('utf-8'), query.encode(' utF-8 '), Hashlib.sha1).digest() signature = base64.b64encode(hmac_str) # print(signature) = signature resp = requests.get('https://' + url ,params=data) print(resp.content.decode('utf-8'))Copy the code