Flask交流

十七、get和post请求

2018-10-08  本文已影响11人  十柒年

1.get请求

1.1概念

1.2使用

先来看一段代码。这是html。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<a href="{{ url_for('search',q='hello') }}">跳转到搜索页面</a>
</body>
</html>

这是python

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search/')
def search():
    q = request.args.get('q')
    return '用户提交的参数是%s' % q

在这里由首页跳转到搜索页面,并且在路径及传递一个参数q,value值为hello。请求的完整路径如下。

http://127.0.0.1:5000/search/?q=hello

页面展示效果如下。


get请求

2.post请求

2.1概念

2.2使用

先看login.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="{{ url_for('login') }}" method="post">
    <table>
        <tbody>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" placeholder="请输入用户名"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="text" name="password" placeholder="请输入密码"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="登录"></td>
        </tr>
        </tbody>
    </table>
</form>
</body>
</html>

效果图如下。


登录页面

app.py代码如下。

# 默认的视图函数 只能采用get请求
# 如果想要使用post请求 则必须指明是post
@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method== 'GET':
        return render_template('login.html')
    else:
       username = request.form.get('username')
       password = request.form.get('password')
       print(username)
       print(password)
       return 'post request'

注意:

input标签中,要写name来标识这个value的key,方便后台获取
在写form表单的时候,要指定method=‘post’并且要指定action="{{ url_for('login') }}"

study hard and make progress every day.

更多学习资料请关注"爱游戏爱编程"。


爱游戏爱编程.jpg
上一篇 下一篇

猜你喜欢

热点阅读