Ejemplo n.º 1
0
def todo(id):
    if request.method == 'GET':
        try:
            todo = Query(Todo).get(id)
            return jsonify(todo.dump()), 200, AccessControl
        except:
            abort(404)
    elif request.method == 'PUT':
        try:
            todo = Query(Todo).get(id)
            title = request.form.get('title')
            todo.set('title', title)
            todo.save()
            return jsonify(todo.dump()), 200, AccessControl
        except:
            abort(404)
    elif request.method == 'DELETE':
        try:
            todo = Query(Todo).get(id)
            todo.destroy()
            return jsonify({}), 204, AccessControl
        except:
            abort(404)
    elif request.method == 'OPTIONS':
        return 'ok', 200, AccessControl
Ejemplo n.º 2
0
def test_query_include_acl():
    with_acl = Query(GameScore).include_acl(True).first()
    assert with_acl.get_acl() is not None
    explicit_without_acl = Query(GameScore).include_acl(False).first()
    assert explicit_without_acl.get_acl() is None
    implicit_without_acl = Query(GameScore).first()
    assert implicit_without_acl.get_acl() is None
Ejemplo n.º 3
0
def showApi():
    """给前端提供api接口
        id -> 提供id页的日记,每页50条日记
        user_id -> 提供该user_id的所有日记
    """
    id = int(request.args.get('id', 1))
    user_id = int(request.args.get('user_id', 0))
    try:
        # 如果没有提供user_id,即user_id为0
        if user_id is 0:
            posts = Query(Tian).ascending('post_no').limit(50).skip(50*(id-1)).find()
        else:
            posts = Query(Tian).equal_to('user_id', user_id).limit(500).find()
        code = 200
    except LeanCloudError as e:
        posts = []
        code = '500' + str(e.code)
    data = {
        'code': code,
        'results': [post.dump() for post in posts]
    }
    res = make_response(jsonify(data))
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Method'] = 'POST'
    return res
Ejemplo n.º 4
0
def getYesterdayKDJ(rlist):
	cyStockData = Object.extend('CYStockData')
	query = Query(cyStockData)  
	query.equal_to('kdjback', 1)
	query.greater_than('kdj',0)
	query.equal_to('volume',1)
	cyresults = query.find()
	for x in cyresults:		
		rlist.append(x.get("stcode"))
	szStockData = Object.extend('SZStockData')
	query = Query(szStockData)  
	query.equal_to('kdjback', 1)
	query.greater_than('kdj',0)
	query.equal_to('volume',1)
	szresults = query.find()
	for x in szresults:
		rlist.append(x.get("stcode"))
	shStockData = Object.extend('SHStockData')
	query = Query(shStockData)  
	query.equal_to('kdjback', 1)
	query.greater_than('kdj',0)
	query.equal_to('volume',1)
	shresults = query.find()
	for x in shresults:
		rlist.append(x.get("stcode"))
Ejemplo n.º 5
0
def test_or_and_query(): # type: () -> None
    q1 = Query(GameScore).greater_than('score', 5)
    q2 = Query(GameScore).less_than('score', 10)
    q3 = Query(GameScore).equal_to('playerName', 'foobar')

    q = Query.and_(q1, q2, q3)
    assert q.dump() == {'where': {'$and': [{'score': {'$gt': 5}}, {'score': {'$lt': 10}}, {'playerName': 'foobar'}]}}

    q = Query.or_(q1, q2, q3)
    assert q.dump() == {'where': {'$or': [{'score': {'$gt': 5}}, {'score': {'$lt': 10}}, {'playerName': 'foobar'}]}}
Ejemplo n.º 6
0
 def login_with_email(cls, email, password):
     try:
         username = Query(cls).equal_to('email', email).first().get('username')
         u = user.User(username=username, password=password)
         u.login()
     except LeanCloudError as e:
         print e.message
         return None
     else:
         return Query(cls).equal_to('username', username).first()
Ejemplo n.º 7
0
def get(article_id):
    try:
        article = Query(Article).get(article_id)
        comment_list = Query(Comment).equal_to("article", article).descending("createdAt").find()
        comments = map(lambda comment: {
            "username": comment.get("username"),
            "content": comment.get("content"),
            "date": comment.get("date"),
            "id": comment.id
        }, comment_list)
    except LeanCloudError, e:
        raise e
Ejemplo n.º 8
0
def show():
    try:
        topics = Query(Topic).descending('reply').limit(200).find()
        rank_posts = Query(Rank).descending('post_count').limit(100).find()
        rankReply = Query(Rank).descending('reply_count').limit(50).find()
    except LeanCloudError, e:
        if e.code == 101:
            topics = []
            rank_posts = []
            rankReply = []
        else:
            raise e
