基于python和flask实现http接口过程解析

时间:2022-06-29 02:12:33

为什么要做这个?

mock 第三方服务时,需要使用,另外包括自身开发,有时也会用到python

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 18:52:42 2020
 
@author: ansonwan
"""
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
app.debug = True
 
@app.route('/http/query/',methods=['post'])
def post_http():
  if not request.data:  #检测是否有数据
    return ('fail')
  params= request.data.decode('utf-8')
  #获取到POST过来的数据,因为我这里传过来的数据需要转换一下编码。根据晶具体情况而定
  prams = json.loads(params)
  #把区获取到的数据转为JSON格式。
  return jsonify(prams)
  #返回JSON数据。
 
if __name__ == '__main__':
  app.run(host='127.0.0.1',port=1234)
  #这里指定了地址和端口号。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python2
# -*- coding: utf-8 -*-#请求http/query/接口
 
"""
Created on Fri Jun 12 18:55:07 2020
 
@author: ansonwan
"""
import requests,json
 
data = {
  "datatime":"2020-07-02"
}
url = 'http://127.0.0.1:1234/http/query/'
 
r = requests.post(url,data=json.dumps(data))
print(r.json())

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/ansonwan/p/12988557.html