Flask杂记

Flask杂记

常用库

from flask import Flask
from flask import redirect
from flask import render_template
from flask import jsonify
from flask import request
from flask import session

默认情况下,只接受GET请求,要想允许其他请求可以这样:

from flask import Flask

@app.route("/",methods=['GET','POST'])
def idnex():
    return "HELLO WORLD!"

模板渲染数据

app.py

from flask import Flask
from flask import render_template

@app.route("/",methods=['GET','POST'])
def idnex():
    data1 = {
        '1':{'name':'mark1','age':'18'},
        '2':{'name':'mark2','age':'19'},
    }
    data2 = [
        {'id':123,'name':'mark1','age':'18'},
        {'id':124,'name':'mark2','age':'19'},
    ]
    return render_template("index.html",data1=data1,data2=data2)

idnex.html

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        {% for key, value in data1.items() %}
        <tr>
            <th>{{key}}</th>
            <th>{{value.name}}</th>
            <th>{{value.age}}</th>
        </tr>
        {% endfor %}
    </tbody>
</table>

<hr/>

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        {% for item in data2 %}
        <tr>
            <th>{{item.id}}</th>
            <th>{{item.name}}</th>
            <th>{{item.get{"age","22"}}}</th>
        </tr>
        {% endfor %}
    </tbody>
</table>

其中,{{item.get{"age","22"}}为获取不到age内容,则返回默认值22

URL 传值

from flask import Flask

@app.route("/<int:id",methods=['GET','POST'])
def idnex():
    return id

url_for 用别名跳转

from flask import Flask,url_for

@app.route("/<int:id",methods=['GET','POST'],endpoint="idx")
def idnex():
    return id

@app.route("/test/")
def test():
    rerurn redirect(url_for("idx"))

其中endpoint未填写,默认是函数名,且重名

获取提交的数据

from flask import request
from flask import Flask

@app.route("/<int:id",methods=['GET','POST'])
def idnex():
    id = request.form.get("id")  # POST形式传递的参数
    name = reuest.args("name")  # GET形式传递的参数
    return id

返回数据

from flask import request
from flask import Flask
from flask import render_template
from flask import jsonify
@app.route("/<int:id",methods=['GET','POST'])
def idnex():
    return render_template("")  
    return jsonify()
    return redirect("")
    return ""
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