def push_data_to_feedback(feedback_data):
    """
    define: feedback data contains a user's feedbacks,
    user's label and applist should be included in {Dict}-feedback_data
    :param feedback_data: format:{"labels":["label1","label2","label3"],"applist":["app1","app2","app3"]}
    :return:
    """
    from config import token_config

    leancloud.init(token_config.LEANCLOUD_APP_ID, token_config.LEANCLOUD_APP_KEY)
    try:
        labels = feedback_data['labels']
        applist = feedback_data['applist']
        fd = FeedbackData()
        if not isinstance(labels, dict):
            raise MsgException('labels should be a dict!')
        if not isinstance(applist, list):
            raise MsgException('applist should be a list!')
        if len(labels) == 0:
            raise MsgException('labels should not be empty!')
        if len(applist) == 0:
            raise MsgException('applist should not be empty!')

        fd.set('applist', applist)
        fd.set('labels', labels)
        fd.save()
    except KeyError, keyerror:
        # simply raise a exception
        raise keyerror
    def __init__(self):
        leancloud.init(settings.APP_ID, master_key=settings.MASTER_KEY)
        QuestionFollowee = Object.extend('Followee' + self.userDataId)
        questionFollowee = QuestionFollowee()  #
        query = Query(QuestionFollowee)

        query.equal_to('followerLinkId',self.userLinkId)
        curTime = datetime.now()
        query.less_than('createdAt', curTime)
        followeeCount = query.count()
        print "followeeNumbers: %s" % str(questionNum)
        queryLimit = 500
        queryTimes = int(followeeCount +queryLimit -1) / queryLimit
        self.urls = []
        for index in range(queryTimes):
            query = Query(QuestionFollowee)
            query.less_than('createdAt', curTime)
            query.equal_to('followerLinkId',self.userLinkId)
            query.descending('createdAt')
            query.limit(queryLimit)
            query.skip(index * queryLimit)
            query.select('followeeDataId')
            quesRet = query.find()
            for ques in quesRet:
                self.followeeDataIdList.extend(ques.get('followeeDataId'))
    def __init__(self):
        super(LeancloudDB, self).__init__()
        self.app_id = APP_ID
        self.app_key = APP_KEY

        # leancloud init
        leancloud.init(self.app_id, self.app_key)
Exemple #4
0
    def __init__(self):
        leancloud.init('mctfj249nwy7c1ymu3cps56lof26s17hevwq4jjqeqoloaey', master_key='ao6h5oezem93tumlalxggg039qehcbl3x3u8ofo7crw7atok')

        Users = Object.extend('Users')
        query = Query(Users)
        curTime = datetime.now()
        query.exists('userId')
        query.less_than('createdAt',curTime)
        userCount = query.count()


        print "userCounts: %s" %str(userCount)
        queryLimit = 500
        queryTimes = userCount/queryLimit + 1
        self.urls = []

        for index in range(queryTimes):
            query = Query(Users)
            query.exists('userId')
            query.less_than('createdAt',curTime)
            query.descending('createdAt')
            query.limit(queryLimit)
            query.skip(index*queryLimit)
            query.select('userId')
            userRet = query.find()
            for user in userRet:
                self.urls.append(self.baseUrl + user.get('userId') +".json")
        pass
Exemple #5
0
def test_use_master_key():
    leancloud.init(os.environ['APP_ID'], os.environ['APP_KEY'], os.environ['MASTER_KEY'])
    assert client.USE_MASTER_KEY is None
    leancloud.use_master_key(True)
    assert client.USE_MASTER_KEY is True
    leancloud.use_master_key(False)
    assert client.USE_MASTER_KEY is False
Exemple #6
0
    def setup_func():
        leancloud.client.USE_MASTER_KEY = None
        leancloud.client.APP_ID = None
        leancloud.client.APP_KEY = None
        leancloud.client.MASTER_KEY = None
        if use_master_key:
            leancloud.init(
                os.environ['APP_ID'],
                master_key=os.environ['MASTER_KEY']
            )
        else:
            leancloud.init(
                os.environ['APP_ID'],
                os.environ['APP_KEY']
            )

        olds = Query(GameScore).find()
        # make sure the test data does not change, else re-initialize it
        if len(olds) == 10:
            pass
        else:
            for old in olds:
                old.destroy()

            for i in range(10):
                game_score = GameScore()
                game_score.set('score', i)
                game_score.set('playerName', '张三')
                game_score.set('location', GeoPoint(latitude=i, longitude=-i))
                game_score.set('random', random.randrange(100))
                game_score.save()
