Forum Freedom-IP VPN

Forum d'entraide de la communauté Freedom-IP VPN

Vous n'êtes pas identifié(e).

#26 2015-11-25 22:38:29

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Bonsoir Didier .
J'ai testé ton "premier jet" et le résultat est tout simplement concluant . smile
J'ai juste une erreur en bout de terminal

ValueError: No JSON object could be decoded

est ce que c'est normal ?
Un grand merci à toi pour ton code et un immense merci à hmz pour la mise en place de l'api .
Bien cordialement à vous deux , Patrick1969 .


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#27 2015-11-25 23:33:52

metalux
Membre
Inscription : 2014-10-30
Messages : 72

Re : Amélioration de l'API

Bonsoir Didier-T,
J'ai des messages d'erreur pour ma part, ça ne fonctionne pas. Sachant que je suis toujours avec Ubuntu 12.04 (Python 2.7.3) , je suppose que cela vient de là. Si ça n'a pas de rapport, dis moi si tu souhaites que je poste ces erreurs.
A+

Hors ligne

#28 2015-11-26 05:28:15

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

Bonjour Patrick metalux,
Pourriez-vous vous me donner vos retours terminal complet ?
Que je puisse voir ce qu'il ce passe, merci.

Patrick tu es sous Windows c'est bien ça ?

A+,
Didier.

Hors ligne

#29 2015-11-26 06:27:15

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Bonjour Didier .
Non , je suis sous linux Voyager 14.04.04 LTS .
Voici mon retour terminal complet :

spies @ spies  ~
└─ $ ▶ cd /home/spies/Bureau
spies @ spies  ~/Bureau
└─ $ ▶ python2 API_lib.py fip_xxxxxxxx xxxxxxxx
[INFO] Demande Server
{"status":"success","fr":{"country":"FR","online":true,"speed_up_bytes":"1808707","speed_down_bytes":"1947261","nbr_logged":"79"},"nl":{"country":"NL","online":true,"speed_up_bytes":"1658169","speed_down_bytes":"1881363","nbr_logged":"60"},"de":{"country":"DE","online":true,"speed_up_bytes":"369118","speed_down_bytes":"679827","nbr_logged":"13"},"es":{"country":"ES","online":true,"speed_up_bytes":"639697","speed_down_bytes":"625624","nbr_logged":"13"},"uk":{"country":"UK","online":true,"speed_up_bytes":"302768","speed_down_bytes":"420449","nbr_logged":"6"},"ie":{"country":"IE","online":true,"speed_up_bytes":"900264","speed_down_bytes":"1137143","nbr_logged":"8"},"cz":{"country":"CZ","online":true,"speed_up_bytes":"33341","speed_down_bytes":"90761","nbr_logged":"10"},"lt":{"country":"LT","online":true,"speed_up_bytes":"97063","speed_down_bytes":"2808495","nbr_logged":"7"},"be":{"country":"BE","online":true,"speed_up_bytes":"699771","speed_down_bytes":"709605","nbr_logged":"16"},"pl":{"country":"PL","online":true,"speed_up_bytes":"60036","speed_down_bytes":"979482","nbr_logged":"10"},"ch":{"country":"CH","online":true,"speed_up_bytes":"746685","speed_down_bytes":"756913","nbr_logged":"12"},"it":{"country":"IT","online":true,"speed_up_bytes":"628917","speed_down_bytes":"702342","nbr_logged":"6"},"lu":{"country":"LU","online":true,"speed_up_bytes":"9884","speed_down_bytes":"1223042","nbr_logged":"7"},"fi":{"country":"FI","online":true,"speed_up_bytes":"436","speed_down_bytes":"2155","nbr_logged":"14"},"pt":{"country":"PT","online":true,"speed_up_bytes":"193351","speed_down_bytes":"740984","nbr_logged":"3"},"gr":{"country":"GR","online":true,"speed_up_bytes":"8806","speed_down_bytes":"9078","nbr_logged":"8"},"mt":{"country":"MT","online":true,"speed_up_bytes":"667356","speed_down_bytes":"785181","nbr_logged":"90"},"dk":{"country":"DK","online":true,"speed_up_bytes":"966","speed_down_bytes":"3541","nbr_logged":"8"},"se":{"country":"SE","online":true,"speed_up_bytes":"51951","speed_down_bytes":"41024","nbr_logged":"7"},"us":{"country":"US","online":true,"speed_up_bytes":"223898","speed_down_bytes":"243190","nbr_logged":"5"},"ca":{"country":"CA","online":true,"speed_up_bytes":"15471","speed_down_bytes":"11250","nbr_logged":"6"},"ru":{"country":"RU","online":true,"speed_up_bytes":"499599","speed_down_bytes":"592410","nbr_logged":"13"},"ua":{"country":"UA","online":true,"speed_up_bytes":"518171","speed_down_bytes":"481723","nbr_logged":"9"},"ro":{"country":"RO","online":true,"speed_up_bytes":"15726","speed_down_bytes":"11996","nbr_logged":"9"},"is":{"country":"IS","online":true,"speed_up_bytes":"146871","speed_down_bytes":"148139","nbr_logged":"8"},"lv":{"country":"LV","online":true,"speed_up_bytes":"111746","speed_down_bytes":"106079","nbr_logged":"5"},"hr":{"country":"HR","online":true,"speed_up_bytes":"753096","speed_down_bytes":"807181","nbr_logged":"5"},"no":{"country":"NO","online":true,"speed_up_bytes":"2296","speed_down_bytes":"7614","nbr_logged":"8"},"si":{"country":"SI","online":true,"speed_up_bytes":"9509","speed_down_bytes":"1624141","nbr_logged":"6"},"at":{"country":"AT","online":true,"speed_up_bytes":"182441","speed_down_bytes":"192503","nbr_logged":"5"},"bg":{"country":"BG","online":true,"speed_up_bytes":"427913","speed_down_bytes":"414989","nbr_logged":"6"},"ee":{"country":"EE","online":true,"speed_up_bytes":"59904","speed_down_bytes":"64768","nbr_logged":"5"}}
[ OK ] Server
[INFO] Demande userInfo

