【问题标题】:Calling a python API from another program从另一个程序调用 python API
【发布时间】:2017-10-14 20:25:09
【问题描述】:

我有一个 Python API,我正在尝试调用并打印给定 IP 范围的城市名称。 python API 如下所示:

import datetime as dt

from flask import Flask, jsonify, request



class IpRangeSearch:

    RANGES = {
        'Tokyo': [
            {'start': '10.10.0.0', 'end': '10.10.255.255'},
            {'start': '192.168.1.0', 'end': '192.168.1.255'},
        ],
        'Paris': [
            {'start': '10.12.0.0', 'end': '10.12.255.255'},
            {'start': '172.16.10.0', 'end': '172.16.11.255'},
            {'start': '192.168.2.0', 'end': '192.168.2.255'},
        ]
    }

    def __init__(self):
       pass

    def get_city(self, ip):
        for city, ipranges in self.RANGES.items():
            for iprange in ipranges:
                if ip >= iprange['start'] and ip <= iprange['end']:
                    return city


app = Flask(__name__)
ip_range_search = IpRangeSearch()



@app.route('/ip_city/<ip>')
def ip_city(ip):

    return jsonify({'city': ip_range_search.get_city(ip)})


if __name__ == '__main__':
    app.run(host='0.0.0.0')

我正在从另一个 python 程序调用 API:

import json
import oauth2 as oauth
import requests

response = requests.get("http://0.0.0.0:5000/ip_city/10.12.1.1")

print(response.status_code)
print(response.content)

理想情况下,上面的代码应该打印出来:

200
{
  "city": Paris
}

但它的印刷:

200
{
  "city": null
}

我不知道为什么,但是当我尝试运行 API 代码以将 json 结构解析为独立函数时 - 代码以正确的格式打印输出。

我做错了什么?

【问题讨论】:

  • 我认为get_city()返回城市,而不是打印它。
  • 找不到条目的情况你还没有处理。在这种情况下,您需要返回一个值。如果您希望在您的案例中找到一个值,您需要调试您的函数。
  • 我在 shell 中运行了这段代码,它确实返回了'Paris',所以基本代码看起来没问题。也许网络脚手架有问题?尝试将 ip 添加到返回的 jsonify dict,这样您就可以看到它显示并确保它被正确接收。
  • 以防万一这些 IP 地址只是示例并且您的实际数据不同,请注意字符串的比较可能与实际数字不同 - 即。 '2.2.2.2' 大于 '10.10.10.10'

标签: python json


【解决方案1】:

您的ip_city 函数返回json 对象,只需在requests 对象上调用json 函数

response = requests.get("http://0.0.0.0:5000/ip_city/10.12.1.1").json()

UPD:

也许IP没有在你的函数中找到,你的函数返回None

只需添加else 语句,并检查它。

def get_city(ip):
    for city, ipranges in RANGES.items():
        for iprange in ipranges:
            if ip >= iprange['start'] and ip <= iprange['end']:
                return city
    return 'IP not found'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多