Flask-视图函数

一个视图方法,可以就写一个请求方式,也可以写多个请求方式,也可是单个请求方式,多个请求方式时候,需要判断是GET,还是POST

from flask import Flask, request

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def list_project():
    if request.method == 'GET':
        return 'GET所有的项目'
    elif request.method == 'POST':
        return '创建一个项目'


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

前后端不分离的情况下,使用一个函数两种请求方式的多,前后端分离的时候,一般使用类视图

例如

from flask import request, render_template, Flask

app = Flask(__name__)


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'GET':
        return render_template('index.html')
    if request.method == 'POST':
        return render_template('success.html')


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

基于类的视图,可插拔视图,用在前后端分离的时候

类视图的好处,

类视图可以继承

代码可以复用

可以定义多种行为

不能通过装饰器进行注册,通过集中管理的方式,把类转换成了是一个视图函数

标准类视图

from flask import Flask
from flask.views import View

app = Flask(__name__)


class ProjectView(View):
    def dispatch_request(self):
        return 'project'


app.add_url_rule('/project',view_func=ProjectView.as_view('pj'))

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

基于调度方法的视图MethodView

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class ProjectView(MethodView):
    def get(self):
        return 'get'

    def post(self):
        return 'post'


app.add_url_rule('/project', view_func=ProjectView.as_view('pj1'))


if __name__ == '__main__':
    app.run(debug=True, port=5000)

不同的请求方式写法

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class ProjectView(MethodView):
    def get(self):
        return 'get'

    def post(self):
        return 'post'


app.add_url_rule('/project', view_func=ProjectView.as_view('pj1'))


class UserView(MethodView):
    def get(self, project_id):
        if project_id is None:
            return 'Get all project'
        return f'get {project_id}'

    def post(self):
        return f'post'

    def put(self, project_id):
        return f'put {project_id}'

    def delete(self, project_id):
        return f'delete {project_id}'


app.add_url_rule('/projects/',
                 view_func=UserView.as_view('uv'),
                 methods=['GET', 'POST', 'DELETE', 'PUT'])
app.add_url_rule('/projects/', defaults={'project_id': None},
                 view_func=UserView.as_view('uv'),
                 methods=['GET'])

if __name__ == '__main__':
    app.run(debug=True, port=5000)

总结:

路由设计

project ,projects

 前后端不分离的模版渲染:1、一个视图函数写一个url

url:获取所有的项目,/projects, def list_projects

url::获取单个项目的内容:/projects/,def get _project()

url:修改某个项目的内容:/project_edit/,def edit_project()

Flask 采用前后端不分离

前后端分离:rest method :get,post,delete

/project/ 类的视图:def   get:单个资源

/projects

DRF采用前后端分离

你可能感兴趣的:(Flask,flask,python,后端)