Traceback (most recent call last):
  File "API_lib.py", line 190, in <module>
    _test()
  File "API_lib.py", line 171, in _test
    api_ret.append(fip.userInfo())
  File "API_lib.py", line 105, in userInfo
    response=self._info("userInfo")
  File "API_lib.py", line 84, in _info
    return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})
  File "API_lib.py", line 69, in _past
    data=json.loads(r)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
spies @ spies  ~/Bureau
└─ $ ▶ 
 

Bonne journée , cordialement , Patrick1969 .
Au passage , petit bonjour à metalux.

Dernière modification par Patrick1969 (2015-11-26 06:31:04)


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#30 2015-11-26 17:56:11

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

Bonsoir,
je suis aussi sous Voyager 14.04 et il n'y a aucun soucis, en fait j'avais rencontré ce soucis hier matin et l'ai réglé avant de poster.
voici le retour cher moi.

didier @ didier-P35-DS3R  ~/développement/FIP_2
└─ $ ▶ python API_lib.py fip_********** *****************
[INFO] Demande Server
{"status":"success","fr":{"country":"FR","online":true,"speed_up_bytes":"1816742","speed_down_bytes":"4659288","nbr_logged":"85"},"nl":{"country":"NL","online":true,"speed_up_bytes":"2186604","speed_down_bytes":"2235876","nbr_logged":"64"},"de":{"country":"DE","online":true,"speed_up_bytes":"1327663","speed_down_bytes":"1341828","nbr_logged":"17"},"es":{"country":"ES","online":true,"speed_up_bytes":"1202830","speed_down_bytes":"1258364","nbr_logged":"19"},"uk":{"country":"UK","online":true,"speed_up_bytes":"418511","speed_down_bytes":"505927","nbr_logged":"10"},"ie":{"country":"IE","online":true,"speed_up_bytes":"418261","speed_down_bytes":"493435","nbr_logged":"10"},"cz":{"country":"CZ","online":true,"speed_up_bytes":"227930","speed_down_bytes":"233517","nbr_logged":"13"},"lt":{"country":"LT","online":true,"speed_up_bytes":"484539","speed_down_bytes":"447362","nbr_logged":"9"},"be":{"country":"BE","online":true,"speed_up_bytes":"2231408","speed_down_bytes":"5443871","nbr_logged":"21"},"pl":{"country":"PL","online":true,"speed_up_bytes":"1326999","speed_down_bytes":"1349853","nbr_logged":"12"},"ch":{"country":"CH","online":true,"speed_up_bytes":"1701081","speed_down_bytes":"1768730","nbr_logged":"14"},"it":{"country":"IT","online":true,"speed_up_bytes":"1047596","speed_down_bytes":"992471","nbr_logged":"10"},"lu":{"country":"LU","online":true,"speed_up_bytes":"470973","speed_down_bytes":"468614","nbr_logged":"10"},"fi":{"country":"FI","online":true,"speed_up_bytes":"184723","speed_down_bytes":"237206","nbr_logged":"12"},"pt":{"country":"PT","online":true,"speed_up_bytes":"866","speed_down_bytes":"2157","nbr_logged":"3"},"gr":{"country":"GR","online":true,"speed_up_bytes":"5305","speed_down_bytes":"218064","nbr_logged":"6"},"mt":{"country":"MT","online":true,"speed_up_bytes":"264940","speed_down_bytes":"421969","nbr_logged":"89"},"dk":{"country":"DK","online":true,"speed_up_bytes":"401091","speed_down_bytes":"386639","nbr_logged":"7"},"se":{"country":"SE","online":true,"speed_up_bytes":"766","speed_down_bytes":"1546","nbr_logged":"6"},"us":{"country":"US","online":true,"speed_up_bytes":"374463","speed_down_bytes":"462814","nbr_logged":"8"},"ca":{"country":"CA","online":true,"speed_up_bytes":"20689","speed_down_bytes":"16543","nbr_logged":"8"},"ru":{"country":"RU","online":true,"speed_up_bytes":"293487","speed_down_bytes":"313434","nbr_logged":"12"},"ua":{"country":"UA","online":true,"speed_up_bytes":"795790","speed_down_bytes":"790902","nbr_logged":"9"},"ro":{"country":"RO","online":true,"speed_up_bytes":"537013","speed_down_bytes":"681346","nbr_logged":"11"},"is":{"country":"IS","online":true,"speed_up_bytes":"20771","speed_down_bytes":"2089189","nbr_logged":"8"},"lv":{"country":"LV","online":true,"speed_up_bytes":"15275","speed_down_bytes":"2491541","nbr_logged":"4"},"hr":{"country":"HR","online":true,"speed_up_bytes":"963223","speed_down_bytes":"1231864","nbr_logged":"6"},"no":{"country":"NO","online":true,"speed_up_bytes":"199346","speed_down_bytes":"199553","nbr_logged":"8"},"si":{"country":"SI","online":true,"speed_up_bytes":"13225","speed_down_bytes":"20011","nbr_logged":"6"},"at":{"country":"AT","online":true,"speed_up_bytes":"114599","speed_down_bytes":"3330050","nbr_logged":"7"},"bg":{"country":"BG","online":true,"speed_up_bytes":"1102440","speed_down_bytes":"1096982","nbr_logged":"7"},"ee":{"country":"EE","online":true,"speed_up_bytes":"224125","speed_down_bytes":"204904","nbr_logged":"7"}}
[ OK ] Server
[INFO] Demande userInfo
{"status":"success","username":"fip_**********","email":"*******@*****.com","isSubscriber":true,"subscription_end":"10\/01\/2016 16:56:30","subscription":{"montant":"0","creation":"1420905390","expiration":"1452441390","expired":"0","offer_code":"OLD_OFFER_2014"},"speed_max":"16777216","nb_slots":"4"}
[ OK ] userInfo
[INFO] Demande livestats
{"status":"success","connections":[]}
[ OK ] livestats
Arbre retour fonction Server() :
[ch][country]=CH
[ch][nbr_logged]=14
[ch][speed_down_bytes]=1768730
[ch][speed_up_bytes]=1701081
[ch][online]=True
[gr][country]=GR
[gr][nbr_logged]=6
[gr][speed_down_bytes]=218064
[gr][speed_up_bytes]=5305
[gr][online]=True
[ee][country]=EE
[ee][nbr_logged]=7
[ee][speed_down_bytes]=204904
[ee][speed_up_bytes]=224125
[ee][online]=True
[ca][country]=CA
[ca][nbr_logged]=8
[ca][speed_down_bytes]=16543
[ca][speed_up_bytes]=20689
[ca][online]=True
[it][country]=IT
[it][nbr_logged]=10
[it][speed_down_bytes]=992471
[it][speed_up_bytes]=1047596
[it][online]=True
[cz][country]=CZ
[cz][nbr_logged]=13
[cz][speed_down_bytes]=233517
[cz][speed_up_bytes]=227930
[cz][online]=True
[at][country]=AT
[at][nbr_logged]=7
[at][speed_down_bytes]=3330050
[at][speed_up_bytes]=114599
[at][online]=True
[ie][country]=IE
[ie][nbr_logged]=10
[ie][speed_down_bytes]=493435
[ie][speed_up_bytes]=418261
[ie][online]=True
[es][country]=ES
[es][nbr_logged]=19
[es][speed_down_bytes]=1258364
[es][speed_up_bytes]=1202830
[es][online]=True
[ru][country]=RU
[ru][nbr_logged]=12
[ru][speed_down_bytes]=313434
[ru][speed_up_bytes]=293487
[ru][online]=True
[nl][country]=NL
[nl][nbr_logged]=64
[nl][speed_down_bytes]=2235876
[nl][speed_up_bytes]=2186604
[nl][online]=True
[pt][country]=PT
[pt][nbr_logged]=3
[pt][speed_down_bytes]=2157
[pt][speed_up_bytes]=866
[pt][online]=True
[no][country]=NO
[no][nbr_logged]=8
[no][speed_down_bytes]=199553
[no][speed_up_bytes]=199346
[no][online]=True
[lv][country]=LV
[lv][nbr_logged]=4
[lv][speed_down_bytes]=2491541
[lv][speed_up_bytes]=15275
[lv][online]=True
[lt][country]=LT
[lt][nbr_logged]=9
[lt][speed_down_bytes]=447362
[lt][speed_up_bytes]=484539
[lt][online]=True
[lu][country]=LU
[lu][nbr_logged]=10
[lu][speed_down_bytes]=468614
[lu][speed_up_bytes]=470973
[lu][online]=True
[ro][country]=RO
[ro][nbr_logged]=11
[ro][speed_down_bytes]=681346
[ro][speed_up_bytes]=537013
[ro][online]=True
[is][country]=IS
[is][nbr_logged]=8
[is][speed_down_bytes]=2089189
[is][speed_up_bytes]=20771
[is][online]=True
[pl][country]=PL
[pl][nbr_logged]=12
[pl][speed_down_bytes]=1349853
[pl][speed_up_bytes]=1326999
[pl][online]=True
[status]=success
[be][country]=BE
[be][nbr_logged]=21
[be][speed_down_bytes]=5443871
[be][speed_up_bytes]=2231408
[be][online]=True
[fr][country]=FR
[fr][nbr_logged]=85
[fr][speed_down_bytes]=4659288
[fr][speed_up_bytes]=1816742
[fr][online]=True
[bg][country]=BG
[bg][nbr_logged]=7
[bg][speed_down_bytes]=1096982
[bg][speed_up_bytes]=1102440
[bg][online]=True
[dk][country]=DK
[dk][nbr_logged]=7
[dk][speed_down_bytes]=386639
[dk][speed_up_bytes]=401091
[dk][online]=True
[hr][country]=HR
[hr][nbr_logged]=6
[hr][speed_down_bytes]=1231864
[hr][speed_up_bytes]=963223
[hr][online]=True
[de][country]=DE
[de][nbr_logged]=17
[de][speed_down_bytes]=1341828
[de][speed_up_bytes]=1327663
[de][online]=True
[fi][country]=FI
[fi][nbr_logged]=12
[fi][speed_down_bytes]=237206
[fi][speed_up_bytes]=184723
[fi][online]=True
[us][country]=US
[us][nbr_logged]=8
[us][speed_down_bytes]=462814
[us][speed_up_bytes]=374463
[us][online]=True
[mt][country]=MT
[mt][nbr_logged]=89
[mt][speed_down_bytes]=421969
[mt][speed_up_bytes]=264940
[mt][online]=True
[si][country]=SI
[si][nbr_logged]=6
[si][speed_down_bytes]=20011
[si][speed_up_bytes]=13225
[si][online]=True
[uk][country]=UK
[uk][nbr_logged]=10
[uk][speed_down_bytes]=505927
[uk][speed_up_bytes]=418511
[uk][online]=True
[ua][country]=UA
[ua][nbr_logged]=9
[ua][speed_down_bytes]=790902
[ua][speed_up_bytes]=795790
[ua][online]=True
[se][country]=SE
[se][nbr_logged]=6
[se][speed_down_bytes]=1546
[se][speed_up_bytes]=766
[se][online]=True


