<untitled> (Python)

Ревизии: current

text/plain
text/html
source
Old rev.:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       api1.py
#      
#       PyVkApi
#       Copyright 2010 * <*@*>
#      
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#      
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#      
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

#Оценка объема работ

#Реализация методов API                        12.5%       3   9
#Тестирование методов                        37.5%       9   27
#Реализация авторизации                        4.1(6)%     1   3
#Поддержка fields                          4.1(6)%     1   3
#Остальное тестирование                        4.1(6)%     1   3
#Рефакторинг                             25%         6   18
#Документация                               12.5%       3   9

#Статус:
#
##################### ВСЕГО ############################################

import pycurl, hashlib, urllib, json, pycurl

global api_url
api_url = 'http://api.vkontakte.ru/api.php'
global init_params
init_params = {'api_id' : '1896263',
            'layout' : 'popup',
            'type' : 'browser',
            'v' : '3.0',
            'format' : 'JSON'}
           
class Response(object):
    content = ""
    def add_data(self, buf):
        self.content = self.content + buf

class ApiError(Exception):
    pass

class MethodError(ApiError):
    def __init__(self, error_code, error_msg):
        self.error_code = error_code
        self.error_msg = error_msg
       
    def __str__(self):
        return repr(self.error_msg)
   
def create_sig(method_params):
    params = {}
    params['api_id'] = init_params['api_id']
    params['format'] = init_params['format']
    params['v'] = init_params['v']
    params.update(method_params)
    params_keys_sorted = params.keys()
    params_keys_sorted.sort()
    sig_obj = str(session['mid'])
    for param in params_keys_sorted:
        sig_obj += param + '=' + params[param]
    sig_obj += session['secret']
    #md5 = hashlib.md5(sig_obj)
    #sig = md5.hexdigest()
    sig = hashlib.md5(sig_obj).hexdigest()
    return sig

def compose_url(method_params):
    sig = create_sig(method_params)
    url_params = {}
    url_params['api_id'] = init_params['api_id']
    url_params['sig'] = sig
    url_params['v'] = init_params['v']
    url_params['format'] = init_params['format']
    url_params['sid'] = session['sid']
    url_params.update(method_params)
    url = api_url + '?' + urllib.urlencode(url_params)
    return url

def vk_method(method_params):
    url = compose_url(method_params)
    resp = Response()
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.WRITEFUNCTION, resp.add_data)
    c.setopt(c.COOKIE, browser["cookie"])
    c.setopt(c.USERAGENT, browser["useragent"])
    c.perform()
    c.close()
    resp_data = json.loads(resp.content)
    if resp_data.has_key("response"):
        return resp_data["response"]
    if resp_data.has_key("error"):
        raise MethodError(int(resp_data["error"]["error_code"]), resp_data["error"]["error_msg"])

############### API Methods ############################################

#Users

def isAppUser(uid=None):
    method_params = {}
    method_params['method'] = 'isAppUser'
    if uid != None:
        method_params['uid'] = str(uid)
    return bool(vk_method(method_params))

#not_full
def getProfiles(uids, domains=None, fields=None, name_case='nom'):
    method_params = {}
    method_params['method'] = 'getProfiles'
    uids_str = ""
    for uid in uids:
        uids_str += str(uid) + ','
    uids_str = uids_str[:-1]
    method_params['uids'] = uids_str
    method_params['name_case'] = name_case
   
    return compose_url(method_params)
   
def getUserBalance():
    method_params = {}
    method_params['method'] = 'getUserBalance'
    return int(vk_method(method_params))

def getUserSettings():
    method_params = {}
    method_params['method'] = 'getUserSettings'
    return vk_method(method_params)
   
def getGroups():
    method_params = {}
    method_params['method'] = 'getGroups'
    return vk_method(method_params)

def getGroupsFull():
    method_params = {}
    method_params['method'] = 'getGroupsFull'
    return vk_method(method_params)
   
