python Flask篇(一)


 

MarkdownPad Document

python Flask教程

例子1:

import flask
from flask import *
app=Flask(__name__) #創建新的開始

@app.route('/') #路由設置
def imdex(): #如果訪問了/則調用下面的局部變量
   return 'Post qingqiu !' #輸出


if __name__ == '__main__':
    app.run() #運行開始

訪問:127.0.0.1:5000/
結果:

請求方式

例子2:

import flask
from flask import *
app=Flask(__name__)
#flask.request為請求方式
@app.route('/',methods=['GET',"POST"]) #mthods定義了請求的方式
def imdex():
    if request.method=='POST': #判斷請求
        return 'Post qingqiu !'
    else:
        return 'Get qinqiu !'

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

GET請求返回的結果如下:

POST請求如下:

模板渲染

在同一目錄下創建一個templates的文件夾,然后里面放入你要調用
的html。使用render_template('要調用的html')
例子3:

import flask
from flask import *
app=Flask(__name__)

@app.route('/',methods=['GET',"POST"])
def imdex():
    if request.method=='POST':
        return 'Post qingqiu !'
    else:
        return render_template('index.html') #調用html

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

index.html代碼:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小灰灰的網絡博客</title>
</head>
<body>
<h1>Hello Word</h1>
</body>
</html>

結果:

動態摸版渲染

個人來認為吧,這個應該比較少用到,畢竟是這樣子的:/路徑/參數
例子:

import flask
from flask import *
app=Flask(__name__)

@app.route('/index')
@app.route('/index/<name>') #html里面的參數為name這里也為name動態摸版調用
def index(name): #html里面的參數為name這里也為name
    return render_template('index.html',name=name) #調用

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

html代碼:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小灰灰的網絡博客</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
</body>
</html>

結果:

接受請求參數

例子:
request.form.請求方式('表單里的數據名稱') #用於接受表單傳來的數據

import flask
from flask import *
app=Flask(__name__)

@app.route('/index/<name>')
def index(name):
    return render_template('index.html',name=name)

@app.route('/login',methods=['GET','POST']) #可使用的請求有GET和POST
def login():
    error=None
    if request.method=="GET": #如果請求為GET打開login.html
        return  render_template('login.html') 
    else:
        username=request.form.get('username') #獲取表單里的username數據
        password=request.form.get('password') #獲取表單里的password數據
        if username=='admin' and password=='admin': #判斷表單里的username和password數據是否等於admin
            return 'login ok' #如果是則返回登錄成功

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

html代碼:
這里的{{ url_for('login') }} #代表着發送數據

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="{{url_for('login')}}" method="POST">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="login">
</form>
</body>
</html>

結果如下

輸入admin admin
返回如下

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM