Flask Project Vue

Vue与Flask交互

目的

本文主要讲述Vue如何使用AxiosFlask发送请求,以及Flask如何正确接收参数。
如果处理不当的话可能会报415(Unsupported Media Type),422(Unprocessable Entity)等错。

0. 基础工作

Vue

import axios from 'axios';

// 全局 axios 配置
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// other global configuration...

const http = axios.create({
    headers: { 
        'Content-Type': 'application/json;'  // 默认 json
    },
    baseURL: 'http://localhost:5000/api', // 后端(Flask)接口前缀
    timeout: 5000, // 超时时间 5s
});

Flask

class User(db.Model):
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_name = db.Column(db.String(32), nullable=False)
    user_email = db.Column(db.String(256), unique=True, nullable=False)
    user_password = db.Column(db.String(256), nullable=False)

    # other attributes

class UserApi(MethodView):
    @jwt_required()
    def get(self):
        # ...

        return Result.success()

    @jwt_required()
    def post(self):
        # ...

        return Result.success()

    @jwt_required()
    def put(self):
        # ...

        return Result.success()

    @jwt_required()
    def delete(self):
        # ...

        return Result.success()


class AvatarApi(MethodView):
    @jwt_required()
    def post(self):
        # ...

        return Result.success()
def register_routes(app: Flask):
    user_view = UserApi.as_view('user_api')
    app.add_url_rule('/api/user', view_func=user_view, methods=['GET', 'POST', 'PUT', 'DELETE'])

    avatar_view = AvatarApi.as_view('avatar_api')
    app.add_url_rule('/api/avatar', view_func=avatar_view, methods=['POST'])

1. GET

Vue

const params = {
    'user_name': '张',
    'user_email': '@163.com'
}

// 模糊查询'姓张'并且'用163邮箱'的用户
export const _getUsers = (params) => {
    return http.get('/user', {
        params: params
    });
}

Flask

class UserApi(MethodView):
    @jwt_required()
    def get(self):
        args = request.args

        user_name = args.get('user_name')
        user_email = args.get('user_email')

        data = []
        # ...

        return Result.success(data=data)

2. POST (json)

Vue

const params = {
    'user_name': '张三',
    'user_email': 'zhangsan@163.com',
    'user_password': 'zhangsan'
}

// 新用户注册
export const _postUserByJson = (params) => {
    return http.post('/user', params);
}

Flask

class UserApi(MethodView):
    @jwt_required()
    def post(self):
        params = request.json

        user_name = params.get('user_name')
        user_email = params.get('user_email')
        user_password = params.get('user_password')

        # ...

        return Result.success()

3. POST (x-www-form-urlencoded)

Vue

const params = {
    'user_name': '张三',
    'user_email': 'zhangsan@163.com',
    'user_password': 'zhangsan'
}

// 新用户注册
// http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
// 上为实例配置Content-Type 或 下为调用时配置Content-Type
export const _postUserByForm = (params) => {
    return http.post('/user', params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
}

Flask

class UserApi(MethodView):
    @jwt_required()
    def post(self):
        form = request.form

        user_name = form.get('user_name')
        user_email = form.get('user_email')
        user_password = form.get('user_password')

        # ...

        return Result.success()

4. Post(form)

Vue

// 用户上传头像
export const _postAvatar = (avatar: File) => {
    const formData = new FormData()
    formData.append('avatar', avatar)

    return http.post('/avatar', formData)
}

Flask

class AvatarApi(MethodView):
    @jwt_required()
    def post(self):
        form = request.form

        user_avatar = form.get('avatar')

        # ...

        return Result.success()

5. PUT

Vue

const params = {
    'user_id': 1,
    'user_name': '张3',
    'user_email': 'zhangsan@126.com',
}

// 修改用户信息
export const _putUser = (params) => {
    return http.put('/user', params);
}

Flask

class UserApi(MethodView):
    @jwt_required()
    def put(self):
        params = request.json

        user_id = params.get('user_id')
        user_name = params.get('user_name')
        user_email = params.get('user_email')

        # ...

        return Result.success()

6. Delete

Vue

const params = {
    'user_id': 1
}

// 删除用户
export const _deleteUser = (params) => {
    return http.delete('/user', {
        params: params
    });
}

Flask

class UserApi(MethodView):
    @jwt_required()
    def get(self):
        args = request.values

        user_id = params.get('user_id')

        # ...

        return Result.success()

你可能也会喜欢...