Exemple #7
0
def test_current_user():
    leancloud.init(os.environ['APP_ID'], master_key=os.environ['MASTER_KEY'])
    saved_user = leancloud.User()
    saved_user.set('username', 'user{}'.format(int(time.time())))
    saved_user.set('password', 'password')
    saved_user.set_email('{}@leancloud.rocks'.format(int(time.time())))
    saved_user.sign_up()
    session_token = saved_user.get_session_token()

    @engine.define
    def current_user():
        user = engine.current_user
        o = leancloud.Object.extend('TestCurrentUser')()
        o.set('user', user)
        o.set({'yetAnotherUser': user})
        o.save()
        assert user.get('username') == saved_user.get('username')

    response = requests.get(url + '/__engine/1/functions/current_user', headers={
        'x-avoscloud-application-id': TEST_APP_ID,
        'x-avoscloud-application-key': TEST_APP_KEY,
        'x-avoscloud-session-token': session_token,
    })
    assert response.status_code == 200

    @engine.before_save('Xxx')
    def before_xxx_save(xxx):
        assert engine.current_user.get('username') == saved_user.get('username')

    response = requests.post(url + '/__engine/1/functions/Xxx/beforeSave', headers={
        'x-avoscloud-application-id': TEST_APP_ID,
        'x-avoscloud-application-key': TEST_APP_KEY,
    }, json={'object': {}, 'user': {'username': saved_user.get('username')}})
    assert response.status_code == 200
Exemple #8
0
    def setup_func():
        leancloud.client.USE_MASTER_KEY = None
        leancloud.client.APP_ID = None
        leancloud.client.APP_KEY = None
        leancloud.client.MASTER_KEY = None
        leancloud.init(
            os.environ['APP_ID'],
            app_key=os.environ['APP_KEY'],
            master_key=os.environ['MASTER_KEY']
        )
        users = Query(User).find()
        for u in users:
            u.destroy()

        user1 = User()
        user1.set('username', 'user1_name')
        user1.set('password', 'password')
        user1.set_email('*****@*****.**')
        user1.set_mobile_phone_number('18611111111')
        user1.sign_up()
        user1.logout()

        user2 = User()
        user2.set('username', 'user2_name')
        user2.set('password', 'password')
        user2.sign_up()
        user2.logout()
        leancloud.client.use_master_key(use_master_key)
def leancloud_init():
    '''
    leancloud初始化
    :return:
    '''
    urllib3.disable_warnings()
    leancloud.init('lXyQBue2G2I80NX9OIFY7TRk', 'NkLOGPRHeVrFdJOQiDIGVGJ7')
def get_crf_event_probmap():
    leancloud.init(app_id='llir9y4gtqys053tivb4tildoan0hgj87kdd0j6ib5naye5e',
                   app_key='h5roibgrbtux2luasq1o9xwr218jebbsyuthv9ho4lced9rv')
    Config = leancloud.Object.extend('Config')
    config_query = leancloud.Query(Config)
    config_query.equal_to('name', 'crf_event_prob_map')
    crf_event_probmap = config_query.first().attributes
    return crf_event_probmap
def connect_db_log():##sensor.log.tracer   not label.sensor, 
	import leancloud,cPickle
	appid = "9ra69chz8rbbl77mlplnl4l2pxyaclm612khhytztl8b1f9o"
	   
	appkey = "1zohz2ihxp9dhqamhfpeaer8nh1ewqd9uephe9ztvkka544b"
	#appid = "ckjjqzf3jqwl8k1u4o10j2hqp0rm0q6ferqcfb0xpw00e8zl"
	#appkey = "rn0qw8ib96xl0km63kylo6v5afuxclc8jti5ol8rx4kylqob"
	leancloud.init(appid, appkey)
def main():
	#init leancloud
	leancloud.init('IRLv1lvUGypwG5XCKF248SiG-gzGzoHsz', '2lRAArUswyFeFTtIXl2wC6b5')
	#清除表中所有纪录
	table_prjList = Object.extend('table_prjList')
	table = table_prjList()
	table.destroy()
    #重置索引
	saveIndex(1)
Exemple #13
0
def setup_func():
    leancloud.client.USE_MASTER_KEY = None
    leancloud.client.APP_ID = None
    leancloud.client.APP_KEY = None
    leancloud.client.MASTER_KEY = None
    leancloud.init(
        os.environ['APP_ID'],
        os.environ['APP_KEY']
    )
Exemple #14
0
def only_init():
    leancloud.client.USE_MASTER_KEY = None
    leancloud.client.APP_ID = None
    leancloud.client.APP_KEY = None
    leancloud.client.MASTER_KEY = None
    leancloud.init(
        os.environ['APP_ID'],
        master_key=os.environ['MASTER_KEY']
    )
Exemple #15
0
def test_request_sms_code():
    leancloud.init(os.environ['APP_ID'], master_key=os.environ['MASTER_KEY'])
    try:
        cloudfunc.request_sms_code('13111111111')
    except LeanCloudError as e:
        # 短信发送过于频繁或者欠费
        if e.code in (601, 160):
            pass
        else:
            raise e
    def __init__(self, config_path="/etc/pass-word/config.cfg"):
        self.config_path = config_path
        config = ConfigParser.SafeConfigParser()
        config.read(self.config_path)
        self.appid = config.get('leancloud', 'APPID')
        self.appkey = config.get('leancloud', 'APPKEY')
        self.pass_word_data = config.get('leancloud', 'pass_word_data_table_name')
        self.pass_word_devicereg = config.get('leancloud', 'pass_word_devicereg_table_name')

        leancloud.init(self.appid, self.appkey)