Ejemplo n.º 9
0
def test_multiple_order():
    MultipleOrderObject = leancloud.Object.extend('MultipleOrderObject')
    for obj in Query(MultipleOrderObject).find():
        obj.destroy()
    MultipleOrderObject(a=1, b=10).save()
    MultipleOrderObject(a=10, b=20).save()
    MultipleOrderObject(a=1, b=3).save()
    q = Query(MultipleOrderObject)
    q.add_descending('a')
    q.add_descending('b')
    r = q.find()
    for i in range(1, len(r)):
        assert r[i - 1].get('a') >= r[i].get('a')
        assert r[i - 1].get('b') >= r[i].get('b')
Ejemplo n.º 10
0
def test_multiple_order():  # type: () -> None
    MultipleOrderObject = leancloud.Object.extend("MultipleOrderObject")
    for obj in Query(MultipleOrderObject).find():
        obj.destroy()
    MultipleOrderObject(a=1, b=10).save()
    MultipleOrderObject(a=10, b=20).save()
    MultipleOrderObject(a=1, b=3).save()
    q = Query(MultipleOrderObject)
    q.add_descending("a")
    q.add_descending("b")
    r = q.find()
    for i in range(1, len(r)):
        assert r[i - 1].get("a") >= r[i].get("a")
        assert r[i - 1].get("b") >= r[i].get("b")
Ejemplo n.º 11
0
def _receiversOffline(**params):
    print('_receiversOffline start')
    print(params)

    conversation_id = params['convId']
    query = Query("_Conversation")
    conversation = query.get(conversation_id)
    # if it is system notification skip
    if conversation.get('sys') == True:
        print "system notification, skip pushMessage"
        print('_receiversOffline end')
        return {'skip': True}
    else:
        from_peer = params['fromPeer']
        short_content = ""
        query = Query("_User")
        query.equal_to('username', from_peer)
        query_list = query.find()
        if len(query_list) > 0:
            short_content = query_list[0].get('nickname') + ": "

        content = params['content']
        mediaType = content[content.find('_lctype') +
                            9:content.find('_lctype') + 11]
        if mediaType == "-1":
            short_content += content[content.find('_lctext') +
                                     10:content.find('_lcattrs') - 3]
        elif mediaType == "-2":
            short_content += "[图片]"
        elif mediaType == "-3":
            short_content += "[语音信息]"
        elif mediaType == "-4":
            short_content += "[视频信息]"
        elif mediaType == "-5":
            short_content += "[位置]"
        elif mediaType == "-6":
            short_content += "[文件]"
        print('short_content:', short_content)
        payloads = {
            # 自增未读消息的数目,不想自增就设为数字
            'badge': 'Increment',
            'sound': 'default',
            # 使用开发证书
            '_profile': 'prod',
            'alert': short_content,
        }
        print('_receiversOffline end')
        return {
            'pushMessage': json.dumps(payloads),
        }
Ejemplo n.º 12
0
Archivo: app.py Proyecto: Panmax/bbzai
def j_hello():
    result = {
        'playing': False
    }
    q1 = Query(PlayingUser).equal_to('user1', current_user)
    q2 = Query(PlayingUser).equal_to('user2', current_user)
    try:
        playing = Query(PlayingUser).or_(q1, q2).first()
        result['playing'] = True
        actions = playing.actions
        result['actions'] = actions[:-1]
    except:
        pass

    return json.dumps(result)
Ejemplo n.º 13
0
def pic(message):
    cmd, text = parse_cmd_text(message.text)
    url = None
    base_url = 'http://7xqh4i.com1.z0.glb.clouddn.com/pic'
    if text != None:
        url = base_url + str(text)
        pic_num = text
    else:
        query = Query(Pic)
        pics = query.find()
        bolcks = [pic.get('pid') for pic in pics]
        pic_num = None
        size_of_images = 330  # 0~size_of_images
        while pic_num == None or str(pic_num) in bolcks:
            pic_num = random.randint(0, size_of_images)
        url = base_url + str(pic_num)
    bot.sendChatAction(chat_id=message.chat.id,
                       action=telegram.ChatAction.UPLOAD_PHOTO)

    def send_photo_task():
        bot.sendPhoto(chat_id=message.chat.id,
                      photo=url + '.jpg',
                      caption=pic_num)

    t = threading.Thread(target=send_photo_task)
    t.start()
