Giter Club home page Giter Club logo

python-sdk's Introduction

Python-SDK

GitHub Workflow Status (branch) Codecov

LeanCloud Python SDK

Install

pip install leancloud

or

easy_install leancloud

Maybe you need the sudo prefix depends on your OS environment.

Supported Python Versions

Python 2.7.18 and Python 3.6+.

Generate API document

Install dependencies:

pip install Sphinx sphinx_rtd_theme
cd apidoc
make html

Run Tests

Configure the following environment variables:

  • APP_ID
  • APP_KEY
  • MASTER_KEY
  • USE_REGION

Make sure the following options are configured on the LeanCloud console:

  • Data Storage > Settings > Include ACL with objects being queried: checked
  • Push Notification > Push notification settings > Prevent clients from sending push notifications: unchecked
  • Settings > Security > Service switches > Push notifications: enabled
  • Settings > Security > Service switches > SMS: disabled

And there is a cloud function naming add which returns 3 for add(a=1, b=2) deployed on the LeanEngine production environment of the application. For example:

AV.Cloud.define('add', async function (request) {
    return request.params["a"] + request.params["b"]
})

Install dependencies:

pip install -e .'[test]'

Run tests:

python -m nose

Run a single test without swallowing print:

python -m nose -v --nocapture tests/test_engine.py:test_lean_engine_error

Linter and Formatter

Currently, flake8 (linter) and black (formatter) are used. But we are still exploring.

Release a New Version

  1. Edit changelog and setup.py (version).
  2. Generate API doc.
  3. Commit the changes above and send a pull request.
  4. The maintainer will review and merge the pull request, then create a new release at GitHub web UI.
  5. A new version of the package will be published to PyPI automatically (via GitHub Actions).

License

License: GNU LGPL.

Author: asaka ([email protected])

python-sdk's People

Contributors

aisk avatar azalea avatar chaim007 avatar cshuaimin avatar dionysusg avatar dlmyb avatar feisuzhu avatar iceber avatar jinke18 avatar johndeng avatar juvenn avatar jwfing avatar killme2008 avatar leeyeh avatar lord63 avatar lupintheforth avatar nervouna avatar pyup-bot avatar sdjcw avatar weakish avatar ym avatar yongbo 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

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

python-sdk's Issues

对象属性能否直接获取

from leancloud import Query
query = Query(GameScore)
game_score = query.get('520ca0bbe4b07e8e0e847e31')
# print game_score.get('playerName')
print game_score.playerName

可否支持通过重写__getattr__达到获取参数名称时无需使用get方法

例如:

def __getattr__(self, attr):
    return self.get(attr)

这里的User.py中很多方法,通过pip install 没有

用pip install leancloud-sdk, 并且upgrade到1.3
user.py中,到

def is_linked(self, provider):
        try:
            self.get('authData')[provider]
        except KeyError:
            return False
        return True

后面就没了。我还想打算用

@classmethod
    def request_password_reset(self, email):
        params = {'email': email}
        client.post('/requestPasswordReset', params)

调用的时候,显示没有这个method

Python3?

are there plans to support Python 3?

服务端返回中文错误信息,无法正确 decode

我返回的是 escape 过的 unicode

Traceback (most recent call last):
  File "test1.py", line 23, in <module>
    print e
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128)

sdk的engine/authorization.py获取环境变量代码有问题

1.1.0的代码里面,engine/authorization.py获取环境变量的3个字段如下:

APP_ID = os.environ.get('LC_APP_ID')
APP_KEY = os.environ.get('LC_APP_KEY')
MASTER_KEY = os.environ.get('LC_MASTER_KEY')

但是,avoscloud-command的代码,0.7.8的代码,关于python运行时的代码是如下设置的:


