标签:img 运行 auto mock bsp api ascii als mysq
1、开发一个get接口
1 import flask 2 import json 3 """ 4 flask轻量级的web开发框架 5 """ 6 7 # 初始化一个服务 8 server = flask.Flask(__name__) 9 10 11 @server.route(‘/api/payment‘) # 装饰器:一个接口 12 def payment(): 13 data = {"code":301,"msg":"支付处理中","amount":30000} 14 return json.dumps(data,ensure_ascii=False) 15 16 # http://localhost:9999/api/payment 17 # http://127.0.0.1:9999/api/payment 18 server.run(port=9999,debug=True)
结果:
2、post接口
1 import flask 2 import json 3 """ 4 flask轻量级的web开发框架 5 """ 6 7 # 初始化一个服务 8 server = flask.Flask(__name__) 9 10 11 @server.route(‘/api/payment‘) # 装饰器:一个get接口 12 def payment(): 13 data = {"code":301,"msg":"支付处理中","amount":30000} 14 return json.dumps(data,ensure_ascii=False) 15 16 17 @server.route(‘/api/login‘,methods=[‘post‘]) # 装饰器:一个post接口 18 def login(): 19 data = {"code":0,"msg":"登录成功"} 20 return json.dumps(data,ensure_ascii=False) 21 22 # http://localhost:9999/api/payment 23 # http://127.0.0.1:9999/api/payment 24 server.run(port=9999,debug=True)
结果:
3、启动服务,非本地也可以访问
1 # 启动后,别人可以访问 2 # http://ip:9999/api/payment 3 server.run(host=‘0.0.0.0‘,port=9999,debug=True)
运行后,手机访问(同一个局域网):
4、实例
import flask import json,pymysql """ flask轻量级的web开发框架 """ # 初始化一个服务 server = flask.Flask(__name__) def op_mysql(sql): connect = pymysql.connect(host=‘xxx‘, port=3306, db=‘xxx‘, password=‘xxx‘, charset=‘utf8‘, autocommit=True, user=‘jxz‘ ) cursor = connect.cursor(pymysql.cursors.DictCursor) try: cursor.execute(sql) except Exception as e: result = {‘error‘:‘sql错误‘} else: result = cursor.fetchall() finally: cursor.close() connect.close() return result @server.route(‘/api/payment‘) # 装饰器:一个get接口 def payment(): status = flask.request.values.get(‘status‘) if status == ‘success‘: data = {"code": 0, "msg": "支付成功", "amount": 30000} elif status == ‘process‘: data = {"code":305,"msg":"支付处理中"} elif status == ‘fail‘: data = {"code": -1, "msg": "支付失败"} else: data = {"code": 400, "msg": "支付状态错误"} return json.dumps(data,ensure_ascii=False) @server.route(‘/api/login‘,methods=[‘post‘]) # 装饰器:一个post接口 def login(): data = {"code":0,"msg":"登录成功"} return json.dumps(data,ensure_ascii=False) @server.route(‘/api/account/data‘) def account_data(): #传入参数 account_name = flask.request.values.get(‘account‘) # 获取json格式的参考 # args = flask.request.json.get(‘xxx‘) if account_name: result = op_mysql(‘select * from gtm_account where account="%s";‘% account_name) else: result = op_mysql(‘select * from gtm_account;‘) data = {"code":0,"msg":"success","data":result} return data # # 启动服务:启动后只能本地访问 # # http://localhost:9999/api/payment # # http://127.0.0.1:9999/api/payment # server.run(port=9999,debug=True) # 启动服务:启动后别人可以访问 # http://ip:9999/api/payment # debug=True表示调试模式,改了之后立即生效,不需要重新启动服务 server.run(host=‘0.0.0.0‘,port=9999,debug=True)
结果1:
结果2:
结果3:
标签:img 运行 auto mock bsp api ascii als mysq
原文地址:https://www.cnblogs.com/tour8/p/13060083.html