Arbre retour fonction userInfo() :
[status]=success
[username]=fip_********
[speed_max]=16777216
[subscription_end]=10/01/2016 16:56:30
[nb_slots]=4
[email]=*****@****.com
[isSubscriber]=True
[subscription][offer_code]=OLD_OFFER_2014
[subscription][creation]=1420905390
[subscription][expired]=0
[subscription][expiration]=1452441390
[subscription][montant]=0


Arbre retour fonction livestats() :
[status]=success


Chronomètre :
Temp consultation API : 0.651360034943
Temp exploration arbres : 0.00125694274902
Temp consultation API + exploration arbres : 0.652616977692

Si je fait une erreur mot de passe ou identifiant

didier @ didier-P35-DS3R  ~/développement/FIP_2
└─ $ ▶ python API_lib.py fip_********** ****************
[INFO] Demande Server
[FAIL] HTTP Error 401: Unauthorized
[INFO] Veuillez vérifier vos identifiants 
[ OK ] Server
[INFO] Demande userInfo
[FAIL] HTTP Error 401: Unauthorized
[INFO] Veuillez vérifier vos identifiants 
[ OK ] userInfo
[INFO] Demande livestats
[FAIL] HTTP Error 401: Unauthorized
[INFO] Veuillez vérifier vos identifiants 
[ OK ] livestats
Arbre retour fonction Server() :



