flask中几种请求参数的获取,以及cookie和session的操作

from flask import request, jsonify, make_response, session, abort
from flask.blueprints import Blueprint

from app import app
from converters import MobileConverter

admin_bp = Blueprint(name='admin',import_name=__name__)
# 设置session时需要使用secret_key
app.secret_key='abc'

# 使用手机号的路由转换器
app.url_map.converters['mobiles']=MobileConverter
# url路径参数
@admin_bp.route('/admin/<mobiles:mobile>')
def admin_login(mobile):
    return 'phone is {}'.format(mobile)

# 查询字符串  request.args
@admin_bp.route('/admin/queryparam')
def query_param():
    query = request.args
    name = query.get('name')
    id = query['id']
    return {'id':id,'name':name}

# 表单参数 request.form
# 设置cookie
@admin_bp.route('/login',methods=['post'])
def login():
    data = request.form
    name = data.get('name','lisi')
    id = data.get('id',None)
    data = {'success':True}
    response = make_response(data)
    response.set_cookie('name',name)
    response.set_cookie('id',id)
    # response.json({'success':True})
    return response

# json格式的参数 request.json
# 响应返回列表需要使用jsonify
@admin_bp.route('/json',methods=['post'])
def json():
    print(request.json)
    data = request.json
    name = data.get('name',None)
    id = data.get('id',None)
    result = [{'name':name,'id':id,'success':True},{'message':'niubi'}]
    return jsonify(result)

# 删除cookie
@admin_bp.route('/logout',methods=['get'])
def logout():
    name = request.cookies.get('name')
    id = request.cookies.get('id')
    data = {'name':name,'id':id,'message':'退出成功'}
    response = make_response(data)
    response.delete_cookie('name')
    response.delete_cookie('id')
    return response

#获取session中的信息,也可以使用 .get()
@admin_bp.route('/index/login',methods=['post'])
def index_login():
    name = request.form.get('name')
    id = request.form.get('id')
    session['name']=name
    session['id']=id
    return jsonify({'name':name,'success':True})

# 删除session
# abort抛出异常
@admin_bp.route('/index/logout')
def index_logout():
    name = session.get('name')
    id = session.get('id')
    try:
        session.clear()
    except Exception as e:
        print(e)
        abort(404)
    if name is None:
        abort(404)
    return jsonify({'name':name,'success':True})

# 编辑抛出404异常时的动作
@app.errorhandler(404)
def not_fond_page(e):
    return 'sorry, not fond page'
posted @ 2021-07-21 19:28  kopok  阅读(352)  评论(0编辑  收藏  举报