def read_mesh_tree():
    leancloud.init(APP_ID, APP_KEY)
    MESH = Object.extend("MESH")
    with open("../data/2016MeshTree.txt") as f:
        for line in f:
            if "......." in line:
                items = line.strip(" \r\r\n").split("." * 43)
                mesh = MESH()
                mesh.set("tag", items[0])
                mesh.set("title", items[1])
                mesh.save()
def get_trace_by_id(trace_id):
    leancloud.init(MapToolsVars['app_id'], MapToolsVars['app_key'])
    GeneratedData = leancloud.Object.extend('GeneratedData')
    gd_query = leancloud.Query(GeneratedData)
    gd_query.equal_to('objectId', trace_id)
    try:
        find_results = gd_query.find()
        return find_results
    except leancloud.LeanCloudError, lce:
        print 'get_trace_by_id error:' + lce
        return None
def get_context_menus():
    leancloud.init(app_id='llir9y4gtqys053tivb4tildoan0hgj87kdd0j6ib5naye5e',
                   app_key='h5roibgrbtux2luasq1o9xwr218jebbsyuthv9ho4lced9rv')
    Config = leancloud.Object.extend('Config')
    config_query = leancloud.Query(Config)
    config_query.equal_to('name', 'crf_event_prob_map')
    events_type = config_query.first()
    events = events_type.attributes
    menu = []
    for event in events['value'].keys():
        menu.append(event)
    return menu
def get_recent_tracelist(limit=5):
    leancloud.init(MapToolsVars['app_id'], MapToolsVars['app_key'])
    GeneratedData = leancloud.Object.extend('GeneratedData')
    gd_query = leancloud.Query(GeneratedData)
    gd_query.limit(limit)
    gd_query.descending('createdAt')
    try:
        find_results = gd_query.find()
        return find_results
    except leancloud.LeanCloudError, lce:
        print 'get_recent_tracelist error:' + lce
        return None
Exemple #21
0
def setup():
    leancloud.init(TEST_APP_ID, TEST_APP_KEY)
    authorization._ENABLE_TEST = True
    authorization.APP_ID = TEST_APP_ID
    authorization.APP_KEY = TEST_APP_KEY
    authorization.MASTER_KEY = TEST_MASTER_KEY

    requests_intercept.install()
    add_wsgi_intercept(host, port, make_app)

    @engine.define
    def hello(**params):
        return 'hello'
Exemple #22
0
    def __init__(self,stats):
        self.stats = stats

        leancloud.init(settings.APP_ID_S, master_key=settings.MASTER_KEY_S)

        Boards = Object.extend('Boards')
        query = Query(Boards)
        query.exists('boardLink')
        query.select('boardLink')
        boards= query.find()
        self.urls = []
        for board in boards:
            self.urls.append(self.baseUrl+board.get('boardLink'))
Exemple #23
0
def setup():
    leancloud.init(os.environ['APP_ID'], app_key=os.environ['APP_KEY'], master_key=os.environ['MASTER_KEY'])
    leancloud.use_master_key(True)
    users = leancloud.Query(leancloud.User).find()
    for u in users:
        u.destroy()
    leancloud.use_master_key(False)

    user1 = leancloud.User()
    user1.set('username', 'user1_name')
    user1.set('password', 'password')
    user1.set_email('*****@*****.**')
    user1.set_mobile_phone_number('18611111111')
    user1.sign_up()
def save_to_leancloud(routeDatas):
    leancloud.init(app_id='i13osrwxayxnaqsd3v0ikmqc0b1vndjnrgp6bp00p8iae6zc',
                   app_key='d9jubbw9fokmav8j0vqyxaccz8yokmyisk98orsnnu3o8kd4')
    GeneratedData = leancloud.Object.extend('GeneratedData')
    gd = GeneratedData()
    try:
        gd.set('timestamp', int(time.time() * 1000))
        gd.set('senz_data', routeDatas)
        gd.save()
        return gd.id
    except leancloud.LeanCloudError, lce:
        # raise lce
        print 'save_to_leancloud error:' + lce
        return None
Exemple #25
0
def init_leancloud_client():
    import os

    LEANCLOUD_APP_ID = os.environ.get("LEANCLOUD_APP_ID",
                                      "rGngnUit9fqERRVjQMfzQhWg-gzGzoHsz")
    LEANCLOUD_APP_KEY = os.environ.get("LEANCLOUD_APP_KEY",
                                       "xWQ3c4CoLPXIlRd6UxLRGndX")
    LEANCLOUD_MASTER_KEY = os.environ.get("LEANCLOUD_MASTER_KEY",
                                          "x3cl6OYR2mC6dDQsW0dMeceJ")
    LEANCLOUD_REGION = os.environ.get("LEANCLOUD_REGION", "CN")
    leancloud.init(app_id=LEANCLOUD_APP_ID,
                   app_key=LEANCLOUD_APP_KEY,
                   master_key=LEANCLOUD_MASTER_KEY)
    leancloud.use_region(LEANCLOUD_REGION)
    print("leancloud init success with app_id: {}, app_key: {}, region: {}".
          format(LEANCLOUD_APP_ID, LEANCLOUD_APP_KEY, LEANCLOUD_REGION))
