IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau/Web Python Discussion :

API, KEY ERROR Variable manquante lors de la demande


Sujet :

Réseau/Web Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2019
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Aisne (Picardie)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2019
    Messages : 21
    Points : 20
    Points
    20
    Par défaut API, KEY ERROR Variable manquante lors de la demande
    Bonjour,

    je récupère des informations d'une API, mais cette dernière n'envoie pas toujours toutes les valeurs.

    Dans mon cas, je lui demande de récupérer le copyright mais l'information n'existe pas tout le temps, j'ai donc cette erreur KEY ERROR: 'copyright' qui est normale.

    Ma question est comment je peux faire une condition "if" (lors du formatage du json reçu), si il manque une information ?

    Merci par avance,

    Jean Christophe

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
     
     
    import requests
    import webbrowser
     
    """ Statut des réponses
    Les codes de retour HTTP de l'API sont : 200 si la requête a été acceptée et que des données sont retournées ; un code de la centaine des 400 si la requête est erronée ou le code 500 s'il y a une erreur du côté du serveur. Les codes suivants sont actuellement utilisés :
     
    200: OK
    400: Paramètre manquant, ou valeur incorrecte.
    401: Authentification nécessaire (token absent ou invalide)
    403: Action non autorisée (URL non autorisée avec votre abonnement)
    404: Page inaccessible (URL inconnue)
    500: Erreur interne au serveur, contactez-nous
    503: L'API est momentanément indisponible, réessayez dans quelques minutes
     
    """
    class ApiNasa:
     
        #copyright = ''
     
        def __init__(self):
     
            #self.copyright = copyright
            self.date = date
            self.explanation = explanation
            self.url_hdimage = url_hdimage
            self.url_imageslow = url_imageslow
     
        def format_response_nasa(apod):
            #Formattage des informations à recevoir: API NASA
            try:
                #ApiNasa.copyright = apod ['copyright']
                ApiNasa.date = apod ['date']
                ApiNasa.explanation = apod ['explanation']
                ApiNasa.url_hdimage = apod ['hdurl']
                ApiNasa.url_imageslow = apod ['url']
                #webbrowser.open_new(url_hdimage)
            except KeyError as e:
                print('Erreur:',e)
            return """"Copyright:\t" + str(copyright) + '\n' +""" "Date:\t\t" + str(ApiNasa.date) + '\n' + "explanation:\t" + str(ApiNasa.explanation) + '\n\n' + "UrlHdImage:\t" + str(ApiNasa.url_hdimage) + '\n' + "UrlImageSlow:\t" + str(ApiNasa.url_imageslow) + '\n'
     
        def get_nasa_api():
            # Connexion à l'api de la NASA
            nasa_key = 'gygr7huhu8huh986ghggez4'
            url_planetary = 'https://api.nasa.gov/planetary/apod?api_key={}'.format(nasa_key)
            send_requests = requests.get(url_planetary)
            apod_data_json = send_requests.json()
            print(apod_data_json)
            print(ApiNasa.format_response_nasa(apod_data_json))
            #return
     
    def main():
        ApiNasa.get_nasa_api()
        print(ApiNasa.date)
        print(ApiNasa.url_imageslow)
     
    if __name__ == "__main__":
        print("\nMy script is directly executed...\n ")
        main()
    else:
        print("My script is imported by an other module... ")

  2. #2
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 823
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 823
    Points : 7 119
    Points
    7 119
    Par défaut
    Bonjour,

    Vous avez trop d'erreur, ce qui indique qu'il y a besoin de se tourner vers un tutoriel python,


    1. Manque des arguments self dans les méthodes de classe
    2. Création d'instance absente
    3. Utilisation de variables indéfinies
    4. Ligne 7 et 41 trop longues
    5. ... (sans parler de l'algo que je ne vérifie pas)


    Je vous propose de consolider vos bases python avant d'attaquer la partie classes en python.
    Celui qui trouve sans chercher est celui qui a longtemps cherché sans trouver.(Bachelard)
    La connaissance s'acquiert par l'expérience, tout le reste n'est que de l'information.(Einstein)

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2019
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Aisne (Picardie)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2019
    Messages : 21
    Points : 20
    Points
    20
    Par défaut
    bonsoir,

    merci Fred de m'avoir répondu.

    voilà, je me suis sérieusement mis au classe cet après midi, le code ci-dessous devrait être nettement mieux au niveau de la classe.

    Si vous avez des suggestions elles sont toujours les biens venues...

    Il reste l'exception à régler si l'API ne me renvoie pas une information que je demande comme copyright dans mon code. L'information n'est pas toujours présente au niveau de l'API...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
     
    # coding: utf-8
    import requests
    import webbrowser
     
    """ Statut des réponses
    Les codes de retour HTTP de l'API sont : 200 si la requête a été acceptée et
    que des données sont retournées ;
    un code de la centaine des 400 si la requête est erronée ou le code 500
    s'il y a une erreur du côté du serveur.
    Les codes suivants sont actuellement utilisés :
     
    200: OK
    400: Paramètre manquant, ou valeur incorrecte.
    401: Authentification nécessaire (token absent ou invalide)
    403: Action non autorisée (URL non autorisée avec votre abonnement)
    404: Page inaccessible (URL inconnue)
    500: Erreur interne au serveur, contactez-nous
    503: L'API est momentanément indisponible, réessayez dans quelques minutes
     
    """
    class ApiNasa():
     
        def __init__(self):
     
            self.nasa_key = 'zzzzzzzzzzzzzzlplpzzlpzlpzplzppzlpzl'
            self.url_base = 'https://api.nasa.gov/planetary/apod?api_key='
            self.url_planetary = self.url_base + self.nasa_key
     
            self.date = ''
            self.explanation = ''
            self.url_hdimage = ''
            self.url_imagesSlow = ''
            self.apod_data_json = ''
            self.final_str = ''
            self.copyright = ''
     
            self.get_nasa_api()
     
        def format_response_nasa(self, apod):
     
            try:
                #self.copyright = apod ['copyright']
     
                self.date = apod ['date']
                self.explanation = apod ['explanation']
                self.url_hdimage = apod ['hdurl']
                self.url_imagesSlow = apod ['url']
     
     
                #self.copyright = "\nCopyright:\t" + str(copyright) + '\n'
     
                self.date = "\nDate:\t\t" + str(self.date) + '\n'
                self.explanation = "Explanation:\t" + str(self.explanation) + '\n\n'
                self.url_hdimage = "UrlHdImage:\t" + str(self.url_hdimage) + '\n'
                self.url_imagesSlow = "UrlImageSlow:\t" + str(self.url_imagesSlow) + '\n'
     
                self.final_str = self.date + self.explanation + self.url_hdimage + self.url_imagesSlow
            except:
                print(" There are a problem retrieving that information")
     
            return self.date + self.explanation + self.url_hdimage + self.url_imagesSlow
     
        def get_nasa_api(self):
     
            try:
                send_requests = requests.get(self.url_planetary)
                self.apod_data_json = send_requests.json()
     
            except Exception as e:
                print("Erreur:", e)
            else:
                print(self.format_response_nasa(self.apod_data_json))
            return(self.format_response_nasa(self.apod_data_json))
     
    if __name__ == "__main__":
        print("\nMy script is directly executed...\n ")
        app = ApiNasa()
     
        # print(app.date)
        # print(app.apod_data_json)
        # print(app.explanation)
        # print(app.final_str)
        # print(app.nasa_key)
        # print(app.url_base)
        # print(app.url_hdimage)
        # print(app.url_planetary)
        # print(app.url_imagesSlow)
     
    else:
        print("My script is imported by an other module... ")

  4. #4
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 283
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 283
    Points : 36 770
    Points
    36 770
    Par défaut
    Citation Envoyé par JC JC Voir le message
    Il reste l'exception à régler si l'API ne me renvoie pas une information que je demande comme copyright dans mon code. L'information n'est pas toujours présente au niveau de l'API...
    Avant de jouer avec les "class", çà serait bien de vous inquiéter des structures de données que retourne send_requests.json() car çà ne devrait pas être autre chose qu'une composition de listes et de dictionnaires qui sont des types de bases.

    Cela vous permettrait de reformuler votre question en "comment savoir si la clef d'un dictionnaire existe" ou "comment récupérer une valeur par défaut lorsque la clef d'un dictionnaire n'existe pas". Et de parcourir dans votre tuto préféré le chapitre qui parle des dictionnaires pour voir comment faire çà.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2019
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Aisne (Picardie)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2019
    Messages : 21
    Points : 20
    Points
    20
    Par défaut
    Wiztricks,

    A la base, ma question n'a rien à voir avec les classes... j'ai fait un début de classe (que je ne maitrise pas du tout), mais c'était pour récupérer les informations dans des variables en dehors des fonctions.
    Ma vrai question était de gérer l'erreur qui survient quand une donnée est manquante comme le copyright qui n'est pas toujours indiqué dans le Json.

    Ensuite, Fred a commenté mon message, et j'ai regardé les classes pour faire quelques choses de propre tout simplement... (apparement pas d'erreurs, vous m'avez rien dit )

    Vous êtes surement tous experts et de longues années d'expérience.
    Pour ma part, je débute, donc pas facile de poser la bonne question qui va au but.

    Je passe tout mon temps sur Python, donc des fois la fatigue est présente et le cerveau doit bugger

    Merci Wiztricks de me montrer le chemin. En plus, je le sais que c'est un dictionnaire ou une liste... mais comme je dis le cerveau ne veut plus des fois

    Maintenant, au travail... et bonne journée à vous!

    Jean Christophe

  6. #6
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2019
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Aisne (Picardie)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2019
    Messages : 21
    Points : 20
    Points
    20
    Par défaut
    Bonsoir,

    voilà sans classe.

    Vous en pensez quoi?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
     
     
    # coding: utf-8
    import requests
    import webbrowser
     
    nasa_key = 'dfefifefefefefefefokofoekofkeokeoknceveneue'
    url_base = 'https://api.nasa.gov/planetary/apod?api_key='
    url_planetary = url_base + nasa_key
     
    def format_response_nasa(apod):
        #Formattage des informations reçues
        try:
            copyright = apod ['copyright']
            date = apod ['date']
            explanation = apod ['explanation']
            url_hdimage = apod ['hdurl']
            url_imagesSlow = apod ['url']
            title = apod ['title']
     
            copyright = "\nCopyright:\t" + str(copyright) + '\n'
            date = "\nDate:\t\t" + str(date) + '\n'
            explanation = "Explanation:\t" + str(explanation) + '\n\n'
            url_hdimage = "UrlHdImage:\t" + str(url_hdimage) + '\n'
            url_imagesSlow = "UrlImageSlow:\t" + str(url_imagesSlow) + '\n'
            title = "\nTitre:\t\t" + str(title) + '\n'
     
            final_str = copyright \
            + title \
            + date \
            + explanation \
            + url_hdimage \
            + url_imagesSlow
     
        except:
            print("❌There are a problem retrieving that information")
     
        return final_str
     
    def get_nasa_api():
     
        try:
            response = requests.get(url_planetary)
     
            if response.status_code == 200:
                print('✅Connexion réussie!\n')
            elif response.status_code == 404:
                print('demande Not Found.')
     
            apod_data_json = response.json()
            content = response.content
            print("✅content brut:\n",content)
            print(type(("content brut:\n",content)))
            print("\n✅Apod_data_json brut:\n",apod_data_json)
        except Exception as e:
            print("❌Erreur:", e)
     
        print("Print self.apod_data_json['date']:", apod_data_json['date'])
        print(type(apod_data_json))
     
        if "copyright" not in apod_data_json:
            apod_data_json ['copyright'] = 'Donnée non fournie' # ajout à la fin
            print("\n✅Ajout de la clé copyright\n")
            print(apod_data_json)
        else:
            print("\n✅Ok pour Copyright, il est déjà dans le dictionaire")
     
        return print("\n✅Apod_data_json avec format:\n",format_response_nasa(apod_data_json))
     
    if __name__ == "__main__":
        print("\n✅My script is directly executed...\n ")
        app = get_nasa_api()
     
    else:
        print("✅My script is imported by an other module... ")
    Résultat:


    ✅My script is directly executed...

    ✅Connexion réussie!

    ✅content brut:
    b'{"date":"2019-10-16","explanation":"How do binary stars form? To help find out, ESO\'s Atacama Large Millimeter Array (ALMA) recently captured one of the highest resolution images yet taken of a binary star system in formation. Most stars are not alone -- they typically form as part of a multiple star systems where star each orbits a common center of gravity. The two bright spots in the featured image are small disks that surround the forming proto-stars in [BHB2007] 11, while the surrounding pretzel-shaped filaments are gas and dust that have been gravitationally pulled from a larger disk. The circumstellar filaments span roughly the radius of the orbit of Neptune. The BHB2007 system is a small part of the Pipe Nebula (also known as Barnard 59), a photogenic network of dust and gas that protrudes from Milky Way\'s spiral disk in the constellation of Ophiuchus. The binary star formation process should be complete within a few million years.","hdurl":"https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_1881.jpg","media_type":"image","service_version":"v1","title":"BHB2007: A Baby Binary Star in Formation","url":"https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_960.jpg"}\n'
    <class 'tuple'>

    ✅Apod_data_json brut:
    {'date': '2019-10-16', 'explanation': "How do binary stars form? To help find out, ESO's Atacama Large Millimeter Array (ALMA) recently captured one of the highest resolution images yet taken of a binary star system in formation. Most stars are not alone -- they typically form as part of a multiple star systems where star each orbits a common center of gravity. The two bright spots in the featured image are small disks that surround the forming proto-stars in [BHB2007] 11, while the surrounding pretzel-shaped filaments are gas and dust that have been gravitationally pulled from a larger disk. The circumstellar filaments span roughly the radius of the orbit of Neptune. The BHB2007 system is a small part of the Pipe Nebula (also known as Barnard 59), a photogenic network of dust and gas that protrudes from Milky Way's spiral disk in the constellation of Ophiuchus. The binary star formation process should be complete within a few million years.", 'hdurl': 'https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_1881.jpg', 'media_type': 'image', 'service_version': 'v1', 'title': 'BHB2007: A Baby Binary Star in Formation', 'url': 'https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_960.jpg'}
    Print self.apod_data_json['date']: 2019-10-16
    <class 'dict'>

    ✅Ajout de la clé copyright

    {'date': '2019-10-16', 'explanation': "How do binary stars form? To help find out, ESO's Atacama Large Millimeter Array (ALMA) recently captured one of the highest resolution images yet taken of a binary star system in formation. Most stars are not alone -- they typically form as part of a multiple star systems where star each orbits a common center of gravity. The two bright spots in the featured image are small disks that surround the forming proto-stars in [BHB2007] 11, while the surrounding pretzel-shaped filaments are gas and dust that have been gravitationally pulled from a larger disk. The circumstellar filaments span roughly the radius of the orbit of Neptune. The BHB2007 system is a small part of the Pipe Nebula (also known as Barnard 59), a photogenic network of dust and gas that protrudes from Milky Way's spiral disk in the constellation of Ophiuchus. The binary star formation process should be complete within a few million years.", 'hdurl': 'https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_1881.jpg', 'media_type': 'image', 'service_version': 'v1', 'title': 'BHB2007: A Baby Binary Star in Formation', 'url': 'https://apod.nasa.gov/apod/image/1910/BabyBinary_Alma_960.jpg', 'copyright': 'Donnée non fournie'}

    ✅Apod_data_json avec format:

    Copyright: Donnée non fournie

    Titre: BHB2007: A Baby Binary Star in Formation

    Date: 2019-10-16

    Explanation: How do binary stars form? To help find out, ESO's Atacama Large Millimeter Array (ALMA) recently captured one of the highest resolution images yet taken of a binary star system in formation. Most stars are not alone -- they typically form as part of a multiple star systems where star each orbits a common center of gravity. The two bright spots in the featured image are small disks that surround the forming proto-stars in [BHB2007] 11, while the surrounding pretzel-shaped filaments are gas and dust that have been gravitationally pulled from a larger disk. The circumstellar filaments span roughly the radius of the orbit of Neptune. The BHB2007 system is a small part of the Pipe Nebula (also known as Barnard 59), a photogenic network of dust and gas that protrudes from Milky Way's spiral disk in the constellation of Ophiuchus. The binary star formation process should be complete within a few million years.

    UrlHdImage: https://apod.nasa.gov/apod/image/191..._Alma_1881.jpg
    UrlImageSlow: https://apod.nasa.gov/apod/image/191...y_Alma_960.jpg

    [Finished in 1.153s]

  7. #7
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 823
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 823
    Points : 7 119
    Points
    7 119
    Par défaut
    Vous en pensez quoi?
    le module webbrowser ne semble pas utilisé, je me trompe ?

    L'exception ligne 35 est trop généraliste, il faudrait dans le meilleur des cas, prendre chaque erreur possible et là traiter de telle manière qu'on soit informé de comment résoudre l'erreur.
    Même chose ligne 55

    Est-ce que ça fonctionne comme vous voulez ? Si oui, c'est déjà très bien...
    Celui qui trouve sans chercher est celui qui a longtemps cherché sans trouver.(Bachelard)
    La connaissance s'acquiert par l'expérience, tout le reste n'est que de l'information.(Einstein)

Discussions similaires

  1. [Google Maps] Warning: error-messages#no-api-keys
    Par vivgar dans le forum APIs Google
    Réponses: 3
    Dernier message: 09/11/2016, 21h43
  2. [VB6] Registry Key Error
    Par jul54 dans le forum VB 6 et antérieur
    Réponses: 1
    Dernier message: 19/07/2006, 09h53
  3. Apparition Error : Object Required lors de l'intégration de mon outil
    Par Davboc dans le forum Général JavaScript
    Réponses: 11
    Dernier message: 22/05/2006, 16h34
  4. Réponses: 21
    Dernier message: 02/10/2005, 19h05

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo