项目中用python开发,要对外接口时,根据场景不同,一般有两种方式:
1)外部调用python接口,返回数据
2)接口主动向外部推送数据
1)外部调用python接口,返回数据
这种方式一般可以通过http接口,定义接口的ip和端口,外部通过ip和端口调用,调用的程序再返回结果。
接口服务代码如下:
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 | import flask import json from flask import request ''' flask: web框架,通过flask提供的装饰器@server.route()将普通函数转换为服务 登录接口,需要传url、username、passwd ''' # 创建一个服务,把当前这个python文件当做一个服务 server = flask.Flask(__name__) @server .route( '/login' , methods = [ 'get' , 'post' ]) def login(): # 获取通过url请求传参的数据 usename = request.args.get( 'name' ) password = request.args.get( 'pwd' ) #这里可以加入核心功能代码 resu = { 'code' : 200 , 'result' : 'success!' } #返回数据 return json.dumps(resu, ensure_ascii = False ) # 将字典转换为json串, json是字符串 if __name__ = = '__main__' : server.run(debug = True , port = 80 , host = '0.0.0.0' ) # 指定端口、host设为0.0.0.0代表不管几个网卡,任何ip都可以访问 |
2)接口主动向外部推送数据
接口对外主动反馈数据的方式也有多种实现方式,其中python中requests库提供了非常方便的接口可以直接用。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/env python # -*- coding: utf-8 -*- import requests import json import datetime url = '推送数据的目标网址' headers = { 'content-type' : "application/json" , 'Authorization' : 'APP appid = 4abf1a,token = 9480295ab2e2eddb8' } #数据头 body = { "Data" : "需要推送的数据" , "Time" : str (datetime.datetime.now())} response = requests.post(url, data = json.dumps(body), headers = headers) print (response.text, response.status_code) |
发表评论