Arbre retour fonction userInfo() :



Arbre retour fonction livestats() :



Chronomètre :
Temp consultation API : 0.395014047623
Temp exploration arbres : 0.000139951705933
Temp consultation API + exploration arbres : 0.395153999329

tout ceci est contrariant
pourais-tu me donner le retour de python -V

didier @ didier-P35-DS3R  ~
└─ $ ▶ python -V
Python 2.7.6

A+,
Didier.

Hors ligne

#31 2015-11-26 18:07:48

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

Re,
essaye donc ceci Patrick

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import urllib, urllib2, time, platform, simplejson, base64
try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password)

    def _past(self, url, args):
        params = urllib.urlencode(args)
        req = urllib2.Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urllib2.urlopen(req, context=gcontext, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urllib2.urlopen(req, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            data=simplejson.loads(response.read())
        else:
            data = ""
        return data

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=self._info("Server")
        return self._verif(response, "Server")

    def userInfo(self):
        response=self._info("userInfo")
        return self._verif(response, "userInfo")

    def livestats(self):
        response=self._info("livestats")
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print 'Temp consultation API :', t1
    print 'Temp exploration arbres :', timer.interval-t1
    print 'Temp consultation API + exploration arbres :', timer.interval


if __name__ == '__main__':
    _test()

Hors ligne

#32 2015-11-26 18:58:58

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import urllib, urllib2, time, platform, simplejson, base64
try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password)

    def _past(self, url, args):
        params = urllib.urlencode(args)
        req = urllib2.Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urllib2.urlopen(req, context=gcontext, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urllib2.urlopen(req, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            data=simplejson.loads(response.read())
        else:
            data = ""
        return data

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=self._info("Server")
        return self._verif(response, "Server")

    def userInfo(self):
        response=self._info("userInfo")
        return self._verif(response, "userInfo")

    def livestats(self):
        response=self._info("livestats")
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print 'Temp consultation API :', t1
    print 'Temp exploration arbres :', timer.interval-t1
    print 'Temp consultation API + exploration arbres :', timer.interval


if __name__ == '__main__':
    _test()

L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#33 2015-11-26 19:01:17

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

En fait c'est comme si il n'y avait rien a traiter  hmm

Hors ligne

#34 2015-11-26 19:08:09

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

et avec ceci, au cas ou il y aurait un retour a la ligne caché

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import urllib, urllib2, time, platform, simplejson, base64
try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password)

    def _past(self, url, args):
        params = urllib.urlencode(args)
        req = urllib2.Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urllib2.urlopen(req, context=gcontext, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urllib2.urlopen(req, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            data=simplejson.loads(response.read().replace('\r', '').replace('\n', ''))
        else:
            data = ""
        return data

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=self._info("Server")
        return self._verif(response, "Server")

    def userInfo(self):
        response=self._info("userInfo")
        return self._verif(response, "userInfo")

    def livestats(self):
        response=self._info("livestats")
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print 'Temp consultation API :', t1
    print 'Temp exploration arbres :', timer.interval-t1
    print 'Temp consultation API + exploration arbres :', timer.interval


if __name__ == '__main__':
    _test()

Hors ligne

#35 2015-11-26 19:10:26

metalux
Membre
Inscription : 2014-10-30
Messages : 72

Re : Amélioration de l'API

Bonsoir Didier et Patrick,
J'ai les mêmes messages d'erreur pour la 1ère version et pour la seconde ça diffère un petit peu:

python '/home/metalux/Bureau/API_lib.py'  fip_**********  ************
[INFO] Demande Server
[ OK ] Server
[INFO] Demande userInfo
Traceback (most recent call last):
  File "/home/metalux/Bureau/API_lib.py", line 188, in <module>
    _test()
  File "/home/metalux/Bureau/API_lib.py", line 169, in _test
    api_ret.append(fip.userInfo())
  File "/home/metalux/Bureau/API_lib.py", line 103, in userInfo
    response=self._info("userInfo")
  File "/home/metalux/Bureau/API_lib.py", line 82, in _info
    return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})
  File "/home/metalux/Bureau/API_lib.py", line 67, in _past
    data=simplejson.loads(response.read())
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 413, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

Hors ligne

#36 2015-11-26 19:12:07

metalux
Membre
Inscription : 2014-10-30
Messages : 72

Re : Amélioration de l'API

Pas mieux avec le 3ème script  sad
Python 2.7.3

Dernière modification par metalux (2015-11-26 19:15:41)

Hors ligne

#37 2015-11-26 19:19:28

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Le retour du message #34

spies @ spies  ~/Bureau
└─ $ ▶ python2 API_lib.py fip_xxxxxxx xxxxxx
[INFO] Demande Server
[ OK ] Server
[INFO] Demande userInfo
Traceback (most recent call last):
  File "API_lib.py", line 188, in <module>
    _test()
  File "API_lib.py", line 169, in _test
    api_ret.append(fip.userInfo())
  File "API_lib.py", line 103, in userInfo
    response=self._info("userInfo")
  File "API_lib.py", line 82, in _info
    return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})
  File "API_lib.py", line 67, in _past
    data=simplejson.loads(response.read().replace('\r', '').replace('\n', ''))
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 488, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 389, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
spies @ spies  ~/Bureau
└─ $ ▶ 
 

