flask框架+上传文件接口实战【多测师_王sir】

HTML文件源码:
<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> body{ background: antiquewhite; } * { padding: 0; margin: 0; } form { width: 500px; border: 1px solid rgba(0,0,0,0.7); box-shadow: inset 0 0 15px rgba(0,0,0,0.3); border-radius: 10px; margin: 100px auto; background: #99bfe1; } form>div { margin: 15px 0; padding: 0 50px; } input[type='text']{ width: 300px; height: 30px; } input[type='radio'] { margin: 0 10px; } input[type='submit'],input[type='button']{ width: 100px; height: 30px; border: 1px solid rgba(0,0,0,0.5); color: white; background: rgba(0,0,0,0.7); border-radius: 5px; } form>div:last-child{ text-align: right; } </style> </head> <body> <!--在文件上传时form表单的数据传输方式必须为post,并且编码格式必须为 multipart/form-data,否则服务器端是无法获取传输的文件数据--> <form action="/duoceshi/upload" method="post" enctype="multipart/form-data"> <div> 头像:<input type="file" name="pic"> </div> <div> 昵称: <input type="text" name="dcs_name"> </div> <div> 性别: <input type="radio" name="sex" value="男" checked><input type="radio" name="sex" value="女"></div> <div> 年龄: <input type="text" name="age"> </div> <div> <input type="submit" value="提交"> </div> </form> </body> </html>
#coding=utf-8
"""
===========================
Author:多测师_王sir
Time:2020-07-22 22:39
Wechat:xiaoshubass
website:www.duoceshi.cn
===========================
"""

import os
from flask import Flask, request, render_template, jsonify
from werkzeug.utils import secure_filename
from flask import send_from_directory
import datetime

app = Flask(__name__)

# 文件上传的路径
UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'images')

@app.route('/duoceshi/upload', methods=['GET', 'POST'])
def settings():
    if request.method == 'GET':
        # 创建视图函数,将该模板内容进行渲染返回
        return render_template("upload_page.html")
    else:
        # 获取请求的参数
        name = request.form.get('dcs_name')
        sex = request.form.get("sex")
        age = request.form.get("age")
        # 获取上传的图片
        pic = request.files.get('pic')
        if all([name, sex, age, pic]):
            # 保存文件
            filename = secure_filename(pic.filename)
            pic.save(os.path.join(UPLOAD_PATH, filename))
            msg = "文件上传成功,文件保存的地址为:http://127.0.0.1:5000/images/{}".format(filename)
            data = {
                "code": 1,
                "data": {
                    "name": name,
                    "sex": sex,
                    "age": age,
                    "filename": filename,
                    "datetime": datetime.datetime.now()
                },
                "msg": msg
            }
        else:
            # 返回内容:
            data = {
                "code": 1,
                "data": None,
                "msg": "参数不能为空!"
            }

        return jsonify(data)

# 访问上传的文件
# 浏览器访问:http://127.0.0.1:5000/images/xxx.png 查看文件
@app.route('/images/<filename>', methods=['GET', 'POST'])
def get_image(filename):
    return send_from_directory(UPLOAD_PATH, filename)


if __name__ == '__main__':
    app.run(debug=True)
#coding=utf-8
"""
===========================
Author:多测师_王sir
Time:2020-07-28 20:36
Wechat:xiaoshubass
website:www.duoceshi.cn
===========================
"""

'''
1.请求的url地址:http://127.0.0.1:5000/duoceshi/upload
2.post请求参数传递的几种方式:
data:一般用来传递表单类型的参数、默认的请求头是Content-Type:application/x-www-form-urlencoded
json:用来传递json类型的参数、默认的请求头是Content-Type:application/json
files:用来上传文件的参数、默认的请求头是Content-Type:multipart/form-data
3.参数名:(文件名、文件流、文件类型image/png)
'''

#组建接口的要素:url地址、接口的入参、请求头、接口的请求方法

import requests   #做接口测试的库

#1.定义url地址
url = 'http://127.0.0.1:5000/duoceshi/upload'

#2.定义接口的入参
data = {
    'dcs_name':'多测师_王sir',
    'sex':'',
    'age':18
}

#3.接口的入参为文件  参数名:(文件名、文件流、文件类型image/png)
file = {
    'pic':('duoceshi_api.png',open(r'C:\Users\wangzhiqiang\Desktop\desktop\duoceshi_api.png','rb'),'image/png')
}

#4.发送接口的请求
response = requests.post(url=url,data=data,files=file)
# print(response.text)
# print(type(response.text))
print(response.json())   #通过json函数把接口的返回数据转换为字典
print(type(response.json()))

 

运行环境和流程:
1、前提安装好python
2、安装flask
   cmd 执行命令 pip install flask
3、运行http_service.py这个文件

4、就可以通过http://127.0.0.1:5000/duoceshi/upload访问这个接口
   注意点:get请求返回的是上传文件的页面,post请求是上传文件
5、通过打开upload_page.html进行测试
6、通过postman或者编写测试代码进行测试
7、通过Python+Requests库编写测试代码进行测试

 

posted @ 2020-07-29 18:18  多测师_树哥  阅读(1596)  评论(0编辑  收藏  举报