python接口开发-入门级

一、安装Flask

cmd进入DOS界面,执行以下命令

pip install Flask

二、编写接口

  • 不带参数的get接口
import flask,json

server = flask.Flask(__name__) 

@server. route('/index',methods =['get'])

def index():
    res = {
     'msg':'这个是一个接口','msg_code':0}
    return json.dumps(res,ensure_ascii=False)
    
server.run(port=8999,debug = True,host='0.0.0.0') #host 本机ip

先运行,然后用JMeter调用该接口,如下
python接口开发-入门级_第1张图片
python接口开发-入门级_第2张图片

  • 带参数的post接口
import flask,json
server=flask.Flask(__name__)

@server.route('/index',methods=['post']) #post请求
def reg():
    username=flask.request.values.get('username') #要传的参数,get('')获取参数的值
    passwd=flask.request.values.get('passwd')#要传的参数,get('')获取参数的值
    
    if username and passwd:
        Ang = "admin"
        if username == Ang:
            res={
     'msg':'用户已存在','msg_code':2001}
        else:
            res={
     'msg':'用户不存在','msg_code':0}
    else:
        res={
     'msg':'必填字段未填,请查看接口文档','msg_code':1001} #1001表示必填接口未填
    return json.dumps(res,ensure_ascii=False)
server.run(port=8999,debug=True,host='0.0.0.0')

先运行,然后用JMeter调用该接口,如下

场景1 参数为空:
python接口开发-入门级_第3张图片
python接口开发-入门级_第4张图片

场景2 已存在用户:
python接口开发-入门级_第5张图片
python接口开发-入门级_第6张图片
场景3 用户不存在:
python接口开发-入门级_第7张图片
python接口开发-入门级_第8张图片

注释:

  1. __name __:代表当前这个python文件
  2. server = flask.Flask(__name __) :把当前这个python文件,当做一个服务
  3. @server. route(’/index’,methods =[‘get’]):只有在函数前加上@server.route (),这个函数才是个接口,不是一般的函数 。/index代表路径
  4. ensure_ascii=False 响应数据输入中文
  5. port是端口号,host=0.0.0.0表示只要在同一个局域网,如果其他人要访问,就通过你的电脑IP来进行访问
  6. username=flask.request.values.get(‘username’):#获取接口请求的参数

你可能感兴趣的:(#,python_Flask接口,python,接口)