【问题标题】:I'm new to flask api programming我是烧瓶 api 编程的新手
【发布时间】:2020-07-14 06:20:40
【问题描述】:

我的代码有问题,没有出现错误,但由于某种原因,我没有得到想要的结果 结果

这是用户将收到的“json”数据

books = [
  {'id': 0,
   'title': 'A fire Upon the Deep',
   'author': 'Vernor Vinge',
   'first_sentence': 'The coldsleep itself was dreamless.',
   'year_published': '1992'},
  {'id': 1,
   'title': 'The Ones Who Walk Away From Omelas',
   'author': 'Ursula K. Le Guin',
   'first_sentence': 'With a clamor of bells that set the swallows soaring, the \
    Festival of Summer came to the city Omelas, bright-towered by the sea.',
   'published': '1973'},
  {'id': 2,
   'title': 'Dhalgren',
   'author': 'Samuel R. Delany',
   'first_sentence': 'to wound the autumnal city.',
   'published': '1975'}
 ]

如果不存在 id,那么它会返回一条错误消息,因为每本书都有一个 id,所以它不应该看到该消息

@app.route('/api/v1/resource/books', methods=['GET'])
def api_id():
    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "Error: ID not provided. Please specify an ID"

    results = []

    for book in books:
        if book['id'] == id:
            results.append(book)

return jsonify(results)

【问题讨论】:

    标签: json python-3.x api dictionary


    【解决方案1】:

    也许,请求 url 类似于 http://localhost:5000/api/v1/resource/books/?id=1

    对于多个书籍 ID,它将类似于 http://localhost:5000/api/v1/resource/books/?id=1&id=2

    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    books = [
      {'id': 0,
       'title': 'A fire Upon the Deep',
       'author': 'Vernor Vinge',
       'first_sentence': 'The coldsleep itself was dreamless.',
       'year_published': '1992'},
      {'id': 1,
       'title': 'The Ones Who Walk Away From Omelas',
       'author': 'Ursula K. Le Guin',
       'first_sentence': 'With a clamor of bells that set the swallows soaring, the \
        Festival of Summer came to the city Omelas, bright-towered by the sea.',
       'published': '1973'},
      {'id': 2,
       'title': 'Dhalgren',
       'author': 'Samuel R. Delany',
       'first_sentence': 'to wound the autumnal city.',
       'published': '1975'}
     ]
       
    @app.route("/api/v1/resource/books/", methods=["GET"])
    def api_id():
    
        # This will look for 'id' in the url. If there's no id/ids, it will take None as default value
        bids = request.args.getlist('id')
        # if you are expecting to serve only one id at a time, use >> request.args.get('id')
    
        if bids:
            results = []
            for book in books:
                for bid in bids: # this for loop won't be required for strictly single id
                    if book['id'] == int(bid):
                        results.append(book)
            return jsonify(results)
        else:
            return "Error: ID not provided. Please specify an ID"
    
    if __name__ == "__main__":
        app.run()
    

    此代码对我有用。我希望它也适合你。

    请求网址:

    http://localhost:5000/api/v1/resource/books/?id=0&id=2

    输出:

    [{"author":"Vernor Vinge","first_sentence":"The coldsleep itself was dreamless.","id":0,"title":"A fire Upon the Deep","year_published":"1992"},{"author":"Samuel R. Delany","first_sentence":"to wound the autumnal city.","id":2,"published":"1975","title":"Dhalgren"}]
    

    请求网址:

    http://localhost:5000/api/v1/resource/books/?id=0

    输出:

    [{"author":"Vernor Vinge","first_sentence":"The coldsleep itself was dreamless.","id":0,"title":"A fire Upon the Deep","year_published":"1992"}]
    

    请求网址:

    http://localhost:5000/api/v1/resource/books/

    输出:

    Error: ID not provided. Please specify an ID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2014-07-05
      • 2021-12-25
      • 2021-09-04
      • 2020-02-10
      • 2017-11-09
      相关资源
      最近更新 更多