windows python flask返回json数据
  TEZNKK3IfmPf 2023年11月14日 19 0
 

实战1

data/pvuv.txt

日期  	PV	UV
2020/7/18	15000	150
2020/7/19	15001	151
2020/7/20	15002	152
2020/7/21	15003	153
2020/7/22	15004	154
2020/7/23	15005	155
2020/7/24	15006	156
2020/7/25	15007	157
2020/7/26	15008	158
2020/7/27	15009	159
2020/7/28	15010	160
2020/7/29	15011	161
2020/7/30	15012	162
2020/7/31	15013	163
2020/8/1	15014	164
2020/8/2	15015	165
2020/8/3	15016	166
2020/8/4	15017	167
2020/8/5	15018	168
2020/8/6	15019	169
2020/8/7	15020	170

app.py

from flask import Flask, render_template, request
import json
app = Flask(__name__)
def read_pvuv_data():
    """ read pv uv data return: list , ele:(pdate, pv, uv)"""
    
    data = []
    with open("./data/pvuv.txt") as fin:
        is_first_line =True
        for line in fin:
            if is_first_line:
                is_first_line = False
                continue
            line = line[:-1] #\n
            pdate, pv, uv = line.split("\t")
            data.append((pdate, pv, uv))
    return data
@app.route("/getjson")
def getjson():
    # read json
    data = read_pvuv_data()
    # return html
    return json.dumps(data)

if __name__ == '__main__':
    app.run(host='192.168.1.4',debug=True)

执行,界面访问
windows python flask返回json数据

test_get_json.py

利用api接口处理json文件

import requests
import json

url = "http://192.168.1.4:5000/getjson"

r = requests.get(url)

print(r.status_code)
for row in json.loads(r.text):
    print(row)

执行python test_get_json.py

200
['2020/7/18', '15000', '150']
['2020/7/19', '15001', '151']
['2020/7/20', '15002', '152']
['2020/7/21', '15003', '153']
['2020/7/22', '15004', '154']
['2020/7/23', '15005', '155']
['2020/7/24', '15006', '156']
['2020/7/25', '15007', '157']
['2020/7/26', '15008', '158']
['2020/7/27', '15009', '159']
['2020/7/28', '15010', '160']
['2020/7/29', '15011', '161']
['2020/7/30', '15012', '162']
['2020/7/31', '15013', '163']
['2020/8/1', '15014', '164']
['2020/8/2', '15015', '165']
['2020/8/3', '15016', '166']
['2020/8/4', '15017', '167']
['2020/8/5', '15018', '168']
['2020/8/6', '15019', '169']
['2020/8/7', '15020', '170']
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   40   0   0 python开发语言
TEZNKK3IfmPf