Coder Social home page Coder Social logo

aliyunsdkcore's Introduction

阿里云python sdk文档地址

阿里云python sdk最新文档地址

阿里将sdk接入分为特化调用和泛化调用,特化调用安装地址为:

pip install alibabacloud_dysmsapi20170525==2.0.24,

泛化地址为:

pip install alibabacloud-tea-openapi


Deprecated

目前阿里云好像官方出了aliyun-python-sdk-core-v3的Python3的支持包,地址是https://pypi.org/project/aliyun-python-sdk-core-v3/,经过测试可以正常发送短信,所以推荐大家安装这个新的包。官方文档

安装方式

pip install aliyun-python-sdk-core-v3

官方文档中的发送例子 demo_sms_send.py

# -*- coding: utf-8 -*-
import sys
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequest
from aliyunsdkcore.client import AcsClient
import uuid
from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.http import method_type as MT
from aliyunsdkcore.http import format_type as FT

"""
短信业务调用接口示例,版本号:v20170525

Created on 2017-06-12

"""
try:
    reload(sys)
    sys.setdefaultencoding('utf8')
except NameError:
    pass
except Exception as err:
    raise err

# 注意:不要更改
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"

# ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
ACCESS_KEY_ID = "yourAccessKeyId"
ACCESS_KEY_SECRET = "yourAccessKeySecret"

acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)
region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)

def send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)

    # 短信模板变量参数
    if template_param is not None:
        smsRequest.set_TemplateParam(template_param)

    # 设置业务请求流水号,必填。
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(sign_name)
	
    # 数据提交方式
	# smsRequest.set_method(MT.POST)
	
	# 数据提交格式
    # smsRequest.set_accept_format(FT.JSON)
	
    # 短信发送的号码列表,必填。
    smsRequest.set_PhoneNumbers(phone_numbers)

    # 调用短信发送接口,返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    # TODO 业务处理

    return smsResponse


if __name__ == '__main__':
    __business_id = uuid.uuid1()
    #print(__business_id)
    params = "{\"code\":\"12345\",\"product\":\"云通信\"}"
	#params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'
    print(send_sms(__business_id, "13000000000", "云通信测试", "SMS_5250008", params))

文档中将ACCESS_KEY_ID和ACCESS_KEY_SECRET放在了const.py的文件中,此处直接放在了测试代码里。


Deprecated

aliyunsdkcore

阿里短信Python3 API,基于阿里官网 Python2 API的翻版, 主要修改为Python2转Python3时不兼容包的替换。

Requirements

  • Python (3.3, 3.4, 3.5, 3.6)

Installation

$ pip install aliyunsdkcore

Sample

import sys
from aliyunsdkcore import SendSmsRequest, QuerySendDetailsRequest
from aliyunsdkcore.client import AcsClient
import uuid


REGION = "cn-hangzhou"
# ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
ACCESS_KEY_ID = "YOUR ACCESS_KEY_ID"
ACCESS_KEY_SECRET = "YOUR ACCESS_KEY_SECRET"

acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)


def send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)

    # 短信模板变量参数
    if template_param is not None:
        smsRequest.set_TemplateParam(template_param)

    # 设置业务请求流水号,必填。
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(sign_name);

    # 短信发送的号码列表,必填。
    smsRequest.set_PhoneNumbers(phone_numbers)

    # 调用短信发送接口,返回json
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    # TODO 业务处理

    return smsResponse


def query_send_detail(biz_id, phone_number, page_size, current_page, send_date):
    queryRequest = QuerySendDetailsRequest.QuerySendDetailsRequest()
    # 查询的手机号码
    queryRequest.set_PhoneNumber(phone_number)
    # 可选 - 流水号
    queryRequest.set_BizId(biz_id)
    # 必填 - 发送日期 支持30天内记录查询,格式yyyyMMdd
    queryRequest.set_SendDate(send_date)
    # 必填-当前页码从1开始计数
    queryRequest.set_CurrentPage(current_page)
    # 必填-页大小
    queryRequest.set_PageSize(page_size)

    # 调用短信记录查询接口,返回json
    queryResponse = acs_client.do_action_with_exception(queryRequest)

    # TODO 业务处理

    return queryResponse


__name__ = 'send'
if __name__ == 'send':
    __business_id = uuid.uuid1()
    print(__business_id)
    params = {"code": "456789"}
    print(send_sms(__business_id, "13000000000", "测试", "SMS_1234567", params))

aliyunsdkcore's People

Contributors

duangy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

aliyunsdkcore's Issues

import err

ImportError: cannot import name 'CommonRequest' from 'aliyunsdkcore.request'

user_config_endpoints 错误

if product in user_config.user_config_endpoints:
AttributeError: module 'aliyunsdkcore.profile.region_provider' has no attribute 'user_config_endpoints'

报错SDK.InvalidRegionId Can not find endpoint to access的解决

  • 首先,要用自己的ak和sk才能运行.
  • 其次,报错
params = "{\"code\":\"12345\",\"product\":\"云通信\"}"
print(send_sms(__business_id, "我的手机号", "云通信", "SMS_137885156", params))