Exemple #26
0
class MixinUser(Model):
    leancloud.init(config.leancloud.APP_ID, config.leancloud.APP_KEY)
    mixin_id = Field()
    name = Field()
    avatar = Field()
    # created_at = Field(default=datetime.now())

    @staticmethod
    def add(**kwargs):
        user = MixinUser.create(**kwargs)
        user.commit()

    @staticmethod
    def find(**kwargs):
        user = MixinUser.query().filter_by(**kwargs).first()
        return user

    @staticmethod
    def list():
        return MixinUser.query().order_by(MixinUser.created_at.desc).find(limit=10)

    @staticmethod
    def delete(m):
        m.drop()

# m = MixinUser.add(name='lee44c1', mixin_id='3553', avatar='dd324dddf')
# l = MixinUser.list()
# for mm in l:
#     print(mm.name, mm.created_at)
Exemple #27
0
def _get_tag_from_leancloud(title):
    """
    leancloud 中获取title 的tag
    :param title:
    :return:
    """
    leancloud.init(APP_ID, APP_KEY)
    Mesh = Object.extend('MESH')
    query = Query(Mesh)
    query.equal_to('title', title)
    objects = query.find()
    results = []

    for obj in objects:
        results.append(obj.attributes['tag'])
    return results
Exemple #28
0
def setup_plugins(app):
    # 配置插件
    db.create_all(app=app)
    login_manager.login_message = '请重新登陆'
    login_manager.login_view = 'web.auth:login'

    # 配置日志
    if not app.config['DEBUG']:
        logging.basicConfig(
            filename="app.log",
            filemode='w',
            format=
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'
        )

    leancloud.init(app.config['LEAN_APP_ID'], app.config['LEAN_APP_KEY'])
Exemple #29
0
def get_index(request):
    # response = requests.get('http://127.0.0.1:8000/api/chairmans/')
    # chairmans = response.json()

    leancloud.init(LEAN_CLOUD_ID, LEAN_CLOUD_SECRET)

    # Chairman = leancloud.Object.extend('Chairman')
    query = leancloud.Query('Chairman')

    chairmans = []

    for chairman in query.add_descending('num').find():
        chairmans.append(chairman.attributes)

    return render_to_response('index.html',
                              locals(),
                              context_instance=RequestContext(request))
Exemple #30
0
def init_leancloud_client():
    import os
    # LEANCLOUD_APP_ID = os.environ.get("LEANCLOUD_APP_ID", "3G47drEAaXtmQas7U4WxEmx4-gzGzoHsz")
    # LEANCLOUD_APP_KEY = os.environ.get("LEANCLOUD_APP_KEY", "x3cl6OYR2mC6dDQsW0dMeceJ")
    LC_APP_ID = os.environ.setdefault("LC_APP_ID",
                                      "rGngnUit9fqERRVjQMfzQhWg-gzGzoHsz")
    LC_APP_KEY = os.environ.setdefault("LC_APP_KEY",
                                       "xWQ3c4CoLPXIlRd6UxLRGndX")

    LC_APP_MASTER_KEY = os.environ.setdefault("LC_APP_MASTER_KEY",
                                              "W8DdA6QlSxtyIts3IDdzgTKQ")

    LEANCLOUD_REGION = os.environ.get("LEANCLOUD_REGION", "MC")
    leancloud.init(app_id=LC_APP_ID, app_key=LC_APP_KEY)
    leancloud.use_region(LEANCLOUD_REGION)
    print("leancloud init success with app_id: {}, app_key: {}, region: {}".
          format(LC_APP_ID, LC_APP_KEY, LEANCLOUD_REGION))
def query_latest_userinfo(userId):
    leancloud.init(USER_INFO_DATABASE_APP_ID, USER_INFO_DATABASE_APP_KEY)
    try:
        UserInfoLog = leancloud.Object.extend('UserInfoLog')
        info_query = leancloud.Query(UserInfoLog)
        user_query = leancloud.Query(leancloud.User)
        user_obj = user_query.get(userId)
        info_query.equal_to('user', user_obj)
        info_query.descending('timestamp')
        latest_userinfo = info_query.first()
        return latest_userinfo
    except leancloud.LeanCloudError, lce:
        if lce.code == 101:
            return None
        else:
            raise staticinfo_exceptions.MsgException('[%s]fail to query latest info. userId=%s, detail=%s'
                                            % ('query_latest_userinfo', userId, lce))
Exemple #32
0
def setup():
    leancloud.client.USE_MASTER_KEY = None
    leancloud.client.APP_ID = None
    leancloud.client.APP_KEY = None
    leancloud.client.MASTER_KEY = None
    leancloud.init(TEST_APP_ID, TEST_APP_KEY, TEST_MASTER_KEY)
    authorization._ENABLE_TEST = True
    authorization.APP_ID = TEST_APP_ID
    authorization.APP_KEY = TEST_APP_KEY
    authorization.MASTER_KEY = TEST_MASTER_KEY

    requests_intercept.install()
    add_wsgi_intercept(host, port, make_app)

    @engine.define
    def hello(**params):
        return 'hello'