Dernière modification par Patrick1969 (2015-11-26 19:21:14)


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#38 2015-11-26 19:28:32

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

J'y perd mon latin.
En plus vous n'avez pas l'erreur sur le même caractère yikes

Hors ligne

#39 2015-11-26 20:16:29

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

ont vas finir par pourrir le topic  big_smile

aller nouvelle essais cette fois on sort les données de la fonction et on fait le traitement plus tard

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import urllib, urllib2, time, platform, simplejson, base64
try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password)

    def _past(self, url, args):
        params = urllib.urlencode(args)
        req = urllib2.Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urllib2.urlopen(req, context=gcontext, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urllib2.urlopen(req, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            ret=response.read()
        else:
            ret = "{}"
        return ret

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=simplejson.loads(self._info("Server"))
        return self._verif(response, "Server")

    def userInfo(self):
        response=simplejson.loads(self._info("userInfo"))
        return self._verif(response, "userInfo")

    def livestats(self):
        response=simplejson.loads(self._info("livestats"))
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print 'Temp consultation API :', t1
    print 'Temp exploration arbres :', timer.interval-t1
    print 'Temp consultation API + exploration arbres :', timer.interval


if __name__ == '__main__':
    _test()

pour info tout les codes que je vous aient proposé fonctionne parfaitement cher moi

Hors ligne

#40 2015-11-26 20:30:04

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Re

spies @ spies  ~/Bureau
└─ $ ▶ python2 API_lib.py fip_xxxxxxx xxxxxxx
[INFO] Demande Server
[ OK ] Server
[INFO] Demande userInfo
Traceback (most recent call last):
  File "API_lib.py", line 188, in <module>
    _test()
  File "API_lib.py", line 169, in _test
    api_ret.append(fip.userInfo())
  File "API_lib.py", line 103, in userInfo
    response=simplejson.loads(self._info("userInfo"))
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 488, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 389, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
spies @ spies  ~/Bureau
└─ $ ▶ 
 

cry  .....


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#41 2015-11-26 20:32:25

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

Eh bien il parait que la nuit porte conseille cool

Hors ligne

#42 2015-11-26 20:36:18

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Il parait ...
En tous les cas merci quand même pour ton implication .
Je regrette bien de ne pas pouvoir t'aider plus .
Passe une bonne soirée , cordialement , Patrick .


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#43 2015-11-26 21:43:18

Polizei
Membres de confiance
Inscription : 2013-12-27
Messages : 403

Re : Amélioration de l'API

Hors ligne

#44 2015-11-26 22:33:29

metalux
Membre
Inscription : 2014-10-30
Messages : 72

Re : Amélioration de l'API

Bonsoir Polizei,
Plus on est de fou, plus on ris, c'est pas ce qu'on dit?  devil

Désolé Didier, c'était trop tentant. ops  Pour me faire pardonner, voici le dernier Log:

[INFO] Demande Server
[ OK ] Server
[INFO] Demande userInfo
Traceback (most recent call last):
  File "/home/metalux/Bureau/API_lib.py", line 188, in <module>
    _test()
  File "/home/metalux/Bureau/API_lib.py", line 169, in _test
    api_ret.append(fip.userInfo())
  File "/home/metalux/Bureau/API_lib.py", line 103, in userInfo
    response=simplejson.loads(self._info("userInfo"))
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 413, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

Hors ligne

#45 2015-11-28 10:21:20

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

Bonjour,
un nouvelle essais, avant de changer de version de python et passer a python 3  cry
cette fois je demande au script de décoder les informations et de les transformer en unicode, pour éliminer les problèmes de codage (après tous pourquoi pas  tongue )

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import urllib, urllib2, time, platform, simplejson, base64
try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password)

    def _past(self, url, args):
        params = urllib.urlencode(args)
        req = urllib2.Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urllib2.urlopen(req, context=gcontext, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urllib2.urlopen(req, timeout = 5)
            except Exception, e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            encode=response.headers['content-type'].split('charset=')[-1]
            decode = unicode(response.read(), encode)
            print(decode)
            ret=decode#.encode('utf-8')
        else:
            ret = "{}"
        return ret

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=simplejson.loads(self._info("Server"))
        return self._verif(response, "Server")

    def userInfo(self):
        response=simplejson.loads(self._info("userInfo"))
        return self._verif(response, "userInfo")

    def livestats(self):
        response=simplejson.loads(self._info("livestats"))
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print 'Temp consultation API :', t1
    print 'Temp exploration arbres :', timer.interval-t1
    print 'Temp consultation API + exploration arbres :', timer.interval


if __name__ == '__main__':
    _test()

j’attends vos retour avec impatience  big_smile

A+,
Didier.

@Metalux, viens faire un tour sur le salon IRC s'il te plaît, j'aimerais tester un truc... Merci

Hors ligne

#46 2015-11-28 11:13:56

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Bonjour Didier_T , bonjour à tous .
Voici mon retour terminal :

[INFO] Demande Server
{"status":"success","fr":{"country":"FR","online":true,"speed_up_bytes":"1140110","speed_down_bytes":"2218319","nbr_logged":"85"},"nl":{"country":"NL","online":true,"speed_up_bytes":"2119967","speed_down_bytes":"2334955","nbr_logged":"63"},"de":{"country":"DE","online":true,"speed_up_bytes":"370881","speed_down_bytes":"373611","nbr_logged":"16"},"es":{"country":"ES","online":true,"speed_up_bytes":"2190116","speed_down_bytes":"3493815","nbr_logged":"21"},"uk":{"country":"UK","online":true,"speed_up_bytes":"573493","speed_down_bytes":"549898","nbr_logged":"8"},"ie":{"country":"IE","online":true,"speed_up_bytes":"377735","speed_down_bytes":"390853","nbr_logged":"15"},"cz":{"country":"CZ","online":true,"speed_up_bytes":"140711","speed_down_bytes":"140499","nbr_logged":"11"},"lt":{"country":"LT","online":true,"speed_up_bytes":"27799","speed_down_bytes":"1293558","nbr_logged":"8"},"be":{"country":"BE","online":true,"speed_up_bytes":"223773","speed_down_bytes":"247117","nbr_logged":"16"},"pl":{"country":"PL","online":true,"speed_up_bytes":"514753","speed_down_bytes":"581709","nbr_logged":"15"},"ch":{"country":"CH","online":true,"speed_up_bytes":"337249","speed_down_bytes":"1371677","nbr_logged":"15"},"it":{"country":"IT","online":true,"speed_up_bytes":"638068","speed_down_bytes":"917339","nbr_logged":"8"},"lu":{"country":"LU","online":true,"speed_up_bytes":"464602","speed_down_bytes":"463934","nbr_logged":"10"},"fi":{"country":"FI","online":true,"speed_up_bytes":"111768","speed_down_bytes":"167947","nbr_logged":"9"},"pt":{"country":"PT","online":true,"speed_up_bytes":"309290","speed_down_bytes":"305533","nbr_logged":"4"},"gr":{"country":"GR","online":true,"speed_up_bytes":"488524","speed_down_bytes":"547044","nbr_logged":"7"},"mt":{"country":"MT","online":true,"speed_up_bytes":"318777","speed_down_bytes":"1862303","nbr_logged":"87"},"dk":{"country":"DK","online":true,"speed_up_bytes":"122374","speed_down_bytes":"137202","nbr_logged":"9"},"se":{"country":"SE","online":true,"speed_up_bytes":"139199","speed_down_bytes":"147372","nbr_logged":"7"},"us":{"country":"US","online":true,"speed_up_bytes":"264174","speed_down_bytes":"332582","nbr_logged":"7"},"ca":{"country":"CA","online":true,"speed_up_bytes":"171381","speed_down_bytes":"233046","nbr_logged":"8"},"ru":{"country":"RU","online":true,"speed_up_bytes":"228206","speed_down_bytes":"1621967","nbr_logged":"11"},"ua":{"country":"UA","online":true,"speed_up_bytes":"16399","speed_down_bytes":"821816","nbr_logged":"6"},"ro":{"country":"RO","online":true,"speed_up_bytes":"285303","speed_down_bytes":"255862","nbr_logged":"10"},"is":{"country":"IS","online":true,"speed_up_bytes":"20879","speed_down_bytes":"22661","nbr_logged":"13"},"lv":{"country":"LV","online":true,"speed_up_bytes":"148279","speed_down_bytes":"146342","nbr_logged":"7"},"hr":{"country":"HR","online":true,"speed_up_bytes":"174506","speed_down_bytes":"200577","nbr_logged":"6"},"no":{"country":"NO","online":true,"speed_up_bytes":"639177","speed_down_bytes":"1861311","nbr_logged":"7"},"si":{"country":"SI","online":true,"speed_up_bytes":"396","speed_down_bytes":"2312","nbr_logged":"3"},"at":{"country":"AT","online":true,"speed_up_bytes":"111921","speed_down_bytes":"147681","nbr_logged":"6"},"bg":{"country":"BG","online":true,"speed_up_bytes":"119867","speed_down_bytes":"1950090","nbr_logged":"5"},"ee":{"country":"EE","online":true,"speed_up_bytes":"278699","speed_down_bytes":"273678","nbr_logged":"6"}}
[ OK ] Server
[INFO] Demande userInfo

Traceback (most recent call last):
  File "API_lib.py", line 191, in <module>
    _test()
  File "API_lib.py", line 172, in _test
    api_ret.append(fip.userInfo())
  File "API_lib.py", line 106, in userInfo
    response=simplejson.loads(self._info("userInfo"))
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 488, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 389, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
 

Reste zen , à+ , cordialement , Patrick .   smile


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#47 2015-11-28 11:14:15

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

#! /usr/bin/python3
# -*- coding: utf-8 -*-
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import time, platform, json, base64
from urllib.parse import urlencode
from urllib.request import Request
from urllib.request import urlopen

try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password.encode()).decode().replace('\n', '')

    def _past(self, url, args):
        req = Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urlopen(req, context=gcontext, timeout = 5)
            except Exception as e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urlopen(req, timeout = 5)
            except Exception as e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            encoder=response.headers['content-type'].split('charset=')[-1]
            ret = response.read().decode(encoder)
#            print(ret)
        else:
            ret = "{}"
        return ret

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=json.loads(self._info("Server"))
        return self._verif(response, "Server")

    def userInfo(self):
        response=json.loads(self._info("userInfo"))
        return self._verif(response, "userInfo")

    def livestats(self):
        response=json.loads(self._info("livestats"))
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print('Temp consultation API :', t1)
    print('Temp exploration arbres :', timer.interval-t1)
    print('Temp consultation API + exploration arbres :', timer.interval)


if __name__ == '__main__':
    _test()

Hors ligne

#48 2015-11-28 11:26:00

Patrick1969
Membre
Inscription : 2015-01-23
Messages : 283

Re : Amélioration de l'API

Re .
Le retour en Python3

[INFO] Demande Server
[ OK ] Server
[INFO] Demande userInfo
Traceback (most recent call last):
  File "API_lib.py", line 193, in <module>
    _test()
  File "API_lib.py", line 174, in _test
    api_ret.append(fip.userInfo())
  File "API_lib.py", line 108, in userInfo
    response=json.loads(self._info("userInfo"))
  File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
 

Voici ma version de python3 :

└─ $ ▶ python3 -V
Python 3.4.3
 

Dernière modification par Patrick1969 (2015-11-28 11:31:18)


L'accès à ce forum reste un privilège et non un droit , n'oubliez pas que nous sommes une communauté et non pas un dû .

Hors ligne

#49 2015-11-28 11:27:30

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

au moins il y a une certaine constance  hmm

Hors ligne

#50 2015-11-28 11:34:26

Didier-T
Contributeurs Confirmés
Lieu : Argenteuil
Inscription : 2014-02-01
Messages : 323

Re : Amélioration de l'API

#! /usr/bin/python3
# Par Didier-T pour les utilisateurs de Freedom-IP
# Version 3

########################################################################
#                                                                      #
#                            UTILISATION                               #
#                                                                      #
########################################################################
#                                                                      #
# from API_lib import api                                              #
#                                                                      #
# user="Identifiant VPN"                                               #
# password="Mot de passe VPN"                                          #
#                                                                      #
# IsLogged=api.Server()                                                #
# FairUse=api.userInfo()                                               #
# DNSConfig=api.livestats()                                            #
#                                                                      #
########################################################################

########################################################################
#                                                                      #
#                   UTILISATION FONCTION TEST API                      #
#                                                                      #
########################################################################
#                                                                      #
# python API_lib.py user password                                      #
#                                                                      #
########################################################################

import time, platform, json, base64
from urllib.parse import urlencode
from urllib.request import Request
from urllib.request import urlopen

try:
    import ssl
except:
    pass

class api():
    def __init__(self, user, password):
        self.user=user
        self.password=base64.encodestring(password.encode()).decode().replace('\n', '')

    def _past(self, url, args):
        req = Request(url, headers=args)
        if platform.system() != 'Linux':
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            try:
                response = urlopen(req, context=gcontext, timeout = 5)
            except Exception as e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        else:
            try:
                response = urlopen(req, timeout = 5)
            except Exception as e:
                print("[\033[31mFAIL\033[0m] %s" % e)
                if e.code==401:
                    print("[\033[33mINFO\033[0m] Veuillez vérifier vos identifiants ")
                response = ""
                pass
        if response != "":
            encoder=response.headers['content-type'].split('charset=')[-1]
            ret = str(response.read().decode(encoder)).strip("'<>() ").replace('\'', '\"')
#            print(ret)
        else:
            ret = "{}"
        return ret

    def _info(self, recherche):
        print("[\033[33mINFO\033[0m] Demande "+recherche)

        if recherche=="Server":
            url='https://api.freedom-ip.com/Server/all'
        elif recherche=="userInfo":
            url='https://api.freedom-ip.com/Account/userInfo'
        elif recherche=="livestats":
            url='https://api.freedom-ip.com/Account/livestats'

        return self._past(url, {'X-FIP-USER':self.user, 'X-FIP-PASSWORD':self.password})


    def _verif(self, informations, recherche):
        try:
            status=informations["status"]
        except:
            status="success"
        if status=="success":
            print("[\033[32m OK \033[0m] "+recherche)
            return informations
        else:
            print("[\033[31mFAIL\033[0m] Erreur "+status)
            exit(1)


    def Server(self):
        response=json.loads(self._info("Server"))
        return self._verif(response, "Server")

    def userInfo(self):
        response=json.loads(self._info("userInfo"))
        return self._verif(response, "userInfo")

    def livestats(self):
        response=json.loads(self._info("livestats"))
        return self._verif(response, "livestats")

def arbres(jstr):
    tableau=[]

    def decoupage(nom, valeur):
        if type(valeur)==list:
            nb=0
            for x in valeur:
                decoupage(nom+"["+str(nb)+"]", x)
                nb+=1
        elif type(valeur)==dict:
            for x in valeur:
                decoupage(nom+"["+x+"]", valeur[x])
        else:
            try:
                tableau.append(nom+"="+valeur)
            except:
                tableau.append(nom+"="+str(valeur))

    if type(jstr)==list:
        nb=0
        for x in jstr:
            decoupage("["+str(nb)+"]", x)
            nb+=1
    elif type(jstr)==dict:
        for x in jstr:
            decoupage("["+x+"]", jstr[x])
    else:
        tableau.append(str(jstr))

    return tableau




def _test():
    import sys

    class Timer(object):
        def start(self):
            if hasattr(self, 'interval'):
                del self.interval
            self.start_time = time.time()
        def inter(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
        def stop(self):
            if hasattr(self, 'start_time'):
                self.interval = time.time() - self.start_time
                del self.start_time

    timer = Timer()
    user=str(sys.argv[1])
    password=str(sys.argv[2])

    timer.start()
    api_ret=[]
    fip=api(user, password)
    list_api=['Server','userInfo','livestats']
    api_ret.append(fip.Server())
    api_ret.append(fip.userInfo())
    api_ret.append(fip.livestats())

    timer.inter()
    t1=timer.interval

    for x in range(0,len(api_ret)):
        print("\033[41mArbre retour fonction \033[1m{}()\033[0;41m :\033[0m".format(list_api[x]))
        print('\n'.join(arbres(api_ret[x])))
        print('\n')

    print("\033[41mChronomètre :\033[0m")
    timer.stop()
    print('Temp consultation API :', t1)
    print('Temp exploration arbres :', timer.interval-t1)
    print('Temp consultation API + exploration arbres :', timer.interval)


if __name__ == '__main__':
    _test()

Hors ligne

Pied de page des forums