var getPythonRuntimeInfo = function(appPath, cb) {
  var app = run.getAppSync();
  run.initMasterKey(function(masterKey) {
    cb(null, {
      runtime: 'python',
      exec: 'python',
      setDebug: function(debug) {
        if (debug) {
          this.exec = 'python -m pdb';
        }
      },
      getMonconfig: function(args) {
        return {
          exec: this.exec,
          ignore: [
            '.git'
          ],
          "env": {
            LC_APP_ID: app.appId,
            LC_APP_KEY: masterKey,
            LC_APP_MASTER_KEY: masterKey,
            LC_APP_PORT: run.getPort()
          },
          ext: 'py',
          script: 'wsgi.py',
          args: args
        };
      },
      bulk: function() {
        return [{ src: ['**', '!bin/**', '!include/**', '!lib/**', '!pip-selfcheck.json']}];
      }
    });
  });
};

lz发现木有,一个是LC_APP_MASTER_KEY,一个是LC_MASTER_KEY,是不是要改下?

SDK现在不可用是吗

python setup.py test

running test
running egg_info
writing requirements to leancloud_sdk.egg-info/requires.txt
writing leancloud_sdk.egg-info/PKG-INFO
writing top-level names to leancloud_sdk.egg-info/top_level.txt
writing dependency_links to leancloud_sdk.egg-info/dependency_links.txt
reading manifest file 'leancloud_sdk.egg-info/SOURCES.txt'
writing manifest file 'leancloud_sdk.egg-info/SOURCES.txt'
running build_ext
tests.test_avobject.test_extend ... ERROR
tests.test_avobject.test_class_extend ... ERROR
tests.test_avobject.test_set ... ERROR
tests.test_avobject.test_get ... ERROR
tests.test_avobject.test_save ... ERROR
tests.test_avquery.test_basic_query ... ERROR
tests.test_geo_point.test_invalid ... ok
tests.test_geo_point.test_setter ... ok
tests.test_geo_point.test_dump ... ok
tests.test_geo_point.test_radians_to ... ok
tests.test_geo_point.test_eq ... ok

======================================================================
ERROR: tests.test_avobject.test_extend
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/private/tmp/python-sdk/tests/test_avobject.py", line 21, in test_extend
    ok_(Object.extend('Album'))
AttributeError: type object 'Object' has no attribute 'extend'

======================================================================
ERROR: tests.test_avobject.test_class_extend
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/private/tmp/python-sdk/tests/test_avobject.py", line 28, in test_class_extend
    assert 'title' in Album._fields
AttributeError: type object 'Album' has no attribute '_fields'

======================================================================
ERROR: tests.test_avobject.test_set
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/private/tmp/python-sdk/tests/test_avobject.py", line 32, in test_set
    Album = Object.extend('Album')
AttributeError: type object 'Object' has no attribute 'extend'

======================================================================
ERROR: tests.test_avobject.test_get
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/private/tmp/python-sdk/tests/test_avobject.py", line 40, in test_get
    Album = Object.extend('Album')
AttributeError: type object 'Object' has no attribute 'extend'

======================================================================
ERROR: tests.test_avobject.test_save
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/private/tmp/python-sdk/tests/test_avobject.py", line 49, in test_save
    Album = Object.extend('Album')
AttributeError: type object 'Object' has no attribute 'extend'

======================================================================
ERROR: tests.test_avquery.test_basic_query
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/nose/case.py", line 267, in setUp
    try_run(self.test, names)
  File "/Library/Python/2.7/site-packages/nose/util.py", line 470, in try_run
    return func()
  File "/private/tmp/python-sdk/tests/test_avquery.py", line 26, in setup_func
    albums = Query(GameScore).find()
  File "/private/tmp/python-sdk/leancloud/query.py", line 105, in find
    result = rest.get('/classes/{}'.format(self._query_class._class_name), self.dump())
AttributeError: type object 'GameScore' has no attribute '_class_name'

----------------------------------------------------------------------
Ran 11 tests in 0.100s

FAILED (errors=6)

User.create_follower_query和User.create_followee_query无法使用

调用User.create_follower_query(id).find(), 返回的结果永远是 [].

社区里没有人回复我, 所以我自己看了一下源码, 发现create_follower_query调用的是_User的API, 以至于每次的返回值都是[].

https://forum.leancloud.cn/t/python-sdk-create-follower-query/2159里有一个较为简陋的临时解决方法.

Lutz在https://ticket.avosapps.com/tickets/6222也曾提到"通过日志看到,FriendshipQuery最终请求的path是"/1.1/classes/_User",这个请求path应该是有误吧?"

