Coder Social home page Coder Social logo

python-sdk's Introduction

Qiniu Cloud SDK for Python

@qiniu on weibo Software License Build Status GitHub release Latest Stable Version Download Times Scrutinizer Code Quality Coverage Status

安装

通过pip

$ pip install qiniu

运行环境

Qiniu SDK版本 Python 版本
7.x 2.7, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9
6.x 2.7

使用方法

上传

import qiniu

...
    q = qiniu.Auth(access_key, secret_key)
    key = 'hello'
    data = 'hello qiniu!'
    token = q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key, data)
    if ret is not None:
        print('All is OK')
    else:
        print(info) # error message in info
...

更多参见SDK使用指南: https://developer.qiniu.com/kodo/sdk/python


## 测试

``` bash
$ py.test

常见问题

  • 第二个参数info保留了请求响应的信息,失败情况下ret 为none, 将info可以打印出来,提交给我们。
  • API 的使用 demo 可以参考 examples示例
  • 如果碰到ImportError: No module named requests.auth 请安装 requests

代码贡献

详情参考代码提交指南

贡献记录

联系我们

  • 如果需要帮助,请提交工单(在portal右侧点击咨询和建议提交工单,或者直接向 [email protected] 发送邮件)
  • 如果有什么问题,可以到问答社区提问,问答社区
  • 更详细的文档,见官方文档站
  • 如果发现了bug, 欢迎提交 issue
  • 如果有功能需求,欢迎提交 issue
  • 如果要提交代码,欢迎提交 pull request
  • 欢迎关注我们的微信 微博,及时获取动态信息。

代码许可

The MIT License (MIT).详情见 License文件.

python-sdk's People

Contributors

bachue avatar bernieyangmh avatar carter2000 avatar chzyer avatar clouddxy avatar cloverstd avatar deepgully avatar dtynn avatar e06084 avatar forrest-mao avatar hantuo avatar hokein avatar jemygraw avatar lidaobing avatar lihsai0 avatar longbai avatar longshanksmo avatar lyyyuna avatar mandytong002 avatar mei-zhao avatar okbang9 avatar rwifeng avatar songfei9315 avatar sunrunaway avatar why404 avatar xiaoq08 avatar xushiwei avatar xuzhaokui avatar xwen-winnie avatar yangjunren 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  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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-sdk's Issues

关于qiniu.conf的设计模式

Python里的模块是用于全局的,所以应该尽量避免在模块中存放可变对象。qiniu.conf配置access_key和secret_key却在模块中引入了两个变量。这样做的直接后果就是,如果不对代码进行hack,将无法在一个应用中使用多个qiniu账号:一些有这样特殊需要的场合就会凸显出此处设计模式的问题。

更完善的做法,是将config作为一个可实例化的类,在实例化过程中传入变量。在需要使用配置的地方传入实例对象而不是import模块。

如果这样到处传值的方式让人很烦,也可以考虑使用类似flask的上下文管理:

from qiniu.conf import Config, current_config

conf = Config(access_key='blahblah',
              secret_key='blahblah')

with conf.context():
    assert current_config.access_key == conf.access_key
    assert current_config.secret_key == conf.secret_key

py27 unicode 兼容性问题

#!/usr/bin/env python
#coding=utf-8

from __future__ import print_function, unicode_literals, absolute_import
from qiniu import Auth

class settings():
    QINIU_ACCESS_KEY = 'aaaaa'
    QINIU_SECRET_KEY = 'sssss'
    QINIU_BUCKET_NAME = 'bbbbb'
    QINIU_TOKEN_EXPRIE_TIME = 3600

key = ''

q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
token = q.upload_token(settings.QINIU_BUCKET_NAME, key, settings.QINIU_TOKEN_EXPRIE_TIME)

错误提示为

Traceback (most recent call last):
  File "/Users/rex/py/test.py", line 18, in <module>
    token = q.upload_token(settings.QINIU_BUCKET_NAME, key, settings.QINIU_TOKEN_EXPRIE_TIME)
  File "/usr/local/lib/python2.7/site-packages/qiniu/auth.py", line 151, in upload_token
    return self.__upload_token(args)
  File "/usr/local/lib/python2.7/site-packages/qiniu/auth.py", line 155, in __upload_token
    return self.token_with_data(data)
  File "/usr/local/lib/python2.7/site-packages/qiniu/auth.py", line 69, in token_with_data
    return '{0}:{1}:{2}'.format(self.__access_key, self.__token(data), data)
  File "/usr/local/lib/python2.7/site-packages/qiniu/auth.py", line 61, in __token
    hashed = hmac.new(self.__secret_key, data, sha1)
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hmac.py", line 136, in new
    return HMAC(key, msg, digestmod)
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hmac.py", line 75, in __init__
    self.outer.update(key.translate(trans_5C))
TypeError: character mapping must return integer, None or unicode

如果注释掉 第4行 即可正常工作

NoneType has no len()

在没有初始化环境变量下跑单元测试,抛出异常。

======================================================================
ERROR: test_put_crc_fail (__main__.TestUp)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "qiniu/test/io_test.py", line 63, in test_put_crc_fail
    ret, err = io.put(policy.token(), key, data, extra)
  File "/home/alswl/dev/project/python/qiniu/qiniu/rs/rs_token.py", line 48, in token
    return mac.sign_with_data(b)
  File "/home/alswl/dev/project/python/qiniu/qiniu/auth/digest.py", line 27, in sign_with_data
    return '%s:%s:%s' % (self.access, self.__sign(data), data)
  File "/home/alswl/dev/project/python/qiniu/qiniu/auth/digest.py", line 19, in __sign
    hashed = hmac.new(self.secret, data, sha1)
  File "/usr/lib/python2.7/hmac.py", line 133, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib/python2.7/hmac.py", line 68, in __init__
    if len(key) > blocksize:
TypeError: object of type 'NoneType' has no len()

======================================================================

要不在 action 之前做个检查,抛出 NoneType 不太友好吧。

pip install error

Install package from source needs install requests package first, if not, you will see this error:

Traceback (most recent call last):
File "setup.py", line 14, in
version=import('qiniu').version,
File "/home/app/qiniu_demo/python-sdk-7.0.0/qiniu/init.py", line 14, in
from .auth import Auth
File "/home/app/qiniu_demo/python-sdk-7.0.0/qiniu/auth.py", line 7, in
from requests.auth import AuthBase
ImportError: No module named requests.auth

客户端经常Connection timed out, 可不可以让用户设置Timeout的时间长度?

以下是我遇到的异常, 可不可以让用户来设置connection timeout的值?这样如果用户的连接速度不是很快, 可以设置大一些的timeout。

ret, err = qiniu.rs.Client().delete(self.bucket, item['key'])
File "/usr/local/lib/python2.7/dist-packages/qiniu/rs/rs.py", line 18, in delete
return self.conn.call(uri_delete(bucket, key))
File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 22, in call
return self.call_with(path, None)
File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 34, in call_with
resp = self.round_tripper("POST", path, body)
File "/usr/local/lib/python2.7/dist-packages/qiniu/auth/digest.py", line 58, in round_tripper
return super(Client, self).round_tripper(method, path, body)
File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 17, in round_tripper
self._conn.request(method, path, body, self._header)
File "/usr/lib/python2.7/httplib.py", line 958, in request
self._send_request(method, url, body, headers)
File "/usr/local/lib/python2.7/dist-packages/qiniu/httplib_chunk.py", line 84, in _send_request
self.endheaders(body, is_chunked=is_chunked)
File "/usr/local/lib/python2.7/dist-packages/qiniu/httplib_chunk.py", line 100, in endheaders
self._send_output(message_body, is_chunked=is_chunked)
File "/usr/local/lib/python2.7/dist-packages/qiniu/httplib_chunk.py", line 118, in _send_output
self.send(msg)
File "/usr/local/lib/python2.7/dist-packages/qiniu/httplib_chunk.py", line 22, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 757, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 110] Connection timed out

用七牛上传图片时预处理并保存缩略图的问题

我设置了policy.persistentOps,结果始终不能保存缩略图

entry = "%s:%s" %(bucket, fkey)
EncodeEntryURI = base64.urlsafe_b64encode(entry)
policy.persistentOps = "imageView2/1/w/100/h/100|saveas/%s" % EncodeEntryURI
policy.persistentNotifyUrl="localhost:8080"

其他部分应该不用贴吧,因为上传是成功的, 只是预处理和保存没成功。

install error "ImportError: No module named requests.auth"

envs:
ubuntu 14.04 x86_64
python 2.7.6

(qiniu)tomatoengine:/opt/projects/webapps/envs/python-sdk-7.0.0$ python setup.py install
Traceback (most recent call last):
  File "setup.py", line 14, in <module>
    version=__import__('qiniu').__version__,
  File "/opt/projects/webapps/envs/python-sdk-7.0.0/qiniu/__init__.py", line 14, in <module>
    from .auth import Auth
  File "/opt/projects/webapps/envs/python-sdk-7.0.0/qiniu/auth.py", line 7, in <module>
    from requests.auth import AuthBase
ImportError: No module named requests.auth

did i lose some mods?

上传大文件的时候自动输出时间戳等

这里_Resume类在初始化的时候自动print 了两个时间戳,能不能隐藏一下。。。。首先这两个print应该没有什么作用的吧,然后,,,我在终端调用这样自动print东西出来我会比较难处理

print(self.modify_time)
print(modify_time)

然后还有另一个地方

def record_upload_progress(self, offset):

print(record_data)

能不能把这些输出都去掉讷。

好吧,我的终端处理上传的时候暂时没有处理进度条,难道这是会产生输出的原因么。。。。

SDK的返回不友好

目前通过Python-SDK访问通过返回的 ret 和 err 拿到返回信息,但是当出现错误的时候,返回信息最好通过内部定义的返回码定义而不是一个长字符串,这样方便程序容错,重试

Exception: UnicodeDecodeError

Exception
Types:  

UnicodeDecodeError

Value:  

'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

Location:   qiniu/rpc.py in encode_multipart_formdata , line 110

https://github.com/qiniu/python-sdk/blob/develop/qiniu/rpc.py#L101h

这里的 value 可能为 unicode,比如(u'd653c8cd3d6e72f6161992d064f1d445eb84aae8.jpeg'),而 file 的 value 是 str 格式的二进制文件,无法升级到 unicode,导致 join 失败,抛出异常

exception:character mapping must return integer, None or unicode

access_key 和security key 为unicode时, bucket.fetch会出错,必须将unicode转码为ascii
Python 2.7.6 , qiniu==7.0.2

例如:
q = Auth(u'ak', u'sk')
bucket = BucketManager(q)
ret, info = bucket.fetch(url, u'xxx', '1.jpg')

info
exception:character mapping must return integer, None or unicode, status_code:-1, _ResponseInfo__response:None, text_body:None, req_id:None, error:character mapping must return integer, None or unicode, x_log:None

Error when no command line args given (Python 3 only)

This is only reproducible with Python 3 (3.4) here:

$ qiniupy
Traceback (most recent call last):
  File "/usr/bin/qiniupy", line 9, in <module>
    load_entry_point('qiniu==7.0.1', 'console_scripts', 'qiniupy')()
  File "/usr/lib/python3.4/site-packages/qiniu/main.py", line 20, in main
    if args.etag_files:
AttributeError: 'Namespace' object has no attribute 'etag_files'

With Python 2.7, it works as intended:

$ qiniupy2
usage: qiniu [-h] {etag} ...
qiniu: error: too few arguments

list操作的实现是否有问题?

刚刚尝试了Python SDK,list同样的内容,CPU一个核心会满载半分钟,绝大部分时间都在执行http.py中的__return_wrapper函数

相比之下,在PHP SDK中,进行一次bucket内1000个文件的list请求,可以瞬间完成。
是不是Python SDK有些缺陷?

# -*- coding: utf-8 -*-

from qiniu import Auth
from qiniu import BucketManager

AK = ""
SK = ""
BUCKET_NAME = ""

auth = Auth(AK, SK)
bucket = BucketManager(auth)
response, eof, info = bucket.list(BUCKET_NAME, None, None, 1000, None)

公开现有 qiniu.utils._etag 函数

qiniu.utils.etag 支持输入文件路径计算hash,qiniu.utils._etag 支持输入字节流计算hash。实际使用过程中遇到输入 StringIO.StringIO 计算hash的需求,希望能公开这个函数并改个名字,比如叫 qiniu.utils.etag_stream

感谢。

有没有比较新的文档

我用七牛的python sdk上传图片,根据官方的教程,我写了差不多这样的例子

import qiniu
import qiniu.io

...
ret, err = qiniu.io.put(uptoken, key, data, extra)
...

但是在运行的时候提示没有io这个模块,应该是现在的SDK比较新,而文档还是老的。在哪里可以找到比较新的,比较完整的文档吗

httplib.BadStatusLine错误没有被封装到err里面

最近在执行 ret, err = qiniu.io.put_file(uptoken, key, the_file) 时不时会遇到这个错误,然后就挂了,根本运行不到 if err: 这里

Traceback (most recent call last):
  File ".............................................", line ..., in export
    ret, err = qiniu.io.put_file(uptoken, key, the_file)
  File "/usr/local/lib/python2.7/dist-packages/qiniu/io.py", line 65, in put_file
    return put(uptoken, key, f, extra)
  File "/usr/local/lib/python2.7/dist-packages/qiniu/io.py", line 54, in put
    return rpc.Client(conf.UP_HOST).call_with_multipart("/", fields, files)
  File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 59, in call_with_multipart
    return self.call_with(path, mr, content_type, mr.length())
  File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 34, in call_with
    resp = self.round_tripper("POST", path, body)
  File "/usr/local/lib/python2.7/dist-packages/qiniu/rpc.py", line 18, in round_tripper
    resp = self._conn.getresponse()
  File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse
    response.begin()
  File "/usr/lib/python2.7/httplib.py", line 407, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
    raise BadStatusLine(line)
httplib.BadStatusLine: ''

是在aws的云上,而且时有时无,不知道该怎么debug。

我不想用 try except,我觉得 ret, err 挺好的,就是不知道为什么不行。

不能使用 StringIO 提交

UploadFile 中使用 file 打开本地文件,然后在 MultipartPostHandler.py 针对 file type 做判断,这样不太靠谱,因为有时候我会用 StringIO 做 file 提交。

poster module 可以解决这个问题,不过当 poster 提交 StringIO 时候,因为 StringIO 的 name 不存在,所以在 form-data 里面的 filename 是空的,七牛就会报 400 错误。

我现在暂时在提交前强行设定 StringIO.name 来解决这个 400 错误。希望下个版本可以支持 StringIO 提交。

要是没人理会,那我就自己 Pull.

download_private_link无法返回可用链接

按照文档里面的方法

from hashlib import sha1
url = 'http://developer.qiniu.com/resource/flower.jpg?e=1451491200'
secret = 'MY_SECRET_KEY'
print urlsafe_b64encode(hmac.new(url,secret , sha1).digest())
   _wtPUG_vrv3OO3LRNj7W7lju2kM=

并不能得到文档所示的url诶
或者说我的加密方式有错么

sdk文档好像没有找到域名相关的说明

下载私有文件的时候,sdk文档里是这样写的

......
base_url = 'http://%s/%s' % (bucket + '.qiniudn.com', key)
private_url = q.private_download_url(base_url, expires=3600)
......

上面访问的结果是"no such domain"

但是实际使用的时候要使用这个域名代替bucket + '.qiniudn.com

七牛域名
使用带有功能性的七牛域名进行网络资源的解析可获得相应的效果。
xxxxxx.com1.z0.glb.clouddn.com 

_是否更新一下文档?_

fetch 不能抓取外站图片么

url = '外站图片地址'
ret, info = bucket.fetch(url, 'name', filename)

返回数据

exception:None, status_code:200, _ResponseInfo__response:<Response [200]>, text_body:{}, req_id:hSAAAGLRA_feHcIT, x_log:QINIUPROXY:33;gS.h:33;uS.cpy:4;s.ph;s.put.tw;s.put.tr;s.put.tw;s.put.tr;s.ph;s.put.tw;s.put.tr;s.ph;PFDS:1;PFDS:2;PFDS:3;rdb.g/no such key;DBD/404;DBG/404;v4.exist:1/Document not found;rs11_4.ins:1;qtbl.ins:2;mc.s;RS:3;uS.hdo:8;IO:47

review 意见整理

  1. https://github.com/qiniu/python-sdk/blob/develop/demo.py 这个文件似乎应该去掉
    还有 qiniu-logo.jpeg。看了下,这个 demo.py 是 gist 需要,那么应该挪到 gist 目录去。
  2. gist 使用的 demo 代码,最好也由 Travis-CI 进行 check(这个 check 只是确认编译不出错就行)。这一点 c sdk、go sdk 都已经实现。
  3. https://github.com/qiniu/python-sdk/blob/develop/qiniu/auth_token.py
    这个文件从名字空间来说不符合预期。使用上按理应该是 qiniu.rs.PutPolicy.token()
  4. config.py 按照 spec 是 conf.py

https支持吗?

python SDK是否支持https上传文件?若支持https,需要修改那里啊?官方的文档里一直没找到Python SDK是怎么支持https的。能否简单给个示例或者讲解一下需要哪里修改一些配置?

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.