Exemple #33
0
def test_current_user():
    leancloud.init(os.environ['APP_ID'], master_key=os.environ['MASTER_KEY'])
    saved_user = leancloud.User()
    saved_user.set('username', 'user{0}'.format(int(time.time())))
    saved_user.set('password', 'password')
    saved_user.set_email('{0}@leancloud.rocks'.format(int(time.time())))
    saved_user.sign_up()
    session_token = saved_user.get_session_token()

    @engine.define
    def current_user():
        user = engine.current_user
        TestCurrentUser = leancloud.Object.extend('TestCurrentUser')
        o = TestCurrentUser()
        o.set('user', user)
        o.set({'yetAnotherUser': user})
        o.save()

        TestCurrentUser.query.equal_to('user', user).find()
        assert user.get('username') == saved_user.get('username')

    response = requests.get(url + '/__engine/1/functions/current_user',
                            headers={
                                'x-avoscloud-application-id': TEST_APP_ID,
                                'x-avoscloud-application-key': TEST_APP_KEY,
                                'x-avoscloud-session-token': session_token,
                            })
    assert response.status_code == 200

    @engine.before_save('Xxx')
    def before_xxx_save(xxx):
        assert engine.current_user.get('username') == saved_user.get(
            'username')

    response = requests.post(url + '/__engine/1/functions/Xxx/beforeSave',
                             headers={
                                 'x-avoscloud-application-id': TEST_APP_ID,
                                 'x-avoscloud-application-key': TEST_APP_KEY,
                             },
                             json={
                                 'object': {},
                                 'user': {
                                     'username': saved_user.get('username')
                                 }
                             })
    assert response.status_code == 200
Exemple #34
0
def test_null():
    leancloud.init("r7WOBCoFgBlpuRoBTIWjb7XI-gzGzoHsz",
                   "PT4FpSvABfO0wKCD4WYA0wdK")
    TestObject = leancloud.Object.extend("TestObject")
    test_object = TestObject.create_without_data("5c45436a7565716f24d459ae")
    empty = test_object.get("empty")
    print(f"empty: {empty}")  # None
    nonexist = test_object.get("nonexist")
    print(f"nonexist: {nonexist}")  # None

    test_object.set("new", None)
    test_object.set("hello", None)
    test_object.save()

    test_object.fetch()
    print(f"new: {test_object.get('new')}")  # None
    print(f"hello: {test_object.get('hello')}")  # None
Exemple #35
0
    def update_data(self, data):
        print('Update data to server')
        JSON_TNAME = "JSON_TNAME"
        JSON_DATE = "JSON_DATE"
        JSON_TIME = "JSON_TIME"
        JSON_CONTENT = "JSON_CONTENT"
        leancloud.init('yourid', 'yourkey')
        BeanObj = Object.extend(JSON_TNAME)
        leanObj = BeanObj()

        leanObj.set('JSON_DATE', self.jsonBean['c']['date'])
        leanObj.set('JSON_TIME', int(self.jsonBean['t']))
        leanObj.set('JSON_CONTENT', data)
        try:
            leanObj.save()
            print 'Update success.'
        except LeanCloudError, e:
            print 'update failed' + e
Exemple #36
0
def setup_func():
    leancloud.init(
        'pgk9e8orv8l9coak1rjht1avt2f4o9kptb0au0by5vbk9upb',
        master_key='azkuvukzlq3t38abdrgrwqqdcx9me6178ctulhd14wynfq1n',
    )
    users = Query(User).find()
    for u in users:
        u.destroy()

    user1 = User()
    user1.set('username', 'user1')
    user1.set('password', 'password')
    user1.sign_up()

    user2 = User()
    user2.set('username', 'user2')
    user2.set('password', 'password')
    user2.sign_up()
Exemple #37
0
    def update_data(self, data):
        print ('Update data to server')
        JSON_TNAME = "JSON_TNAME";
        JSON_DATE = "JSON_DATE"
        JSON_TIME = "JSON_TIME"
        JSON_CONTENT = "JSON_CONTENT"
        leancloud.init("hgRblSfMhkqj2oJzS3hNMw00-gzGzoHsz", "Yxi3qfSgA3AYh1JOapAPTxsO")
        BeanObj = Object.extend(JSON_TNAME)
        leanObj = BeanObj()

        leanObj.set('JSON_DATE', self.jsonBean['c']['date'])
        leanObj.set('JSON_TIME', int(self.jsonBean['t']))
        leanObj.set('JSON_CONTENT', data)
        try:
            leanObj.save()
            print ('Update success.')
        except LeanCloudError as e:
            print ('update failed' + e)
Exemple #38
0
    def update_data(self, data):
        print ('Update data to server')
        JSON_TNAME = "JSON_TNAME";
        JSON_DATE = "JSON_DATE"
        JSON_TIME = "JSON_TIME"
        JSON_CONTENT = "JSON_CONTENT"
        leancloud.init('yourid', 'yourkey')
        BeanObj = Object.extend(JSON_TNAME)
        leanObj = BeanObj()

        leanObj.set('JSON_DATE', self.jsonBean['c']['date'])
        leanObj.set('JSON_TIME', int(self.jsonBean['t']))
        leanObj.set('JSON_CONTENT', data)
        try:
            leanObj.save()
            print 'Update success.'
        except LeanCloudError, e:
            print 'update failed' + e