#Friends

class vk_friends(object):
    #not_full
    def get(self, fields=None, name_case='nom'):
        method_params = {'method': 'friends.get'}
        if fields != None:
            method_params['fields'] = fields
        method_params['name_case'] = name_case
        return vk_method(method_params)
   
    def getAppUsers(self):
        method_params = {'method': 'friends.getAppUsers'}
        return vk_method(method_params)
       
#Activity

class vk_activity(object):
    def get(self, uid=None):
        method_params = {'method': 'activity.get'}
        if uid != None:
            method_params['uid'] = str(uid)
        return vk_method(method_params)
    def set(self, text):
        method_params = {'method': 'activity.set'}
        method_params['text'] = text
        return vk_method(method_params)
    def getHistory(self, uid=None):
        method_params = {'method': 'activity.getHistory'}
        if uid != None:
            method_params['uid'] = str(uid)
        return vk_method(method_params)
    def deleteHistoryItem(self, aid):
        method_params = {'method': 'activity.deleteHistoryItem'}
        method_params['aid'] = str(aid)
        return vk_method(method_params)
    #not_full
    def getNews(self, timestamp = None, offset = None, count = 20):
        method_params = {'method': 'activity.getNews'}
        if timestamp != None:
            method_params['timestamp'] = str(timestamp)
            return vk_method(method_params)
        method_params['count'] = str(count)
        return vk_method(method_params)
       
#Photos - not tested

class vk_photos(object):
    def getAlbums(self, uid=None, aids=None):
        method_params = {'method': 'photos.getAlbums'}
        if uid != None:
            method_params['uid'] = str(uid)
        if aids != None:
            for aid in aids:
                aids_str += str(aid) + ','
            method_params['aids'] = aids_str[:-1]
        return vk_method(method_params)
    def get(self, uid, aid, pids=None):
        method_params = {'method': 'photos.get'}
        method_params['uid'] = str(uid)
        method_params['aid'] = str(aid)
        if pids != None:
            for pid in pids:
                pids_str += str(pid) + ','
            method_params['pids'] = pids_str[:-1]
        return vk_method(method_params)

#Audio

class vk_audio(object):
    def search(self, q, sort=0, lyrics=0, count=30, offset = 0):
        method_params={}
        method_params['method'] = 'audio.search'
        method_params['q'] = q
        method_params['test_mode'] = '1'
        method_params['sort'] = str(sort)
        method_params['lyrics'] = str(lyrics)
        method_params['count'] = str(count)
        method_params['offset'] = str(offset)
        return vk_method(method_params)
   
########################################################################

def vk_login():
    vk_login_url = 'http://vkontakte.ru/login.php?app='+init_params["api_id"]+'&layout='+init_params["layout"]+'&type='+init_params["type"]+'&settings=16383'
    print vk_login_url
    #ofile=open('vk_login.html', 'w')
    #c = pycurl.Curl()
    #c.setopt(c.URL, vk_login_url)
    #c.setopt(c.WRITEDATA, ofile)
    #c.perform()
    #c.close
    pass

audio = vk_audio()
friends = vk_friends()
activity = vk_activity()
photos = vk_photos()

def main():
    global session
    #vk_login()
    try:
        #print getUserBalance()
        #print getProfiles((24052381, 68654541, 6695150))
        #print isAppUser()
        #print len(audio.search('why', count=301))
        #print getUserSettings()
        #print getGroups()
        #print getGroupsFull()
        #print friends.get()
        #print friends.getAppUsers()
        #print activity.get()
        #print activity.set('')
        #print activity.getHistory()
        #print activity.deleteHistoryItem(15)
        #print activity.getNews()
        #print photos.getAlbums()
       
        pass
    except MethodError as me:
        print me.error_code, ': ', me.error_msg
        return -1
    return 0

if __name__ == '__main__':
    main()

 

Комментарии:

Нет