这个问题似乎在#34里没有得到解决.

几次遇到TypeError: XXX is not JSON serializable的问题

之前用engine.current_user的时候就遇到这个问题,后来绕过去了。现在在云函数里返回一个Object的子类又遇到了。追了一下leanengine.py里的dispatch_request方法里的return Response(json.dumps(result), mimetype='application/json'),result是一个包含Object对象的字典,Python的LeanEngine返回值不能是对象吗?

Traceback (most recent call last):
INFO 2015-12-27 00:54:21 File "/mnt/avos/data/uluru-cloud-code/repos/a06snenjxu3v9ohetuhedb0dfjmw81ejxoqz9cnuetewzy2m/lib/python2.7/site-packages/leancloud/engine/leanengine.py", line 104, in dispatch_request
INFO 2015-12-27 00:54:21 return Response(json.dumps(result), mimetype='application/json')
INFO 2015-12-27 00:54:21 File "/usr/lib/python2.7/json/init.py", line 243, in dumps
INFO 2015-12-27 00:54:21 return _default_encoder.encode(obj)
INFO 2015-12-27 00:54:21 File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
INFO 2015-12-27 00:54:21 chunks = self.iterencode(o, _one_shot=True)
INFO 2015-12-27 00:54:21 File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
INFO 2015-12-27 00:54:21 return iterencode(o, 0)
INFO 2015-12-27 00:54:21 File "/usr/lib/python2.7/json/encoder.py", line 184, in default
INFO 2015-12-27 00:54:21 raise TypeError(repr(o) + " is not JSON serializable")
INFO 2015-12-27 00:54:21 TypeError: <leancloud.object
.YMAVAccess object at 0x7f1e0402e610> is not JSON serializable

提高单元测试覆盖率

目前单元测试覆盖率为 80%,争取达到 100%。

nosetests --with-coverage --cover-package=leancloud :

Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
leancloud                                       23      0   100%
leancloud.acl                                   73     34    53%   22, 34-35, 38-40, 43, 45, 51, 54, 57, 60, 63, 66, 69, 72-73, 75-76, 79-83, 86-90, 93-97
leancloud.client                                75      1    99%   85
leancloud.engine                                46      3    93%   37-39
leancloud.engine.authorization                  40      0   100%
leancloud.engine.cloudfunc                      20      6    70%   34, 43, 46, 59-63
leancloud.engine.context                         5      0   100%
leancloud.engine.https_redirect_middleware      16      8    50%   16, 19-26
leancloud.engine.leanengine                    143     60    58%   29-30, 75-77, 83-84, 93, 95, 97, 99, 103, 105-113, 134, 141, 150-158, 173-186, 190-199, 203-207, 211-215, 219-223, 227, 234, 238, 247, 251
leancloud.engine.utils                           4      0   100%
leancloud.errors                                 8      0   100%
leancloud.file_                                116     14    88%   41, 48, 52-53, 85, 98, 102, 106, 110, 113, 123-126
leancloud.geo_point                             48      4    92%   32, 59, 104, 114
leancloud.mime_type                              2      0   100%
leancloud.object_                              262     13    95%   124, 194-195, 202, 251, 263, 267-270, 441, 444, 508
leancloud.operation                            202     56    72%   13, 16, 19, 48, 77, 82, 86, 93, 101, 110, 112, 115, 120, 126, 134, 143, 145, 148, 157-162, 171, 179, 186, 188, 191-193, 197, 201, 215, 219, 225-230, 234-239, 274, 277, 289, 291-299
leancloud.push                                  28      7    75%   41, 46, 48, 50, 52, 54, 56
leancloud.query                                248     77    69%   26-28, 61, 91, 93-95, 102, 106, 148, 186, 208-209, 218-221, 248-249, 328-329, 348-349, 361-371, 396-399, 411-414, 426-429, 442, 452, 462-463, 473-474, 493-494, 513-514, 524-525, 536-538, 549, 560, 571-572, 581-584, 594, 608, 611-615
leancloud.relation                              47     13    72%   25-27, 60-65, 68, 81-83
leancloud.role                                  25      4    84%   32, 35, 41, 44
leancloud.user                                  93     10    89%   60-62, 70, 74, 126, 137-140
leancloud.utils                                115     23    80%   47, 139, 145-151, 160, 162, 186, 197-201, 208, 225-229
--------------------------------------------------------------------------
TOTAL                                         1639    333    80%
----------------------------------------------------------------------
Ran 78 tests in 18.427s

比较重要的 query / operation / acl 优先级为高,需要达到 100%。

CQL模糊查询中文

查询语句

    cql = "select * from Activity where type=? and publisher=? \
        and title like '?%' limit ?, ? order by createAt desc"

File "/Users/zhouyang/MyCode/Infohold/Platform/loker/lib/python2.7/site-packages/leancloud/query.py", line 97, in do_cloud_query
content = utils.response_to_json(client.get('/cloudQuery', params))
File "/Users/zhouyang/MyCode/Infohold/Platform/loker/lib/python2.7/site-packages/leancloud/client.py", line 70, in new_func
return func(_args, *_kwargs)
File "/Users/zhouyang/MyCode/Infohold/Platform/loker/lib/python2.7/site-packages/leancloud/client.py", line 88, in new_func
raise leancloud.LeanCloudError(content.get('code', 1), content.get('error', 'Unknown Error'))
LeanCloudError: [1] 服务器内部错误,如有疑问请从帮助菜单进入社区提交问题,内部错误代码: qvSfijbNBv45kM39

另外,使用cql无法排序

user login 以后没有session code?

Doc 中提到

login(username=None, password=None)
登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。

但是我login返回为None.

token = User().login(request.form.get('email'), request.form.get('password'))

使用User.get_current()可以得到leancloud user object
使用User().get_session_token()返回也是None
然后我看了一下SDK中login部分:

response = client.post('/login', params=self.dump())
        content = utils.response_to_json(response)
        server_data = self.parse(content, response.status_code)
        self._finish_fetch(server_data, False)
        self._handle_save_result(True)
        if 'smsCode' not in server_data:
            self.attributes.pop('smsCode', None)

没有地方设置 _session_token
请问我miss了那里?

请问你们的文档 和 代码是不是同步的 保存失败

import leancloud
from leancloud import User

leancloud.init('xxx', 'xxx')

u = User()
u.login("user43", "123456")
print u.get('username')
print u.set('password','testname')
u.save()

报错
u.save()
File "C:\Python27\lib\site-packages\leancloud\user.py", line 85, in save
super(User, self).save()
File "C:\Python27\lib\site-packages\leancloud\object_.py", line 160, in save
response = client.put('/classes/{0}/{1}'.format(self._class_name, self.id), data)
File "C:\Python27\lib\site-packages\leancloud\client.py", line 68, in new_func
return func(_args, *_kwargs)
File "C:\Python27\lib\site-packages\leancloud\client.py", line 81, in new_func
raise leancloud.LeanCloudError(content.get('code', 1), content.get('error', 'Unknown Error'))
leancloud.errors.LeanCloudError: [206] The user cannot be altered by a client without the session.

支持DateTime类型但是不支持Date类型

import unittest
import leancloud

from datetime import datetime, date
from leancloud import Object


class LearnCloudTest(unittest.TestCase):
    def setUp(self):
        leancloud.init('ak', 'sk')

    def test_date_time_type(self):
        obj = Object.extend('myObject')()
        obj.set('myNumber', 2.718)
        obj.set('myString', 'foobar')
        obj.set('myDate', datetime.now())
        obj.set('myArray', [1, 2, 3, 4])
        obj.set('myDict', {'string': 'some string', 'number': 1})
        obj.set('myNone', None)
        obj.save()

    def test_date_type(self):
        obj = Object.extend('myObject')()
        obj.set('myNumber', 2.718)
        obj.set('myString', 'foobar')
        obj.set('myDate', date.today())
        obj.set('myArray', [1, 2, 3, 4])
        obj.set('myDict', {'string': 'some string', 'number': 1})
        obj.set('myNone', None)
        obj.save()

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.