【pytho】request五种种请求处理为空和非空处理以及上传excel,上传图片处理

一、python中请求处理

request.args获取的是个字典,所以可以通过get方式获取请求参数和值

request.form获取的也是个字典,所以也可以通过get方式获取请求的form参数和值

request.data,使用过JavaScript,api调用方式进行掺入json字符串,由于传入的是字符串,所有需要通过json.loads(request.data)进行加载成字典

request.json,获取的是个字典,所以特可以通过get方式获取

request.headers也是字典

request.cookies也是字典

from flask import Flask, request, Response
from werkzeug.utils import secure_filename
import os
import json
import xlrd

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/test_1.0', methods=['GET'])
def check():
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
    # 判断入参为空
    # if len(request.args) == 0:
    if not len(request.args):
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
    # 获取传入的params参数
    get_data = request.args.to_dict()
    name = get_data.get('name')
    age = get_data.get('age')
    return_dict['result'] = tt(name, age)

    return json.dumps(return_dict, ensure_ascii=False)


@app.route('/test_1.1', methods=['POST'])
def check1():
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
    # 判断入参为空
    if not request.get_data():
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
    # 获取传入的参数
    get_data = request.get_data()
    get_data = json.loads(get_data)
    name = get_data.get('name')
    age = get_data.get('age')
    return_dict['result'] = tt(name, age)

    return json.dumps(return_dict, ensure_ascii=False)


@app.route('/test_1.2', methods=['POST'])
def check2():
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
    # 判断入参为空
    if not request.form:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
    # 获取传入的参数
    get_data = request.form
    name = get_data.get('name')
    age = get_data.get('age')
    return_dict['result'] = tt(name, age)

    return json.dumps(return_dict, ensure_ascii=False)


@app.route('/test_1.3', methods=['POST'])
def check3():
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
    # 判断入参为空
    if not request.get_json():
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
    # 获取传入的参数
    get_data = request.json
    name = get_data.get('name')
    age = get_data.get('age')
    return_dict['result'] = tt(name, age)

    return json.dumps(return_dict, ensure_ascii=False)


def tt(name, age):
    result_str = "%s今年%s岁" % (name, age)
    return result_str


# 上传表格
@app.route("/excel_info", methods=["GET", "POST"])
def excel_info():
    if request.method == "POST":
        # 获取参数用request.form, 获取文件用request.files
        file = request.files.get('file')
        if not file:
            return {"code": '401', "message": "缺少参数"}
        # 读取表格内容
        workbook = xlrd.open_workbook(file_contents=file.read())
        # 获取第一个sheet
        sheet = workbook.sheet_by_index(0)
        # 获取总行数
        row = sheet.nrows
        # 从表格中选取字段
        titles = ['name', 'age', 'address']
        json_list = []
        # 遍历每一行内容
        for i in range(row):
            if i == 0:
                continue
            row_value = sheet.row_values(i)
            # 构造字典
            obj = dict()
            json_list.append(obj)
            for title, col_val in zip(titles, row_value):
                obj.setdefault(title, col_val)
        return {"code": '200', "message": json_list}
    else:
        return {"code": '403', "message": "仅支持post方法"}


# 设置图片保存文件夹
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__), 'static', 'images')

# app.config['UPLOAD_FOLDER'] = './static/images'

# 设置允许上传的文件格式
ALLOW_EXTENSIONS = ['png', 'jpg', 'jpeg']


# 判断文件的后缀是否在列表中
def allow_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[-1] in ALLOW_EXTENSIONS


# 上传图片
@app.route("/upload_image", methods=['GET', 'POST'])
def uploads():
    if request.method == 'POST':
        # 获取post过来的文件名称,从name=file参数中获取
        file = request.files.get('file')
        # 检查文件格式
        if file and allow_file(file.filename):
            # secure_filename方法会去掉中文名中的中文
            file_name = secure_filename(file.filename)
            # 保存图片
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
            return {"code": "200", "data": "", "message": "上传成功"}

        else:
            return "格式错误,仅支持jpg,png,jpeg格式文件"
    return {"code": '503', "data": "", "message": "仅支持post方法"}


# 查看图片
@app.route('/images/')
def get_frame(imageId):
    with open(r'./static/images/{}'.format(imageId), 'rb') as f:
        image = f.read()
        result = Response(image, mimetype="image/jpg")
        return result


if __name__ == '__main__':
    app.run()

请求示意图:

【pytho】request五种种请求处理为空和非空处理以及上传excel,上传图片处理_第1张图片

三,参考:

(33条消息) python——flask常见接口开发(简单案例)_flask接口开发例子_大蛇王的博客-CSDN博客

你可能感兴趣的:(Python,python,开发语言)