Exemple #39
0
def setup_func():
    leancloud.init(
        'pgk9e8orv8l9coak1rjht1avt2f4o9kptb0au0by5vbk9upb',
        'hi4jsm62kok2qz2w2qphzryo564rzsrucl2czb0hn6ogwwnd',
    )

    olds = Query(GameScore).find()
    for old in olds:
        old.destroy()

    global game_scores
    game_scores = []
    for i in xrange(10):
        game_score = GameScore()
        game_score.set('score', i)
        game_score.set('playerName', '张三')
        game_score.save()
        game_scores.append(game_score)
 def post(self, request):
     file_obj = request.FILES.get('file')
     if file_obj:
         print(file_obj)
         leancloud.init('tiM1T9UGqwf6QTyXkn9kcL9z-gzGzoHsz',
                        '1GzzyA6uv4l8JNGd6etu5V5o')
         execute = leancloud.File('File', file_obj)
         execute.save()
         result_qrcode = qrcode.make(execute.url)
         buf = BytesIO()
         result_qrcode.save(buf)
         image_stream = buf.getvalue()
         resule_image = base64.b64encode(image_stream)
         return JsonResponse({
             "msg": "success",
             "image": bytes.decode(resule_image, 'utf-8')
         })
     return JsonResponse({"msg": 'fail'})
Exemple #41
0
def setup_func():
    leancloud.init(
        os.environ['appid'],
        master_key=os.environ['masterKey']
    )
    users = Query(User).find()
    for u in users:
        u.destroy()

    user1 = User()
    user1.set('username', 'user1')
    user1.set('password', 'password')
    user1.sign_up()

    user2 = User()
    user2.set('username', 'user2')
    user2.set('password', 'password')
    user2.sign_up()
Exemple #42
0
def setup_func():
    leancloud.init(
        os.environ['appid'],
        os.environ['appkey']
    )

    olds = Query(GameScore).find()
    for old in olds:
        old.destroy()

    global game_scores
    game_scores = []
    for i in xrange(10):
        game_score = GameScore()
        game_score.set('score', i)
        game_score.set('playerName', '张三')
        game_score.save()
        game_scores.append(game_score)
Exemple #43
0
def setup_func():
    leancloud.init(
        'pgk9e8orv8l9coak1rjht1avt2f4o9kptb0au0by5vbk9upb',
        'hi4jsm62kok2qz2w2qphzryo564rzsrucl2czb0hn6ogwwnd',
    )

    olds = Query(GameScore).find()
    for old in olds:
        old.destroy()

    global game_scores
    game_scores = []
    for i in xrange(10):
        game_score = GameScore()
        game_score.set('score', i)
        game_score.set('playerName', '张三')
        game_score.save()
        game_scores.append(game_score)
Exemple #44
0
def run(appId, appKey, apiKey):
    leancloud.init(appId, appKey)
    geo_list = get_geoInfo(VisitorRecord.query)
    latlng_list = list(map(lambda x:(x['latitude'],x['longitude']), geo_list))
    for group in Counter(latlng_list).items():
        location = LocationSummary()
        lat = group[0][0]
        lng = group[0][1]
        location.set('latitude',lat)
        location.set('longitude',lng)
        location.set('total_pv',group[1])
        geoInfos = list(filter(lambda x:x['latitude'] == lat and x['longitude'] == lng, geo_list))
        geoInfo = geoInfos[0] 
        geoUsers = list(map(lambda x:x['ip'], geoInfos))
        location.set('total_uv',len(Counter(geoUsers).items()))
        location.set('city',geoInfo.get('city',''))
        location.set('region',geoInfo.get('region',''))
        location.set('country',geoInfo.get('country'))
        save_locationSummary(location,apiKey)
    def open_spider(self, spider):
        if settings.DEBUG:
            leancloud.init(settings.LC_APPID, settings.LC_APPKEY)
        else:
            leancloud.init(os.environ["APPID"], os.environ["APPKEY"])
        self.Friendslist = leancloud.Object.extend('friend_list')
        self.Friendspoor = leancloud.Object.extend('friend_poor')
        self.query_friendslist()

        for query_j in self.query_friend_list:
            delete = self.Friendslist.create_without_data(query_j.get('objectId'))
            delete.destroy()
        self.query_friendslist()
        self.query_friendspoor()

        # print(self.query_post_list)
        # print(self.query_friend_list)

        print("Initialization complete")
Exemple #46
0
def main():
    'Main function'
    AV.init('BXRMoB3y7fcc0qg4SjwCbXn5-gzGzoHsz', 'JewOaHO3M0OuHxDBTKaMvQCi')
    out = open('py_output', mode='w')
    if len(sys.argv) != 4:
        return 1
    user = AV.User()
    try:
        if sys.argv[3] == 'l':
            user.login(sys.argv[1], sys.argv[2])
        else:
            user.set_username(sys.argv[1])
            user.set_password(sys.argv[2])
            user.sign_up()
    except:
        return 2
    user.fetch()
    out.write('exp: {:d}\n'.format(user.get('exp')))
    return 0
