首页 > 解决方案 > 在 Django 上使用 postcodes.io API

问题描述

我正在努力实现这一目标:

使用 postcodes.io 获取每个邮政编码的纬度和经度,并将它们呈现在模板中每个商店位置旁边

我有一系列邮政编码到一个json文件中:

[
{
  "name": "St_Albans",
  "postcode": "AL1 2RJ"
},
{
  "name": "Hatfield",
  "postcode": "AL9 5JP"
},
{
  "name": "Worthing",
  "postcode": "BN14 9GB"
},
{
  "name": "Rustington",
  "postcode": "BN16 3RT"
},
{
  "name": "Eastbourne",
  "postcode": "BN23 6QD"
}, ...

等等...

我需要检查postcodes.io[0] 这些邮政编码的纬度和经度,并将这些坐标呈现在结果旁边json

我的问题不是关于如何呈现它们,而是关于如何在他们的网站上发布我的 json 邮政编码,并获得每个人各自的纬度和经度。

我在纯python上做这个,有什么想法吗?

0.- https://postcodes.io/docs

标签: pythonjsondjango

解决方案


您可以尝试requests。试试这样:

resp = requests.get('https://api.postcodes.io/postcodes/BN14 9GB')
resp.json()

或者

data = {  
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}

resp = requests.post('https://api.postcodes.io/postcodes/', data=data)
resp.json()

将这些与您的 json 文件集成:

json_data = open('path_to/postcodes.json').read()

for i in json_data:
    post_code = i.get('postcode')
    resp = requests.get('https://api.postcodes.io/postcodes/{}'.format(postcode))
    i.update({'latitude': resp.json().get('latitude'), 'longitude': resp.json().get('longitude')})

print(json_data)

推荐阅读