Ejemplo n.º 14
0
def queryOneDataByPosition(position):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    if len(pictures) > 0:
        return pictures[0].get('image_src')
    return ""
Ejemplo n.º 15
0
def is_exit(str):
    global category
    query = Query('Reading')
    query.equal_to('title', str)
    query.equal_to('category', category)
    querys = query.find()
    return len(querys) > 0
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
def changeServerFileName(position, newName):
    query = Query(allPictures)
    query.equal_to('position', position)
    pictures = query.find()
    pictureSelect = pictures[0]
    pictureSelect.set('image_src', newName)
    pictureSelect.save()
Ejemplo n.º 18
0
def result_index(index):
    print 'get result from index', index
    try:
        query = Query(DeviceKey)
        query.equal_to('index', index)
        devicekey = query.first()
        device_name = devicekey.get('name_cn')
        key = devicekey.id
    except:
        return jsonify(error='invalid index')
    try:
        data = get_latest(key)
        hour = data.created_at.hour + 8
        ch2o = data.get('ch2o')
        if ch2o == 65535:
            ch2o = 0
        ch2o = round(ch2o * 1.32 / 1000, 2)
        data.set('ch2o', ch2o)
    except:
        return jsonify(error='invalid key')
    try:
        local_time = utc2local(data.created_at)
    except:
        print 'local time change error'
        local_time = data.created_a
    #pm =average_pm(24,key)
    pm = min_pm(key)
    noise = min_noise(key)
    return render_template('result.html',
                           esp_test=data,
                           local_time=local_time,
                           pm=pm,
                           noise=noise,
                           index=index,
                           device_name=device_name)
Ejemplo n.º 19
0
def show(year, month):
    month = float(month)
    start, end = get_month_id(year, month), get_month_id(year, month + 0.5)
    if end is None:
        end = 1e10
    if start is None:
        abort(404)
    chinese_num = dict(enumerate(u'一二三四五六七八九', start=1))
    chinese_num.update({10: '十', 11: '十一', 12: '十二'})
    chinese_month = chinese_num.get(int(month))
    if float(month) > int(month):
        chinese_month += u'月份下'
    else:
        chinese_month += u'月份上'
    try:
        topics = Query(Topic).less_than("pid", end).greater_than('pid', start)
        top_topics = topics.descending('reply_num').limit(20).find()
        users = [
            topic.get('author_name') for topic in topics.limit(800).find()
        ]
        users.extend(
            topic.get('author_name')
            for topic in topics.limit(800).skip(800).find())
        counter = collections.Counter(users).most_common(20)
    except LeanCloudError, e:
        if e.code == 101:
            topics = []
        else:
            raise e
Ejemplo n.º 20
0
def tuchuang_callback():
    code = request.args.get('code')
    if not code:
        abort(404)

    url = 'https://github.com/login/oauth/access_token'
    config = current_app.config
    params = {
        'client_id': config.get('client_id'),
        'client_secret': config.get('client_secret'),
        'code': code,
    }
    result = requests.get(url, params, headers={'Accept': 'application/json'})
    data = result.json()
    params = {"access_token": data.get('access_token')}
    result = requests.get('https://api.github.com/user', params)

    github_user = result.json()
    current_app.logger.debug('result: %s' % github_user)

    try:
        query = Query(GitHubUser)
        user = query.equal_to('email', github_user.get('email')).first()

        session['user'] = leanobject_to_dict(user)
        flash(u'欢迎回来!', category='success')
        return redirect(url_for('.tuchuang_index', result=result.text))
    except LeanCloudError as e:
        _register(github_user)
        flash(u'恭喜你注册成功,请填写七牛资料', category='success')
        return redirect(url_for('.info'))
Ejemplo n.º 21
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()
Ejemplo n.º 22
0
def dislike(**params):
    card_id = params['cid']
    user_id = params['uid']
    card = Card.create_without_data(card_id)
    user = User.create_without_data(user_id)
    query = Query(Like)
    query.equal_to('card', card)
    query.equal_to('user', user)
    count = query.count()

    if count > 0:
        try:
            likes = query.first()
            likes.destroy()

            card.increment('likes', -1)
            card.fetch_when_save = True
            card.save()
            return {'code': 200, 'message': 'ok'}
        except LeanCloudError as e:
            result = {'code': e.code, 'message': e.error}
            return result
    else:
        result = {'code': 400, 'message': '点赞记录不存在'}
        return result
