issue146:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue146:python [2019/07/02 11:22] – créée auntiee | issue146:python [2019/07/16 23:06] (Version actuelle) – andre_domenech | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | Many regular readers of this column might have wondered why I haven' | + | **Many regular readers of this column might have wondered why I haven' |
- | Partially, the reason that I haven' | + | Partially, the reason that I haven' |
- | So, what exactly is JSON? | + | Beaucoup de lecteurs réguliers de cette rubrique ont pu s' |
+ | |||
+ | En partie, la raison pour laquelle je ne l'ai pas fait est que ça ne collait pas vraiment avec les sujets que j' | ||
+ | |||
+ | **So, what exactly is JSON? | ||
JSON stands for JavaScript Object Notation. It's a way to read, write and exchange data using an industry standard. Python has a library that deals with JSON data. | JSON stands for JavaScript Object Notation. It's a way to read, write and exchange data using an industry standard. Python has a library that deals with JSON data. | ||
Ligne 9: | Ligne 13: | ||
Here (top right) is a short sample of some JSON data (I borrowed this example from https:// | Here (top right) is a short sample of some JSON data (I borrowed this example from https:// | ||
- | Does this look somewhat familiar? It obviously has a key:value structure to it. Something like a dictionary in Python? Hmmmmm. | + | Does this look somewhat familiar? It obviously has a key:value structure to it. Something like a dictionary in Python? Hmmmmm.** |
+ | |||
+ | Alors, qu' | ||
+ | |||
+ | JSON veut dire JavaScript Object Notation. C'est une façon de lire, d' | ||
+ | |||
+ | En haut à droite, voici un court échantillon de données JSON (J'ai emprunté cet exemple sur https:// | ||
+ | |||
+ | Cela ne vous paraît-il pas familier ? Il a d' | ||
+ | |||
+ | **I was going to give you an example of getting and working with some JSON data by using Weather Underground, | ||
+ | |||
+ | Now, one of the requirements of the service is that you keep your secret key, well, secret, so I won't disclose my key. I'll use " | ||
- | I was going to give you an example of getting and working with some JSON data by using Weather Underground, | + | J' |
- | Now, one of the requirements of the service | + | L'un des desiderata du service |
- | Let's try it out. In addition to the API Key, you'll need to know the Latitude and Longitude of the area you are interested in. If you don't know your latitude and longitude off the top of your head, you can got to https:// | + | **Let's try it out. In addition to the API Key, you'll need to know the Latitude and Longitude of the area you are interested in. If you don't know your latitude and longitude off the top of your head, you can got to https:// |
latlon = 30.2672° N, -97.7431° W | latlon = 30.2672° N, -97.7431° W | ||
Ligne 25: | Ligne 41: | ||
(The additional calls can get somewhat complex, so we'll start with the full report). | (The additional calls can get somewhat complex, so we'll start with the full report). | ||
- | We'll start out by testing it in a browser. Put the above address into the browser address box. What you'll get back is quite a bit of data. If you are using Google Chrome, be sure to either add or enable JSONview extension. Firefox shows the JSON pretty print by default. | + | We'll start out by testing it in a browser. Put the above address into the browser address box. What you'll get back is quite a bit of data. If you are using Google Chrome, be sure to either add or enable JSONview extension. Firefox shows the JSON pretty print by default.** |
- | Here (next page, top right) is an abbreviated version of the output data, I purposely have edited it so that it contains only the header and the ' | + | Essayons-la. En plus de votre Clé d'API, vous devrez connaître les longitude et latitude de l' |
+ | |||
+ | latlon = 30.2672° N, -97.7431° W | ||
+ | |||
+ | Ainsi, notre appel sera... | ||
+ | |||
+ | https:// | ||
+ | |||
+ | (Les appels complémentaires peuvent être quelque peu complexes ; aussi, nous commençons par un rapport complet.) | ||
+ | |||
+ | Nous commencerons par le tester dans notre navigateur. Mettez l' | ||
+ | |||
+ | **Here (next page, top right) is an abbreviated version of the output data, I purposely have edited it so that it contains only the header and the ' | ||
Even though I limited it to the header and ‘currently’ sections, that’s a lot of data. Some of it might be important to you and some might not be so important. | Even though I limited it to the header and ‘currently’ sections, that’s a lot of data. Some of it might be important to you and some might not be so important. | ||
- | Before going any further, please save a copy of the data. For Chrome, right-click in the window and select "Save as..". In Firefox, you can simply click the save button. Then save the file as " | + | Before going any further, please save a copy of the data. For Chrome, right-click in the window and select "Save as..". In Firefox, you can simply click the save button. Then save the file as " |
+ | |||
+ | Voici (page suivante, en haut à droite) une version abrégée des données de sortie ; je l'ai délibérément modifiée pour qu' | ||
+ | |||
+ | Bien que je l'aie limitée à l' | ||
+ | |||
+ | Avant d' | ||
- | Now we can look at the information presented. We have some header information, | + | **Now we can look at the information presented. We have some header information, |
As you can see, there is a time field that is a UNIX timestamp, fields for summary, storm information (if there is a storm around), temperature, | As you can see, there is a time field that is a UNIX timestamp, fields for summary, storm information (if there is a storm around), temperature, | ||
- | Now let's start talking Python code. Create a new python file called ‘DarkskyJSON.py’ and put it in the same folder that you put the sample data download earlier. | + | Now let's start talking Python code. Create a new python file called ‘DarkskyJSON.py’ and put it in the same folder that you put the sample data download earlier.** |
- | Let’s start with the import section: | + | Maintenant, nous pouvons regarder l' |
+ | |||
+ | Comme vous pouvez le voir, il y a un champ « time » qui est l' | ||
+ | |||
+ | Maintenant, commençons à parler du code en Python. Créez un nouveau fichier Python appelé « DarkskyJSON.py » et placez-le dans le même dossier que les données échantillon téléchargées précédemment. | ||
+ | |||
+ | **Let’s start with the import section: | ||
import json | import json | ||
Ligne 49: | Ligne 89: | ||
You might be thinking that it makes sense to import the json library, but why requests and datetime libraries? The json library is obvious. The requests library is so we can make a http request directly from our program. And datetime is so we can convert the unix timestamp to a value that normal humans can understand at a glance. By the way, you might want to do a “pip3 list” in a terminal to see if requests is already installed. | You might be thinking that it makes sense to import the json library, but why requests and datetime libraries? The json library is obvious. The requests library is so we can make a http request directly from our program. And datetime is so we can convert the unix timestamp to a value that normal humans can understand at a glance. By the way, you might want to do a “pip3 list” in a terminal to see if requests is already installed. | ||
- | Ok. Moving on. The first task is to work with the local file (below), so we’ll write some code to load that JSON data. I made a copy of my local file – to keep it safe – and named it ‘sampledata.json’. | + | Ok. Moving on. The first task is to work with the local file (below), so we’ll write some code to load that JSON data. I made a copy of my local file – to keep it safe – and named it ‘sampledata.json’.** |
- | This should mainly look familiar to you. We’ve done it many times over the years. The only difference is that we are telling the JSON library to load the file and return it as a Python dictionary called ‘response’. When we print it to the terminal, it should look something like this… | + | Commençons par la section import : |
+ | |||
+ | import json | ||
+ | |||
+ | import requests | ||
+ | |||
+ | from datetime import datetime | ||
+ | |||
+ | Vous devez penser que ça a du sens d' | ||
+ | |||
+ | Bon. Avançons. La première tâche est de travailler avec notre fichier local (ci-dessous) ; aussi, nous écrirons un peu de code pour charger ces données JSON. J'ai fait une copie de mon fichier local - pour le conserver - et je l'ai appelé « sampledata.json ». | ||
+ | |||
+ | **This should mainly look familiar to you. We’ve done it many times over the years. The only difference is that we are telling the JSON library to load the file and return it as a Python dictionary called ‘response’. When we print it to the terminal, it should look something like this… | ||
+ | |||
+ | {' | ||
+ | |||
+ | # ' | ||
+ | |||
+ | Again, things like ‘nearestStormDistance’ and ‘‘precipType’ might not be available when you make your requests. We’ll deal with those in a few moments.** | ||
+ | |||
+ | Ceci devrait vous paraître assez habituel. Nous l' | ||
{' | {' | ||
Ligne 57: | Ligne 117: | ||
# ' | # ' | ||
- | Again, things like ‘nearestStormDistance’ and ‘‘precipType’ might not be available when you make your requests. We’ll deal with those in a few moments. | + | Une fois encore, pensez que des choses comme « nearestStormDistance |
- | Now, we’ll deal with the current time. That shows up in the ‘currently’ section as ‘time’. Since I live in the U.S., I’ll use a datetime format that makes it easy for me. I’m sure you know by now how to do it for yourself. But just in case, here’s a quick memory aid reminder link: https:// | + | **Now, we’ll deal with the current time. That shows up in the ‘currently’ section as ‘time’. Since I live in the U.S., I’ll use a datetime format that makes it easy for me. I’m sure you know by now how to do it for yourself. But just in case, here’s a quick memory aid reminder link: https:// |
tim = response[' | tim = response[' | ||
Ligne 69: | Ligne 129: | ||
Thu 05/23/2019 19:30:20 | Thu 05/23/2019 19:30:20 | ||
- | And that makes perfect sense to me. Now, to help break down the first line of the above code, ‘response’ is the full data packet we got from the JSON library read, ‘currently’ is the section we want to deal with, and ‘time’ is the key that we want. It’s just that simple. | + | And that makes perfect sense to me. Now, to help break down the first line of the above code, ‘response’ is the full data packet we got from the JSON library read, ‘currently’ is the section we want to deal with, and ‘time’ is the key that we want. It’s just that simple.** |
- | Now, we can play some simplifying games with the data so we don’t have to type so much. For example… | + | Maintenant, occupons-nous du temps présent. Il se présente sous « time » dans la section « currently ». Comme je vis aux USA, j' |
+ | |||
+ | tim = response[' | ||
+ | |||
+ | print(datetime.fromtimestamp(tim).strftime(" | ||
+ | |||
+ | Si la valeur de « time » est 1558447441, la sortie devrait être : | ||
+ | |||
+ | Thu 05/23/2019 19:30:20 | ||
+ | |||
+ | Et, pour moi, c'est compréhensible. Maintenant, pour nous aider à décomposer la première ligne du code ci-dessus, « response » est le paquet de données complet que nous avons obtenu par la lecture de la bibliothèque JSON, « currently » est la section que nous voulons traiter et « time » est la clé que nous voulons. Rien de plus simple. | ||
+ | |||
+ | **Now, we can play some simplifying games with the data so we don’t have to type so much. For example… | ||
currents = response[' | currents = response[' | ||
Ligne 80: | Ligne 152: | ||
'Light Rain' | 'Light Rain' | ||
- | Again, to carry on with the key:value dictionary analogy, ‘currents’ is the section of the data, ‘summary’ is the key and ‘Light Rain’ is the value. We also assigned (in the first line of the two) the entire ‘currently’ section of the returned data dictionary to a dictionary named currents. So now, when we want any value within the currents dictionary, we just put the key for that value in square brackets. Here (top) are a few more examples set as print statements. | + | Again, to carry on with the key:value dictionary analogy, ‘currents’ is the section of the data, ‘summary’ is the key and ‘Light Rain’ is the value. We also assigned (in the first line of the two) the entire ‘currently’ section of the returned data dictionary to a dictionary named currents. So now, when we want any value within the currents dictionary, we just put the key for that value in square brackets. Here (top) are a few more examples set as print statements.** |
- | And our output would look, using the above response data, something like this: | + | Maintenant, nous pouvons jouer à simplifier un peu les données pour en avoir moins à saisir. Par exemple : |
+ | |||
+ | currents = response[' | ||
+ | summary = currents[' | ||
+ | |||
+ | Si nous imprimons la variable summary, nous obtiendrons : | ||
+ | |||
+ | 'Light Rain' | ||
+ | |||
+ | À nouveau, pour faire l' | ||
+ | |||
+ | **And our output would look, using the above response data, something like this: | ||
| | ||
Ligne 94: | Ligne 177: | ||
We’ll use the precipType key as an example. If it’s raining or snowing, it will be available, but if it’s sunny, it won’t be in the data structure. Here’s how: | We’ll use the precipType key as an example. If it’s raining or snowing, it will be available, but if it’s sunny, it won’t be in the data structure. Here’s how: | ||
+ | |||
+ | if ' | ||
+ | |||
+ | | ||
+ | |||
+ | Et notre sortie ressemblera, | ||
+ | |||
+ | | ||
+ | Feels like: 90.54 | ||
+ | Dew point: 72.43 | ||
+ | | ||
+ | |||
+ | Ça n'est pas aussi difficile qu'il y paraissait au début de cet article, n' | ||
+ | ••s' | ||
+ | ••s' | ||
+ | |||
+ | Nous utiliserons la clé precipType comme exemple. S'il pleut ou neige, elle sera disponible, mais si le soleil brille, elle ne sera pas présente dans les données. Voici comment : | ||
if ' | if ' | ||
Ligne 99: | Ligne 199: | ||
| | ||
- | So, if the data structure response[‘currently’] has a key of ‘precipType’, | + | |
+ | **So, if the data structure response[‘currently’] has a key of ‘precipType’, | ||
Now we’ll look at the way to get the live data. We start with defining a number of variables so we can just “plug and play” into a string. Here’s the code (top right). | Now we’ll look at the way to get the live data. We start with defining a number of variables so we can just “plug and play” into a string. Here’s the code (top right). | ||
Ligne 106: | Ligne 207: | ||
timeout = 10 # 10 second timeout | timeout = 10 # 10 second timeout | ||
+ | |||
+ | session = requests.Session() | ||
+ | |||
+ | response = session.get(url, | ||
+ | |||
+ | Aussi, si dans la structure de données de réponse[‘currently’] la clé « precipType » est présente, nous l' | ||
+ | |||
+ | Maintenant, regardons, la manière d' | ||
+ | |||
+ | Notez que l' | ||
+ | |||
+ | timeout = 10 # limite de temps de 10 secondes | ||
session = requests.Session() | session = requests.Session() | ||
Ligne 111: | Ligne 224: | ||
response = session.get(url, | response = session.get(url, | ||
- | Now we have the JSON data structure in our dictionary, just like we read it from the local file earlier. So now, you can comment our four lines that read the local file, and add the lines above. This way, if you want to play some more, you can still work with the local file by commenting out the “live” request code and uncommenting the local file-read code. | + | **Now we have the JSON data structure in our dictionary, just like we read it from the local file earlier. So now, you can comment our four lines that read the local file, and add the lines above. This way, if you want to play some more, you can still work with the local file by commenting out the “live” request code and uncommenting the local file-read code. |
I’ve got a fully functioning demonstration program that I’ve created (without my secret key of course, but you can put yours in) and I’ve put it up on pastebin. The address is https:// | I’ve got a fully functioning demonstration program that I’ve created (without my secret key of course, but you can put yours in) and I’ve put it up on pastebin. The address is https:// | ||
- | For those of you who don’t live in the US, and/or don’t use English as your primary language, there are various options for you that keep you from having to write Fahrenheit to Celsius conversion functions, and will present the display text in a language that you want. For example, if you want to see the output in Norwegian, you can pass “nb” within the URL as language and “si” as the units. Below is a modified URL string creation statement that you can use to set things up correctly. Set ‘unitstouse’ as “si” and ‘langtouse’ to ‘nb’. If you want Spanish, use “es”. If you want German, use “de”, and so on. It’s all in the API docs. | + | For those of you who don’t live in the US, and/or don’t use English as your primary language, there are various options for you that keep you from having to write Fahrenheit to Celsius conversion functions, and will present the display text in a language that you want. For example, if you want to see the output in Norwegian, you can pass “nb” within the URL as language and “si” as the units. Below is a modified URL string creation statement that you can use to set things up correctly. Set ‘unitstouse’ as “si” and ‘langtouse’ to ‘nb’. If you want Spanish, use “es”. If you want German, use “de”, and so on. It’s all in the API docs.** |
- | Where to go from here? Well, if you go back to the DarkSky API Documentation page I directed you to before, they have a full list of all the keys that are available. They include daily forecasts for the current day plus seven days, hourly forecasts, changing the output language and units of measurements, | + | Maintenant nous avons la structure de données en JSON dans notre dictionnaire, |
+ | |||
+ | J'ai pris le programme de démonstration complètement fonctionnel que j' | ||
+ | |||
+ | Pour ceux qui ne vivent pas aux USA, et/ou dont l' | ||
+ | |||
+ | **Where to go from here? Well, if you go back to the DarkSky API Documentation page I directed you to before, they have a full list of all the keys that are available. They include daily forecasts for the current day plus seven days, hourly forecasts, changing the output language and units of measurements, | ||
If you are a “weather geek” like me, this can be a very fun project. It would be pretty easy to put this code into a GUI. We might do that sometime in the future. | If you are a “weather geek” like me, this can be a very fun project. It would be pretty easy to put this code into a GUI. We might do that sometime in the future. | ||
- | Start up the Time Machine! | + | Start up the Time Machine!** |
+ | |||
+ | Où aller à partir de là ? Eh bien, si vous retournez à la page de documentation de l'API DarSky vers laquelle je vous ait dirigé précédemment, | ||
+ | |||
+ | Si vous êtes un « fana de météo » comme moi, ceci peut être un très amusant projet. Il devrait être assez facile de mettre ce code dans une interface graphique. Nous pourrions faire cela à un moment quelconque dans le futur. | ||
+ | |||
+ | Démarrez la machine à remonter le temps ! | ||
issue146/python.1562059362.txt.gz · Dernière modification : 2019/07/02 11:22 de auntiee