requests模块请求和数据解析

1.Python创建接口

flask是python的第三方库,所以需要提前安装pip install flask

url和某个函数的绑定关系,当访问一个url时,会调用函数,函数的返回值会返回到前端

# flask是python开发
from flask import Flask

# 服务
app = Flask(__name__)


# url 调用的函数
def login():
    return 'login success'


# 返回json格式
def home():
    return {'msg': 0, 'data': 'welcome'}


# 返回html格式
def other():
    return '''\
    用户名:<input>
    密码:<input type= 'password'>
    '''


# 添加url
app.add_url_rule('/login', view_func=login)
app.add_url_rule('/', view_func=home)
app.add_url_rule('/other', view_func=other)

# 运行服务
app.run()

运行结果:

 2.访问接口

点击运行结果红色框里的链接,跳转到浏览器页面

 在链接后加上/login(/,/other)刷新页面可以看到调用login/home/other函数成功

 

使用postman来访问接口也是一样的

 3.requests

 pstman/jmeter/requests/soupui/浏览器:访问接口

requests只是一个http客户端

requests也是python的一个第三方库,所以使用前需要安装pip install requests

import requests

# 发送一个get
response = requests.get('http://127.0.0.1:5000/')
# 获取响应体
print(response.text)  # 字符串
print(response.content)  # bytes 字节,二进制
print(response.json())  # 字典

运行结果:

{"data":"welcome","msg":0}

b'{"data":"welcome","msg":0}\n'
{'data': 'welcome', 'msg': 0}

Guess you like

Origin blog.csdn.net/weixin_40611700/article/details/120842236