Flask中传递参数详解

1.get请求 
request.args.get("key") 获取get请求参数

2.post请求

request.form.get("key", type=str, default=None) 获取表单数据

request.values.get("key") 获取所有参数

# 参数解析对象生成
parser = reqparse.RequestParser()

args = parser.parse_args()

@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == "POST":
        # 以POST方式传参数,通过form取值
        # 如果Key之不存在,报错KeyError,返回400的页面
        username = request.form['username']
        password = request.form['password']
        print username,password
    else:
        # 以GET方式传参数,通过args取值
        username = request.args['username']
        print username
    return render_template('login.html', req_method=request.method)

传递参数:

传递参数的语法是:`/<参数名>/`。然后在视图函数中,也要定义同名的参数。例如:

@app.route('/article/<string:test>/')

# 传递的参数名是test,因此就需要在函数的形参中定义同名的参数test

def test_article(test):

    return 'test_article:{}'.format(test)

参数的数据类型:

1. 如果没有指定具体的数据类型,那么默认就是使用`string`数据类型。

2. `int`数据类型只能传递`int`类型。 限制参数:<int:article_id>,如果在浏览器中访问:http://127.0.0.1:5000/p/11111.0/ 那就找不到报not found错误,因为我限制了是整形,你现在是浮点型,同理,如果你是浮点型,我使用 整形访问,那就又访问不到了

3. `float`数据类型只能传递`float`类型。

4. `path`数据类型和`string`有点类似,都是可以接收任意的字符串, 但是`path`可以接收路径,也就是说可以包含斜杠。

5. `uuid`数据类型只能接收符合`uuid`的字符串。`uuid`是一个全宇宙都唯一的字符串, 一般可以用来作为表的主键。

关于path数据类型,在主文件中定义如下的代码:

@app.route('/article/<path:test>/') path数据类型

def test_article(test):

     return 'test_article:{}'.format(test)

 

# 通过问号的形式传递参数,例如百度:http://127.0.0.1:5000/d/?wd=%E7%AE%80%E4%B9%A6&pn=20

@app.route('/d/')

def d():

    wd = request.args.get("wd")

    page_number = request.args.get("pn")

    return "通过字符串查询的关键字为:{}, 页码为:{}".format(wd, page_number)

接收用户传递的参数:

1. 第一种:使用path的形式(将参数嵌入到路径中),就是上面讲的。

2. 第二种:使用查询字符串的方式,就是通过`?key=value`的形式传递的。

@app.route('/d/')

def d():

     wd = request.args.get('wd')

     return '您通过查询字符串的方式传递的参数是:%s' % wd ```

3. 如果你的这个页面的想要做`SEO`优化,就是被搜索引擎搜索到,那么推荐使用第一种形式(path的形式)。 如果不在乎搜索引擎优化,那么就可以使用第二种(查询字符串的形式)。

 文件上传

from werkzeug.utils import secure_filename
@app.route('/uploads', methods=['GET', 'POST'])
def uploads():
    if request.method == "POST":
        fe = request.files['files']
        # basepath = os.path.dirname(os.path.abspath(__file__))
        basepath = os.path.abspath(os.path.dirname(__file__))
        upload_path = os.path.join(basepath, 'static', 'upload')
        # f.filename可以拿到文件名,但是是客户端定义的名,不要相信这个名称,用secure_filename包装一下
        fe.save(upload_path+'/'+secure_filename(fe.filename))
        # 这里的url_for 和jinja的前端用法不一样,可以忽略.的引用
        # url_for重定向
        return redirect(url_for('uploads'))
    return render_template('upload.html')

 cookie设置

@app.route('/index')
def index():
    response = make_response(render_template('index.html',title='Index'))
    reqparse.set_cookie('username', '')
    return response

自定义错误页面

from flask import abort
@app.errorhandler(404)
def page_not_not_found(error):
    return render_template('404.html'), 404

 

  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值