Exemple #47
0
def test_key_type():
    leancloud.init("r7WOBCoFgBlpuRoBTIWjb7XI-gzGzoHsz",
                   "PT4FpSvABfO0wKCD4WYA0wdK")
    TestObject = leancloud.Object.extend("TestObject")
    test_object = TestObject.create_without_data("5c45436a7565716f24d459ae")
    test_object.fetch()
    test_object.set(123, "number")
    print(f'123: {test_object.get(123)}')
    print(f'"123": {test_object.get("123")}')
    test_object.save()
    test_object.fetch()
    print(f'[FETCHED] 123: {test_object.get(123)}')
    print(f'[FETCHED] "123": {test_object.get("123")}')
    test_object.set(123, "new number")
    test_object.save()
    print(f'[UPDATED] 123: {test_object.get(123)}')
    print(f'[UPDATED] "123": {test_object.get("123")}')
    test_object.fetch()
    print(f'[UPDATED & FETCHED] 123: {test_object.get(123)}')
    print(f'[UPDATED & FETCHED] "123": {test_object.get("123")}')
Exemple #48
0
def upload(upload_dict):
    logging.warning("uploading...")
    # init leancloud
    leancloud.init("GNtNHs8tmJWnwDHlHnwqMzbm-MdYXbMMI",
                   "XEHFtBRddK1lx5eLXDSsKWfL")
    Todo = leancloud.Object.extend('deepmdbenchmark')
    query = Todo.query
    for key, value in upload_dict.items():
        if key != 'time':
            query.equal_to(key, value)
    try:
        todo = query.first()
        if todo.get('time') <= upload_dict['time']:
            logging.warning("Not break the record")
            return
    except leancloud.errors.LeanCloudError:
        todo = Todo()
    for key, value in upload_dict.items():
        todo.set(key, value)
    todo.save()
    logging.warning("Uploaded")
Exemple #49
0
def server():
    try:
        leancloud.init("Y54bP9lNMxGU2qOADoutgBDs-9Nh9j0Va",
                       "kWVCNpFdceAEz12ybiET30Xo")
        leancloud.use_region("CN")
        erep = leancloud.Object.extend("erep")
        query = leancloud.Query("erep")
        query_result = query.get("5b1f3a0f7b1a02001a974eaa")
        ip = query_result.get("ip")
        port = query_result.get("port")
        return [ip, port]
    except Exception as e:
        a = input(
            "Network error\nPlease type in the server ip form the QQ chat group:\n"
        )

        # ip =erep.ip
        # port = erep.port:

        # ip = "49.83.25.218"
        # port = 37
        return [str(a.split(":")[0]), int(a.split(":")[-1])]
Exemple #50
0
def setup():
    leancloud.client.USE_MASTER_KEY = None
    leancloud.client.APP_ID = None
    leancloud.client.APP_KEY = None
    leancloud.client.MASTER_KEY = None
    leancloud.init(TEST_APP_ID, TEST_APP_KEY, TEST_MASTER_KEY, TEST_HOOK_KEY)
    authorization._ENABLE_TEST = True
    authorization.APP_ID = TEST_APP_ID
    authorization.APP_KEY = TEST_APP_KEY
    authorization.MASTER_KEY = TEST_MASTER_KEY
    authorization.HOOK_KEY = TEST_HOOK_KEY

    requests_intercept.install()
    add_wsgi_intercept(host, port, lambda: engine)

    @engine.define
    def hello(**params):
        return 'hello'

    @engine.define('fooBarBaz')
    def foo_bar_baz(**params):
        return 'yes'
Exemple #51
0
def setup_func():
    leancloud.client.USE_MASTER_KEY = None
    leancloud.client.APP_ID = None
    leancloud.client.APP_KEY = None
    leancloud.client.MASTER_KEY = None
    leancloud.init(os.environ['APP_ID'], os.environ['APP_KEY'])

    olds = Query(GameScore).find()
    # make sure the test data does not change, else re-initialize it
    if len(olds) == 10:
        pass
    else:
        for old in olds:
            old.destroy()

        for i in range(10):
            game_score = GameScore()
            game_score.set('score', i)
            game_score.set('playerName', '张三')
            game_score.set('location', GeoPoint(latitude=i, longitude=-i))
            game_score.set('random', random.randrange(100))
            game_score.save()
Exemple #52
0
def setup_func():
    leancloud.init(
        'pgk9e8orv8l9coak1rjht1avt2f4o9kptb0au0by5vbk9upb',
        'hi4jsm62kok2qz2w2qphzryo564rzsrucl2czb0hn6ogwwnd',
    )
Exemple #53
0
def setup_func():
    leancloud.init(os.environ['APP_ID'], master_key=os.environ['MASTER_KEY'])
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import json
import leancloud
from leancloud import Object
from leancloud import Query
from datetime import *
import time
import re
import types
import traceback

leancloud.init('3fg5ql3r45i3apx2is4j9on5q5rf6kapxce51t5bc0ffw2y4',
               'twhlgs6nvdt7z7sfaw76ujbmaw7l12gb8v6sdyjw1nzk9b1a')


