
# Python签名指导
本节以IntelliJ IDEA版本为例，介绍如何在Python环境中集成API请求签名的SDK。您可以直接导入示例工程体验，然后参考调用说明部分将签名SDK集成到您的应用中。
![](https://support.huaweicloud.com/devg-apisign/public_sys-resources/note_3.0-zh-cn.png)
签名SDK只包含签名功能，不包含云服务的SDK功能，云服务SDK请参见[SDK](https://support.huaweicloud.com/devg-sdk/zh-cn_topic_0070637169.html)。
#### 准备环境
- 获取并安装IntelliJ IDEA 2018.3.5或以上版本，可至[IntelliJ IDEA官方网站](https://www.jetbrains.com/idea/)下载。
- 获取并安装Python安装包（可使用2.7.9+或3.X，包含2.7.9），可至[Python官方下载页面](https://www.python.org/downloads/)下载。
  Python安装完成后，在命令行中使用pip安装"requests"库。
  ```
  pip install requests
  ```
  ![](https://support.huaweicloud.com/devg-apisign/public_sys-resources/note_3.0-zh-cn.png)
  如果pip安装requests遇到证书错误，请下载并使用Python执行[此文件](https://bootstrap.pypa.io/get-pip.py)，升级pip，然后再执行以上命令安装。
  
- 在IDEA中安装Python插件，如下图所示。 ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0160883582.png "点击放大")
  
 
#### 获取SDK
[点此下载SDK与Demo](https://obs.cn-north-1.myhuaweicloud.com/apig-sdk/ApiGateway-python-sdk.zip)。
解压后目录结构如下：
| 名称                         | 说明            |
|:---|:---|
| apig_sdk\\__init__.py      | SDK代码         |
| apig_sdk\\signer.py        | SDK代码         |
| main.py                    | 示例代码          |
| licenses\\license-requests | 第三方库license文件 |
   
#### 示例工程导入
1. 打开IDEA，选择菜单"File \> New \> Project"。 
   弹出"New Project"对话框，选择"Python"，单击"Next"。
   ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0160895290.png "点击放大")
   
   
2. 再次单击"Next"，弹出以下对话框。单击"..."，在弹出的对话框中选择解压后的SDK路径，单击"Finish"。 
   ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0160897494.png "点击放大")
   
   
3. 完成工程创建后，目录结构如下。 
   ![](https://support.huaweicloud.com/devg-apisign/zh-cn_image_0160894808.png)
   
   
 
#### 请求签名与API调用
示例代码修改调用信息后可直接调用，调用信息请参考[API签名准备工作](https://support.huaweicloud.com/devg-apisign/api-sign-provide.html)章节获取。
1. 在命令行中，使用pip安装"requests"库。 
   ```
   pip install requests
   ```
   
   
2. 在工程中引入apig_sdk。 
   ```
   from apig_sdk import signer
   import requests
   ```
   
   
3. 生成一个新的Signer，填入AK和SK。 
   1. 本示例以AK和SK保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。以Linux系统为例在本地将已[获取的AK/SK](https://support.huaweicloud.com/devg-apisign/api-sign-provide-aksk.html)设置为环境变量。
      1. 打开终端，输入以下命令打开环境变量配置文件。 **vi \~/.bashrc**
         
      
      2. 设置环境变量，保存文件并退出编辑器。
         ```
         export HUAWEICLOUD_SDK_AK="已获取AK值" 
         export HUAWEICLOUD_SDK_SK="已获取SK值"
         ```
         
      
      3. 输入以下命令使配置文件生效。 **source \~/.bashrc**
         
       
   
   2. 生成一个新的Signer，填入已设置的环境变量。
      ```
      sig = signer.Signer()
      # Set the AK/SK to sign and authenticate the request.
      # Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables.
      # In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
      sig.Key = os.getenv('HUAWEICLOUD_SDK_AK')
      sig.Secret = os.getenv('HUAWEICLOUD_SDK_SK')
      ```
      
   
   
   
   
4. 生成一个新的Request，指定域名、方法名、请求uri和body。 
   以虚拟私有云服务的**查询VPC列表** 接口为例，HTTP方法为**GET** ，域名（Endpoint）为**service.region.example.com** ，请求URI：**/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs，** Query参数：**limit=1** 。
   ```
   # The following example shows how to set the request URL and parameters to query a VPC list.
   r = signer.HttpRequest("GET", "https://service.region.example.com/v1/77b6a44cba5143ab91d13ab9a8ff44fd/vpcs?limit=1")
   # r.body = "{\"a\":1}"
   ```
   
   
5. 添加需要签名的请求消息头，或者其他用途的头域，如[多项目](https://support.huaweicloud.com/devg-apisign/api-sign-provide-start.html)场景中添加X-Project-Id，或者[全局服务](https://support.huaweicloud.com/devg-apisign/api-sign-provide-start.html)场景中添加X-Domain-Id。如果添加多个请求消息头，使用英文逗号分隔。
   
   ```
   r.headers = {"X-Project-Id": "xxx"}
   r.headers = {"X-Domain-Id": "xxx"}
   ```
   
   
6. 进行签名，执行此函数会在请求参数中添加用于签名的X-Sdk-Date头和Authorization头。 
   ```
   sig.Sign(r)
   ```
   - X-Sdk-Date是必须参与签名的时间戳请求头参数。
   
   - Authorization头是接口中用于安全认证的必要请求头参数。
   
   - 您无需关注哪些消息头参数参与了签名，由SDK自行完成。
    
   
   
7. 访问API，查看访问结果。 
   ```
   resp = requests.request(r.method, r.scheme + "://" + r.host + r.uri, headers=r.headers, data=r.body)
   print(resp.status_code, resp.reason)
   print(resp.content)
   ```
   以上面的**查询VPC列表**接口为例，访问结果如下：
   ```
   {
       "vpcs": [
           {
               "id": "13551d6b-755d-4757-b956-536f674975c0",
               "name": "default",
               "description": "test",
               "cidr": "172.16.0.0/16",
               "status": "OK",
               "enterprise_project_id": "0",
               "routes": [],
               "block_service_endpoint_states": "off",
               "enable_network_address_usage_metrics": false,
               "tenant_id": "087679f0aa80d32a2f4ec0172f5e902b",
               "created_at": "2022-12-15T02:11:13",
               "updated_at": "2022-12-15T02:11:13"
           }
       ]
   }
   ```
   
   
 