Ejemplo n.º 23
0
def delete(**params):
    if 'cid' not in params:
        return {'code': 301, 'message': '参数错误:卡片ID不存在'}
    if 'uid' not in params:
        return {'code': 302, 'message': '参数错误:用户ID不存在'}
    card_id = params['cid']
    user_id = params['uid']
    try:
        query = Query(Card)
        query.include('user')
        card = query.get(card_id)
        if card is not None:
            user = card.get('user')
            if user.get('objectId') == user_id:
                _card = Card.create_without_data(card_id)
                _card.set('hidden', True)
                _card.save()
                return {'code': 200, 'message': 'ok'}
            else:
                result = {'code': 401, 'message': '没有权限'}
                return result
        else:
            result = {'code': 400, 'message': '卡片不存在'}
            return result
    except LeanCloudError as e:
        result = {'code': e.code, 'message': e.error}
        return result
Ejemplo n.º 24
0
def is_exit(name, url):
    query = Query('Caricature')
    query.equal_to('name', name)
    query.equal_to('url', url)
    querys = query.find()

    return len(querys) > 0
Ejemplo n.º 25
0
def test_pointer_query():  # type: () -> None
    foo = Object.create("Foo")
    bar = Object.create("Bar")
    bar.save()
    foo.set("bar", bar)
    foo.save()

    q = Query("Foo").equal_to("bar", bar)
    assert len(q.find()) == 1

    inner_query = leancloud.Query("Post")
    inner_query.exists("image")
    query = leancloud.Query("Comment")
    query.matches_query("post", inner_query)
    assert query.dump() == {
        "where": {
            "post": {
                "$inQuery": {
                    "className": "Post",
                    "where": {
                        "image": {
                            "$exists": True
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 26
0
def query_proxy_item():
    proxy_list = []
    query = Query(Proxy_Item)
    for i in query.find():
        if isinstance(i, Proxy_Item):
            proxy_list.append(i)
    return proxy_list
Ejemplo n.º 27
0
def alias_filter(message):
    text = message.text
    query = Query(Alias)
    alises = query.find()
    if len(alises) == 0:
        return
    catch = False
    aliases_dict = {x.get('key'): x.get('value') for x in alises}
    keys = [x.get('key') for x in alises]
    # make the longer key be replaced first
    matches = sorted(re.findall('|'.join(keys), text),
                     key=lambda x: len(x),
                     reverse=True)
    if len(matches) > 0:
        catch = True
    if len(matches) == 1:
        if aliases_dict.get(matches[0]) == ('@' + message.from_user.username):
            return
    for m in matches:
        if '@' in aliases_dict.get(m):
            prefix = ' '
            if (prefix + m) in text:
                text = text.replace(m, aliases_dict.get(m) + ' ')
            else:
                text = text.replace(m, prefix + aliases_dict.get(m) + ' ')
        else:
            text = text.replace(m, aliases_dict.get(m))

    if catch == True:
        text = get_nickname(message.from_user) + ': ' + text
        bot.sendMessage(chat_id=message.chat.id, text=text)
Ejemplo n.º 28
0
def test_pointer_query():
    foo = Object.create('Foo')
    bar = Object.create('Bar')
    bar.save()
    foo.set('bar', bar)
    foo.save()

    q = Query('Foo').equal_to('bar', bar)
    assert len(q.find()) == 1

    inner_query = leancloud.Query('Post')
    inner_query.exists("image")
    query = leancloud.Query('Comment')
    query.matches_query("post", inner_query)
    assert query.dump() == {
        'where': {
            'post': {
                '$inQuery': {
                    'className': 'Post',
                    'where': {
                        'image': {
                            '$exists': True
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 29
0
    def process_sj_range(item):
        code = item['code'].strip()
        if not code:
            return
        data = {
            'page_num': int(item['page_num']),
            'code': code,
            'type': 'sj',
            'subject': item['subject']
        }

        query = Query(Range)
        query.equal_to('code', code)
        query.equal_to('type', 'sj')
        try:
            one = query.first()
        except LeanCloudError:
            one = Range()
            last_page_num = 0
            one.set('state', 0)
        else:
            last_page_num = one.get('page_num')
            if last_page_num != data['page_num']:
                one.set('state', 0)
            else:
                one.set('state', 1)
        for k, v in data.items():
            one.set(k, v)
        one.set('last_page_num', last_page_num)
        one.save()
        return item
Ejemplo n.º 30
0
def is_exit(url):
    global category
    query = Query('Reading')
    query.equal_to('category', category)
    query.equal_to('source_url', url)
    querys = query.find()
    return len(querys) > 0