欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flask web開發(fā)處理POST請(qǐng)求實(shí)現(xiàn)(登錄案例)

 更新時(shí)間:2018年07月26日 10:00:31   作者:51kata  
這篇文章主要介紹了Flask web開發(fā)處理POST請(qǐng)求實(shí)現(xiàn)(登錄案例),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

本文我們以一個(gè)登錄例子來說明Flask對(duì) post請(qǐng)求的處理機(jī)制。

1、創(chuàng)建應(yīng)用目錄,如

mkdir example
cd example

2、在應(yīng)用目錄下創(chuàng)建  run.py文件,內(nèi)容如下

from flask import Flask
from flask import render_template, redirect,url_for
from flask import request

app = Flask(__name__)

@app.route('/login', methods=['POST','GET'])
def login():
  error = None
  if request.method == 'POST':
    if request.form['username']=='admin':
      return redirect(url_for('home',username=request.form['username']))
    else:
      error = 'Invalid username/password'
  return render_template('login.html', error=error)

@app.route('/home')
def home():
  return render_template('home.html', username=request.args.get('username'))

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

上面的代碼解釋如下:

1)上面的代碼用到了幾個(gè)flask的方法

render_template : 將請(qǐng)求定位到模板文件上,處理模板文件后,將結(jié)果作為請(qǐng)求的響應(yīng)返回

redirect:將請(qǐng)求的響應(yīng)重定向到新的url上。上面的例子是,當(dāng)?shù)卿洺晒螅囟ㄏ虻?home頁(yè)面。

url_for:根據(jù)參數(shù)生成url

2)request對(duì)象的使用

request對(duì)象包含了所有的請(qǐng)求信息,通過它可獲取所需要的請(qǐng)求信息。

3)app.route增加了methods參數(shù),指明該url支持的http請(qǐng)求方式,默認(rèn)是get方式。上面例子 /login即作為get,也作為post的請(qǐng)求目標(biāo)。

3、在應(yīng)用目錄下創(chuàng)建 templates目錄,在templates目錄下創(chuàng)建 login.html 和 home.html,內(nèi)容分別如下:

1)login.html文件

<!DOCTYPE html>
<html lang="zh-CN">
 <head>
  <meta charset="utf-8">
  <title>login</title>
 </head>
 <body>
  <form style="margin:20px;border:1px solid red" method="post" action="/login">
    <span>username:</span><input type="text" name="username" id="username"><br/>
    <span>password:</span><input type="password" name="password" id="password"><br/>
    <button type="submit" id="loginBtn">login</button>
  </form>
  {% if error %}
    <h1 style="color:red">{{ error }}!</h1>
  {% endif %}
 </body>
</html>

2)home.html

<!DOCTYPE html>
<html lang="zh-CN">
 <head>
  <meta charset="utf-8">
  <title>home</title>
 </head>
 <body>
  <h1>wlcome {{username}} , this is home</h1>
 </body>
</html>

4、啟動(dòng)服務(wù)

在應(yīng)用目錄下運(yùn)行  python  run.py

5、測(cè)試訪問

http://192.168.142.138/login

注意:登錄成功后,會(huì)進(jìn)入 http://192.168.142.138/home?username=admin 頁(yè)面

這個(gè)url顯示不好??梢酝ㄟ^session的方式來不需要將username傳入,而是在home.html中通過session獲取。

這個(gè)在后面的文章中介紹。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論