Flask 是基于python的轻量级web开发框架,可以快速实现一个网站服务;
模拟一个第三方支付接口,通过前端访问并返回:
import flask import json
from flask import Flask,request server_name = flask.Flask(__name__) #定义服务名 @server_name.route('/api/payment',methods=['get']) #设置要访问的接口地址和请求方法 def payment(): status = request.values.get('status')#获取参数 if status == 'success': data = {"code":0,"msg":"支付成功","amount":30000} else: data = {"code":-1,"msg":"失败","amount":30000} return json.dumps(data,ensure_ascii=False) #返回参数 server_name.run(host='0.0.0.0',port=9999,debug=True) #运行,服务ip为本机地址
直接浏览器访问
#flask 参数传递:
1.get请求
request.args.get("key") 获取get请求参数
2.post请求
1/获取json:
data = request.get_data()
data = json.loads(data)
username = data['username']
2/获取json:
data = request.get_json()
username = data['username']
3、获取form表单:
username = request.form['username']
开发一个注册接口,并写入数据库,且密码加密存储
import flask import json import pymysql import hashlib #md5加密 server_name = flask.Flask(__name__) def op_mysql(mysql,one_tag=False): connect = pymysql.connect(host='118.24.3.40', user='jxz', password='123456', db='jxz', port=3306, charset='utf8', autocommit=True ) cursor = connect.cursor(pymysql.cursors.DictCursor) cursor.execute(mysql) if one_tag: result = cursor.fetchone() else: result = cursor.fetchall() cursor.close() connect.close() return result def md5(s,salt='www'): #加密,salt-加盐操作, md5加密后不可解密。 s = str(s) + salt m = hashlib.md5(s.encode()) return m.hexdigest() @server_name.route('/register',methods=['post']) def register(): username = flask.request.values.get('username') password = flask.request.values.get('password') cpwd = flask.request.values.get('cpwd') sql = 'insert into app_myuser (user_name,passwd) values ("%s","%s");' %(username,password) if username and password and cpwd: if password != cpwd: data = {'code': 400, 'msg': '两次输入密码不一致'} elif op_mysql(sql): data = {'code': 401, 'msg': '用户已经存在'} else: password = md5(password) insert_sql = 'insert into app_myuser (user_name,passwd) values ("%s","%s");' %(username,password) #密码加密后插入 op_mysql(insert_sql) data = {'code': 0, 'msg': '注册成功'} else: data = {'code': 400, 'msg': '必填参数不能为空'} return json.dumps(data,ensure_ascii=False)
开发一个支付接口,传入token,并校验、获取userid、更新数据库
def op_redis(key,value=None,expire=60*60*2): #请求redis,根据token获取 userid r = redis.Redis(host='118.24.3.40',password='HK139bc&*',decode_responses=True) if value: r.set(key,value,expire) else: return r.get(key) @server_name.route('/api/v2/payment',methods=['get']) def paymeng_v2(): token = flask.request.values.get('token') amount = flask.request.values.get('amount') if token: result = op_redis(token) if result: amount = float(amount) result = json.loads(result) userid = result.get('id') sql = 'update app_myuser set balance=%s where id = %s;' %(amount,userid) op_mysql(sql) data = {'code': 0, 'msg': '支付成功'} else: data = {'code': 401, 'msg': '未登录'} return json.dumps(data,ensure_ascii=False)
fastapi模块开发接口;
import fastapi import uvicorn server_name = fastapi.FastAPI() #实例化一个服务 @server_name.get('/get') #定义一个get接口 def index(id:int,sex:str): #定义请求参数和数据类型 if sex =='男': data = {'id':id,'sex':'男'} else: data = {'id': id, 'sex': '女'} return data #post接口,入参json类型 from pydantic import BaseModel class User(BaseModel): username:str password:str phone:str @server_name.post('/user') def user(u:User): print(u.username) print(u.password) print(u.phone) data = {'code':0,'username':u.username} return data if __name__ == '__main__': #必须加才能启动服务 uvicorn.run('t1:server_name',port=9000,debug=True) #t1是当前python文件名,server_name是实例名
#### ip:port/docs 可查看生成的接口文档,文档上可以跑接口 ###
接口请求返回示例: