python接口开发入门
Posted _雪辉_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python接口开发入门相关的知识,希望对你有一定的参考价值。
一、postman
首先介绍一款API调试工具postman。Postman一款非常流行的API调试工具。其实,开发人员用的更多。因为测试人员做接口测试会有更多选择,例如Jmeter、soapUI等。不过,对于开发过程中去调试接口,Postman确实足够的简单方便,而且功能强大。
官方网站:https://www.postman.com/downloads/
登陆后默认进入家目录
创建工作空间
调试接口
二、接口代码
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import pymysql
import os
import json
import time
import logging
from flask_cors import *
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,request,jsonify
app = Flask(__name__)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
log_path = 'logs/'
log_name = log_path + logdate + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
def __success(data=None):
"""返回成功
"""
if not data:
data = []
return jsonify({'success': True, 'msg': '', 'data': data})
@app.route('/index1', methods=['POST'])
def getcontent():
try:
db = pymysql.connect(
host='127.0.0.1',
port=33071,
user='dms',
passwd='dms',
database='sbtest',
charset='utf8mb4'
)
cursor = db.cursor()
sql = "select * from t1;"
cursor.execute(sql)
data = cursor.fetchall()
para = []
for i in data:
text = {'c1':i[0],'c2':i[1],'c3':i[2]}
para.append(text)
print(text)
return __success(para)
except BaseException as err:
print(err)
logger.error('Failed to open file', exc_info=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5590)
[root@zijie ~]# curl -X POST http://120.27.250.75:5590/index1
{"data":[{"c1":1,"c2":2,"c3":3},{"c1":2,"c2":3,"c3":4},{"c1":3,"c2":4,"c3":5}],"msg":"","success":true}
传入参数
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import pymysql
import os
import json
import time
import logging
from flask_cors import *
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
from flask import Flask,request,jsonify
app = Flask(__name__)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
log_path = 'logs/'
log_name = log_path + logdate + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
def __success(data=None):
"""返回成功
"""
if not data:
data = []
return jsonify({'success': True, 'msg': '', 'data': data})
@app.route('/index1', methods=['POST'])
def wheredata():
inputData = request.json.get('where')
wheredata = getcontent(inputData)
return wheredata
def getcontent(wheredata):
try:
db = pymysql.connect(
host='127.0.0.1',
port=33071,
user='dms',
passwd='dms',
database='sbtest',
charset='utf8mb4'
)
cursor = db.cursor()
sql = "select * from t1 where c1=%s;" %(wheredata)
cursor.execute(sql)
data = cursor.fetchall()
para = []
for i in data:
text = {'c1':i[0],'c2':i[1],'c3':i[2]}
para.append(text)
print(text)
return __success(para)
except BaseException as err:
print(err)
logger.error('Failed to open file', exc_info=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5590)
以上是关于python接口开发入门的主要内容,如果未能解决你的问题,请参考以下文章