• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
python中Flask模块的使用

1.简介

在服务器上运行Flask接口,就能使用requests模块获取该接口的值。

先运行接口文件,再运行requests文件,即可获取值。

2.示例

2.1一个简单的flask接口

 1 import json
 2 from flask import Flask, request
 3 
 4 # python类型
 5 data = {
 6     'name': 'John',
 7     'age': 18,
 8     'location': 'nanjing'
 9 
10 }
11 
12 # 编码为json类型
13 en_json = json.dumps(data)
14 print "data类型:", type(data)
15 print "en_json类型:", type(en_json)
16 
17 app = Flask(__name__)
18 
19 
20 @app.route('/getmsg')
21 def senddata():
22     # 获取url中传递的参数时,使用request.args.get()或request.args[]
23     status = request.args['status']
24     print 'status的类型为', type(status)
25     if status == 'ok':
26         return en_json
27 
28 
29 if __name__ == '__main__':
30     app.run(host='127.0.0.1', port=8080, debug=False)

2.2通过requests获取值

 1 # -*- coding: utf-8 -*-
 2 import requests
 3 
 4 payload = {'status': 'ok', 'data': 'some messages'}
 5 r = requests.get(url='http://127.0.0.1:8080/getmsg', params=payload)
 6 # dict类型
 7 print 'r.json的类型:', type(r.json())
 8 print r.json()
 9 # str类型
10 print 'r.content的类型:', type(r.content)
11 print r.content
12 # 获取数据
13 print r.json()['name']
14 print r.content[1:10]

!!!

 

posted on 2017-12-21 17:01  火磷  阅读(9004)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3