星球大战API获取请求和构建命令行

2024-06-28 19:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用来自http://swapi.co/api/的星球大战API。这是我为《星球大战》的API问题所做的工作。代码工作并打印出我想要的准确输出。我想看看如何把这个问题变成一个命令行工具。你知道吗

你是星球大战叛军的后勤协调员,负责计划部队部署

你需要一个工具来帮助找到有足够载客量的星际飞船和驾驶它们的飞行员

# Build a CLI tool that takes as its single argument the number of people that 
# need to be transported and outputs a list of candidate pilot and starship names 
# that are each a valid possibility. 
# Assume that any pilot can be a candidate regardless of allegiance. 
# Assume the entire group of passengers must fit in a single starship. 

# You may skip starships with no pilots or with unknown passenger capacity.  
# Your tool must use the Star Wars API (http://swapi.co) to obtain the necessary data.



# You may not use any of the official Star Wars API helper libraries but can use any other libraries you want 
# (http client, rest client, json).



# Example usage:

# $ ./find-pilots-and-ships 10

# Luke Skywalker, Imperial shuttle

# Chewbacca, Imperial shuttle

# Han Solo, Imperial shuttle

# Obi-Wan Kenobi, Trade Federation cruiser

# Anakin Skywalker, Trade Federation cruiser

Python 3 solution

import sys
import requests
import json
import urllib.parse

#number of pages in JSON feed

def print_page(page_num, num_passenger):
    endpoint = "https://swapi.co/api/starships/?"
    type = 'json'

    #specifies api parameters
    url = endpoint + urllib.parse.urlencode({"format": type, "page": page_num})

    #gets info
    json_data = requests.get(url).json()
    # number_of_ship = json_data['count']
    if 'results' in json_data:
      for ship in json_data['results']:
          if has_pilot(ship) and has_enough_passenger(ship, num_passenger):
              print_pilots_on(ship)

def get_pilot_name(pilot):
    type = 'json'

    #specifies api parameters
    url = pilot

    #gets info
    json_data = requests.get(url).json()
    return json_data["name"]

def print_pilots_on(ship):
    for pilot in ship['pilots']:
       print(get_pilot_name(pilot), ship['name'])

def has_pilot(ship):
    if ship['pilots']:
      return True
    return False

def has_enough_passenger(ship, num):
    if ship['passengers'] != "unknown" and int(ship['passengers']) >= num:
      return True
    return False

def print_pilots_and_ships(num_passenger):

    page_list = [1,2,3,4,5,6,7,8,9]
    # list to store names

    for page in page_list:
        print_page(page, num_passenger)


if __name__ == '__main__':


Tags: andoftheinjsondataifdef
1条回答
网友
1楼 · 发布于 2024-06-28 19:22:44

由于程序都包含在函数中,因此可以使用input + dict来委托函数调用:

def get_pilots(arg1, arg2):
    #....
def print_pilots(arg1, arg2, kw1, kw2):
    #....

functions = {'get_pilots': get_pilots,
             'print_pilots': print_pilots}

func = None
while func is None:
    ans = input().split()
    func = functions.get(ans[0], None)

ans = ans[1:]
args = []
kwargs = {}
for i in ans :
    if '=' in i:
        kw, arg = i.split('=')
        # split keyword args
        kwargs[kw] = arg
    else:
        args.append(i)

# call function returned from dict with args and kwargs and print result 
print(func(*args, **kwargs))

现在您可以在调用input()时执行以下操作:

>>> get_pilots arg1 arg2 
# result from function call

以及关键字参数:

>>> print_pilots arg1 arg2 kw1=arg kw2=arg

呼叫转换为:

print_pilots(*[arg1, arg2],
             **{kw1: arg, kw2: arg})

相关问题 更多 >