[py]requests+json模块处理api数据,flask前台展示

需要处理接口json数据,过滤字段,处理字段等.

一大波json数据来了

参考: https://stedolan.github.io/jq/tutorial/

https://api.github.com/repos/stedolan/jq/commits?per_page=5

  • json数据结构

requests+json模块处理api数据

参考:
https://github.com/requests/requests
http://blog.51cto.com/haohaozhang/1668761

思路: requests访问api,返回一大段json(列表),对这个列表来操作

import requests
import json
r = requests.get('https://api.github.com/repos/stedolan/jq/commits?per_page=5')
s = r.json()

# 这里将结果s当列表操作处理即可.
for i in s:
    # print i['commit']['message']
    print i['commit']['author']['name']

---
Paul Chvostek
Larry Aasen
Nicolas Williams
David Fetter
Nicolas Williams

获取api数据,flask展示


from __future__ import unicode_literals
from flask import Flask
import requests
import json

app = Flask(__name__)


@app.route("/")
def index():
    # 获取api数据
    data = requests.get('https://api.github.com/repos/stedolan/jq/commits?per_page=5')
    s_data = data.json()
    author = []
    for i in s_data:
        author.append(i['commit']['author']['name'])
    # 组合html
    http = """
        <html>
        <head><meta charset="UTF-8"></head>
        <body>
            <h1>name</h1>
            %s <br>
        </body>
        </html>
    """ % author
    # 返回字符串
    return http


app.run(debug=True)

原文地址:https://www.cnblogs.com/iiiiiher/p/8242586.html