# 返回
b'{"Message":"params must be [a-zA-Z0-9] for verification sms","RequestId":"8AC4C6F8-F483-4AFC-87BD-30490D3A5A21","Code":"isv.INVALID_PARAMETERS"}'

难道params 不能包含子母和数字之外的字符?

简单修改demo有时能正常发送,但有时候会报错::

Traceback (most recent call last):
  File "demo_sms_send.py", line 43, in <module>
    "我的手机号", "我的签名", "模板号", params))
  File "demo_sms_send.py", line 35, in send_sms
    smsResponse = acs_client.do_action_with_exception(smsRequest)
  File "我的路径/aliyunsdkcore/client.py", line 259, in do_action_with_exception
    status, headers, body = self.implementation_of_do_action(acs_request)
  File "我的路径/aliyunsdkcore/client.py", line 224, in implementation_of_do_action
    endpoint = self._resolve_endpoint(request)
  File "我的路径/aliyunsdkcore/client.py", line 174, in _resolve_endpoint
    return endpoint_resolver.resolve_endpoint(self.__region_id, request, self._location_service)
  File "我的路径/aliyunsdkcore/profile/endpoint/endpoint_resolver.py", line 36, in resolve_endpoint
    error_msg.get_msg('SDK_INVALID_REGION_ID'))
aliyunsdkcore.acs_exception.exceptions.ClientException: SDK.InvalidRegionId Can not find endpoint to access.

代码如下:

# -*- coding: utf-8 -*-
from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkcore.client import AcsClient
import uuid


def send_sms(ak, sk, phone_numbers, sign_name, template_code, template_param=None,
             REGION="cn-hangzhou"):
    smsRequest = SendSmsRequest.SendSmsRequest()
    # 申请的短信模板编码,必填
    smsRequest.set_TemplateCode(template_code)

    # 短信模板变量参数
    if template_param is not None:
        smsRequest.set_TemplateParam(template_param)

    # 设置业务请求流水号,必填。
    business_id = uuid.uuid1()
    smsRequest.set_OutId(business_id)

    # 短信签名
    smsRequest.set_SignName(sign_name)

    # 数据提交方式
    # smsRequest.set_method(MT.POST)

    # 数据提交格式
    # smsRequest.set_accept_format(FT.JSON)

    # 短信发送的号码列表,必填。
    smsRequest.set_PhoneNumbers(phone_numbers)

    # 调用短信发送接口,返回json
    acs_client = AcsClient(ak, sk, REGION)
    smsResponse = acs_client.do_action_with_exception(smsRequest)

    # TODO 业务处理

    return smsResponse

params = "{\"code\":\"456\"}"
print(send_sms("我的ak", "我的sk",
               "我的手机号", "我的签名", "模板号", params))

TypeError in region_provider.py

File "/root/workspace/env/lib/python3.6/site-packages/aliyunsdkcore/profile/region_provider.py", line 130, in convert_dict_to_endpointsxml
content += ''+item.keys()[0]+'\n'
TypeError: 'dict_keys' object does not support indexing

For python3, dict keys is not list

python-3.9.0-embed-amd64 用pip安装失败(包括aliyun-python-sdk-core和aliyun-python-sdk-iot)

pip install aliyunsdkcore
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Collecting aliyunsdkcore
Downloading
http://mirrors.aliyun.com/pypi/packages/36/80/4fd3153ce15ec7edae283fa937ee1adc0855f980ce248611b2e009d343df/aliyunsdkcore-1.0.3.tar.gz (23 kB)
ERROR: Command errored out with exit status 1:
command: 'd:\python-3.9.0-embed-amd64\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-vc5sofny\aliyunsdkcore_760263d2c4f3402088d9f8592997f656\setup.py'"'"'; file='"'"'C:\Users\Admin\AppData\Local\Temp\pip-install-vc5sofny\aliyunsdkcore_760263d2c4f3402088d9f8592997f656\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Admin\AppData\Local\Temp\pip-pip-egg-info-lpu5ujkl'
cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-vc5sofny\aliyunsdkcore_760263d2c4f3402088d9f8592997f656\
Complete output (5 lines):
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\Admin\AppData\Local\Temp\pip-install-vc5sofny\aliyunsdkcore_760263d2c4f3402088d9f8592997f656\setup.py", line 225, in
VERSION = import(PACKAGE).version
ModuleNotFoundError: No module named 'aliyunsdkcore'

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

通过替换文件使aliyunsdkcore支持python3

直接把这些文件放项目中还是比较难看的。

如果已经安装这个模块(比如2.3.5或2.4.4版本,虽然官网号称支持python3.x,其实根本没做支持,包括各种print的用法都还是2.x版本的),可以直接将安装后的文件替换掉。

比如这个包安装在我的虚拟环境位置:
venv/lib/python3.4/site-packages/aliyun_python_sdk_core-2.4.4-py3.4.egg
把这个地址下aliyunsdkcore文件夹中的文件统统替换成这边下载的就行;

怎么找到这个位置?
看报错信息就知道了。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.