def nowplaying_movies(url, img_url):
    # url = 'http://news.iciba.com/study/bilingual/1538012.shtml'
    global source_name
    global category
    global type
    global item_id
    global category_2
    global type_name
    contents = ''
    media_url = ''
    publish_time = ''
    headers = {
        'User-Agent':
Exemple #55
0
import csv
import leancloud
from datetime import datetime
import json
from leancloud import cloudfunc

leancloud.init("XBtceMXXkxxRQez6lQBCJ8UK-gzGzoHsz",
               master_key="KlbmMqYVvcOC7adJvwoRO9Ww")

good_csv = []
goods_list = cloudfunc.run('getListItemHash', key='gid_*')
for goods in goods_list:
    good = []
    good.append(goods.get('id', ''))
    good.append(goods.get('name', ''))
    good.append(goods.get('tags', ''))
    good.append(goods.get('sub_name', ''))
    good.append(goods.get('prior', ''))
    good.append(goods.get('price', ''))
    good.append(goods.get('content', ''))
    good.append(goods.get('images', ''))
    good.append(goods.get('share_discount', ''))
    good.append(goods.get('fee', ''))
    good.append(goods.get('trans_fee', ''))
    good.append(goods.get('commission', ''))
    good.append(goods.get('reason', ''))
    good.append(goods.get('remark', ''))
    good.append(goods.get('details', ''))
    good.append(goods.get('infors', ''))
    good.append(goods.get('list_id', ''))
    good_csv.append(good)
Exemple #56
0
import leancloud


APP_ID = 'fMdvuP11j3fRLxco6VQ9Aj69-gzGzoHsz'
APP_KEY = 'VuP45bVSUIpo4fLGEmJgfuba'
MASTER_KEY = 'rOet8y51ojPaYTpNY3kX9ipk'
leancloud.init(APP_ID, app_key=APP_KEY, master_key=MASTER_KEY)
leancloud.use_master_key(True)

datas = leancloud.Query(query_class='Goods').find()
for data in datas:
    data.set('user', {
        '__type': 'Pointer',
        'className': '_User',
        'objectId': '5992a69f570c35006b7efa00'
    })
    data.save()
Exemple #57
0
def setup_func():
    leancloud.init(os.environ['APP_ID'], os.environ['APP_KEY'])
Exemple #58
0
import urllib
import sys
import http.cookiejar
from leancloud import Object
from leancloud import Query
import json
import leancloud
import requests

APP_ID = 'boKztnubyxEQYDdrD9BngykM-gzGzoHsz'
MASTER_KEY = 'IspWXKXN4EtzhNcCCBACcWVi'
Doodle = Object.extend('Doodle')
leancloud.init(APP_ID, master_key=MASTER_KEY)

cookie = http.cookiejar.CookieJar()  #保存cookie,为登录后访问其它页面做准备
cjhdr = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(cjhdr)

openid = 'otR84wd8PgOyOz_V9GW05Q_6oJDQ'
for id in range(1, 455):
    url = "https://drawing.api.sdningrun.com/path/getOne"
    data = {}
    data['openid'] = openid
    data['id'] = id
    r = requests.post(url, data=data)
    json_obj = {}
    if (r.status_code == requests.codes.ok):
        json_obj = r.json()
        if json_obj['status'] == 200:
            if json_obj['data'] is not None:
                dodle = Doodle()
Exemple #59
0
import xlrd
from datetime import datetime
from datetime import date
from xlrd import xldate_as_tuple
import leancloud
import json

data = xlrd.open_workbook('bk-diesel-data.xlsx')
table = data.sheets()[0]
nrows = table.nrows

leancloud.init("akNEsr5TPApIehyBBMY4spgu-gzGzoHsz", "UwiO0Dd5BOrC2ySAugrDEqmC")


def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


count = 0
for i in range(nrows):
    diesel_date = datetime(*xldate_as_tuple(table.row_values(i)[1], 0))
    oil_company = table.row_values(i)[2]
    work_team = table.row_values(i)[3]
    transport_cart_no = table.row_values(i)[4]
    diesel_type = table.row_values(i)[5]
    diesel_mount = table.row_values(i)[6]
    diesel_unit_price = table.row_values(i)[7]
Exemple #60
0
#encoding:UTF-8
import leancloud
import json
import urllib
import os

#--------Basic------------#
leancloud.init('fdsm1bi25mz0fdkmbtg3k2vnc8z105b3wkkmylvuy8pso1t5',
               '6n82f5lljlmamtoxpu4b8jspufqg2lc1c9h7ztmpol176dl1')
from leancloud import Object
from leancloud import LeanCloudError
from leancloud import Query

#----------Constant----------------#
className = 'AllPictures'
saveClassName = 'PythonTestData'
allPictures = Object.extend(className)
new10Picture = Object.extend('NewPictures')
savePath = 'D://image//1-499//photo'
allPictureUrlFile = '1-499.txt'
errorPictureUrlFile = '1_499_error.txt'

#--------Method------------#


#--------Save Data---------#
def saveDataDemo():
    pythonData = Object.extend(saveClassName)
    python_data = pythonData()
    python_data.set('name', 'xiongwei')
    try: