【问题标题】:Input CSV file of lat and long coordinates into API to extract the weather data?将经纬度坐标的 CSV 文件输入 API 以提取天气数据?
【发布时间】:2021-05-11 05:38:50
【问题描述】:

下面是我的代码,我在位置变量中使用了经纬度坐标,并通过坐标字符串将其附加到 URL。因为我有 CSV 文件,其中包含许多位置的纬度和经度坐标,然后调用该 CSV 文件作为此 API 的输入(需要身份验证)。 如何在此代码中输入 CSV 文件而不是位置变量?

import requests
import pprint

locations = [(13.84, -12.57), (12.21, -14.69)]

coordinates_str = ','.join(map(lambda a: ' '.join(f'{f:.3f}' for f in a), locations))

# Replace "poi-settings" with the endpoint you would like to call.

URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates={coordinates_str}'
TOKEN = 'TOKEN KEY'

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

# Send GET request to UBIconnect.
res = session.get(URL)
res.raise_for_status()

# Decode JSON response.
poi_info = res.json()
pprint.pprint(poi_info, indent=2, compact=True)

然后我尝试了这种方式:代替坐标str我做了这个

import requests
import pprint
import pandas as pd 

df = pd.read_csv(r'E:\route_points.csv')
print(df)


# Replace "poi-settings" with the endpoint you would like to call.
URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?'
TOKEN = 'API TOKEN'
params= {'coordinates':(df)}

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

# Send GET request to UBIconnect.
res = session.get(URL, params= params)
res.raise_for_status()

# Decode JSON response.
poi_info = res.json()
pprint.pprint(poi_info, indent=2, compact=True)

还是不行。

从文档调用 API 所需的格式为:

# Replace "poi-settings" with the endpoint you would like to call.
URL = 'https://ubiconnect-eu.ubimet.com:8090/poi-settings'
TOKEN = '<YOUR TOKEN GOES HERE>'

所以我用 pinpoint-data 替换了 poi-settings

URL = 'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates=longitude<space<latitude'

例如:我把一个坐标集放到API URL中

URL = 'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates=132.85 12.84'

然后通过上面的 URL 我得到那个位置的天气数据。

【问题讨论】:

标签: python api csv latitude-longitude weatherdata


【解决方案1】:

如果您只想从 CSV 文件一次提交一个坐标块,那么类似以下内容就足够了:

from itertools import islice
import requests
import pprint
import csv

def grouper(n, iterable):
    it = iter(iterable)
    return iter(lambda: tuple(islice(it, n)), ())


block_size = 10   # how many pairs to submit per request
TOKEN = 'TOKEN KEY'

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

with open('coordinates.csv', newline='') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)        # skip the header
    
    for coords in grouper(block_size, csv_input):
        coordinates = ','.join(f'{float(long):.3f} {float(lat):.3f}' for long, lat in coords)
        print(coordinates)
        
        URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates={coordinates}'

        # Send GET request to UBIconnect.
        res = session.get(URL)
        res.raise_for_status()
        
        # Decode JSON response.
        poi_info = res.json()
        
        pprint.pprint(poi_info, indent=2, compact=True)

(显然这没有经过测试 - 没有令牌)。确保您的 CSV 文件中没有空行。


要输出到文件添加输出文件:

with open('coordinates.csv', newline='') as f_input, open('output.json', 'w', encoding='utf-8')  as f_output:

并在pprint() 调用中使用它:

pprint.pprint(poi_info, f_output, indent=2, compact=True)
f_output.write('\n')    # add blank line if needed

【讨论】:

  • 谢谢,它正在工作!!但是 41,000 个坐标需要很长时间。是否有任何替代方法可以将所有坐标输入为列表或类似 [(13.84, -12.57), (12.21, -14.69),...... ..] 正如您在我的代码的第一个 sn-p 中看到的那样?
  • 这就是需要文档的原因。每次通话可能有最大金额?
  • 我通过'global'检查了帐户限制:{'per_day': {'current': 21186, 'max': None}, 'per_hour': {'current': 745758, 'max ': None}, 'per_month': {'current': 211523, 'max': None}}} 所以我认为没有每月限制..
  • 我已对其进行了更新,以展示如何按给定块大小的组提交
  • 再次感谢您的意见。它有所改进但仍然需要时间,但是当我将块输入为 41000 时,它崩溃了。如果我使用小块大小,则需要时间。
【解决方案2】:

希望这就是你要找的东西

import csv
locations = list()
with open("foo.csv") as csvf:
    csvreader = csv.DictReader(csvf)    
    for row in csvreader:
        locations.append((float(row["lat"]), float(row["long"])))
# now add your code
coordinates_str = ','.join(map(lambda a: ' '.join(f'{f:.3f}' for f in a), locations))

【讨论】:

  • 它应该可以工作,但奇怪的是它给出了这个错误:csvreader = csv.DictReader(csvf) NameError: name 'csv' is not defined
  • 我已编辑以包含导入语句。
  • 这是我得到的错误:文件“e:\API_code_edit.py”,第 9 行,在 位置.append(row["longitude"], row["latitude"] ) TypeError: list.append() 只接受一个参数(给定 2 个)
  • 能否再复制一遍代码试试?后来我注意到我错过了到元组的转换,我在之前的编辑中添加了它
  • 这个错误:coordinate_str = ','.join(map(lambda a: ' '.join(f'{f:.3f}' for f in a), locations)) ValueError: Unknown “str”类型对象的格式代码“f”
猜你喜欢
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2019-04-10
相关资源
最近更新 更多