preface

Interface debugging is an essential part of front-end development. Common practices include mocking.js, etc. However, mocks have a few disadvantages, such as the request being intercepted and not being able to view the details of the request in Chrome. To address these shortcomings, we can broaden our skill tree and write a portion of the back end for project native mock debugging. This article introduces a quick solution to build a front-end debugging background based on Python Flask framework.

Flask Common methods

Based on the sample

from flask import Flask, request
from flask_cors import *
import json
import time
import copy
import random
import os

app = Flask(__name__)
CORS(app, supports_credentials=True, resources=r'/*')

CORS(app)

@app.route('/')
def index() :
  return 'Hello,Python Flask! '

app.run(debug=True, host='0.0.0.0', port=8000)
Copy the code

Note: When the browser tests access, change the IP address of host from 0.0.0.0 to the actual IP address.

routing

The route is set through app.route and is accessed through IP address: port number + route.

@app.route('/api/name')
def name() :
  return 'Name: Leif'
Copy the code

Request method

GET Request method setting. This method is default and is optional.

@app.route('/api/info', methods=['GET'])
Copy the code

POST request method setting.

@app.route('/api/info', methods=['POST'])
Copy the code

Request parameter read

GET Request parameter read, via request.args.get(‘ parameter name ‘)

@app.route('/api/info', methods=['GET'])
def info() :
  type = request.args.get('type')
  time = request.args.get('time')
Copy the code

POST request parameter read by request.form.get(field name)

@app.route('/api/params', methods=['POST'])
def params() :
  # browser & os & computer & folder
  browser = request.form.get('browser')
  os = request.form.get('os')
  computer = request.form.get('computer')
  folder = request.form.get('folder')
Copy the code

Picture reading and saving

@app.route('/api/pic', methods=['POST'])
def pic() :
  img = request.files.get('file')
  if img is None:
    return json.dumps({'msg': 'File upload fail! '})
  else:
    img.save(img.filename)
    return json.dumps({'msg': 'File upload success! '})
Copy the code

Return error code returned

@app.route('/api/stcode')
def statusCode() :
  return json.dumps({'retcode': 0}), 411
Copy the code

Json file reading

with open('./table.json'.'r+') as f:
  data = json.loads(f.read())

@app.route('/api/json')
def getJson() :
  return json.dumps(data)
Copy the code

Demo

portal