flask学习-day1

介绍


django是大而全,flask是轻量级的框架

django提供非常多组件:orm/session/cookie/admin/form/modelform/路由/视图/模板/中间件/分页/auth/contentype/缓存/信号/多数据库连接

flask本身没有太多的功能:路由/试视图/模板/session/中间件,第三方组件齐全

注意:django的请求处理是逐一封装和传递;flask请求是利用上下文管理实现的

快速使用


安装

复制代码
pip install flask

依赖

复制代码
Werkzeug

基于wsgi的服务

python 复制代码
from werkzeug.serving import run_simple

def func(environ,start_response):
    print("请求来了")
    pass

if __name__ =='__main__':
    run_simple('127.0.0.1', 5000, func)

基于flask服务

复制代码
# flask 基于werkzeug的wsgi实现,flask自己没有wgsi
# 用户一旦请求到来,就会调用app.__call__方法
python 复制代码
from flask import Flask

app = Flask(__name__)


@app.route('/index')
def index():
    return "hello word"


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

简单操作


工程目录

主文件s2.py

python 复制代码
from flask import Flask, render_template, jsonify, request, redirect, url_for

app = Flask(__name__)

DATA_DICT = {
    1: {'name': '袁山山', 'age': 13},
    2: {'name': '张涛', 'age': 18}
}


@app.route('/login', methods=['GET', 'POST'])
def login():
    # return '登录'
    if request.method == 'GET':
        return render_template('login.html')
    # return jsonify({'code': 1000, 'data': [1, 2, 3]})
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    print(user, pwd)
    if user == '1' and pwd == '1':
        return redirect('/index')
    error_message = '用户名或密码错误'
    return render_template('login.html', **{'error_message': "用户名或密码错误"})


@app.route('/index', endpoint='idx')
def index():
    data_dict = DATA_DICT
    return render_template('index.html', data_dict=data_dict)


@app.route('/edit', methods=['GET', 'POST'])
def edit():
    nid = int(request.args.get('nid'))
    if request.method == 'GET':
        info = DATA_DICT[nid]
        return render_template('edit.html', info=info)

    username = request.form.get('username')
    age = request.form.get('age')
    DATA_DICT[nid]["username"] = username
    DATA_DICT[nid]["age"] = age
    return render_template('index.html', data_dict=DATA_DICT)


# url_for使用接口别名访问,使用endpoint起别名
@app.route('/delete/<int:nid>')
def delete(nid):
    print(nid)
    del DATA_DICT[nid]
    # return redirect('/index')
    return redirect(url_for('idx'))


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

登录界面

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录界面</title>
</head>
<body>
    <h1>hello ,哈哈哈哈哈哈哈哈哈哈哈</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="password" name="pwd">
        <input type="submit" value="提交">
        {{error_message}}
    </form>
</body>
</html>

主页

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>年龄</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for key,value in data_dict.items() %}
            <tr>
                <td>{{key}}</td>
                <td>{{value.name}}</td>
                <td>{{value.age}}</td>
                <td>
                    <a href="/edit?nid={{key}}">编辑</a>
                    <a href="/delete/{{key}}">删除</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

修改

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改界面</title>
</head>
<body>
    <h1>修改用户信息</h1>
    <form method="post">
        <input type="text" name="username" value="{{info.name}}">
        <input type="number" name="age" value="{{info.age}}">
        <input type="submit" value="提交">
    </form>
</body>
</html>

总结

flask路由
复制代码
@app.route('/login', methods=['GET', 'POST'])
def login():
路由参数:endpoint为页面的别名,不可以重复,可以使用url_for直接引用别名跳转
复制代码
@app.route('/index', methods=['GET', 'POST'], endpoint='idx')
def index():
    pass
复制代码
@app.route('/delete/<int:nid>')
def delete(nid):
    print(nid)
    del DATA_DICT[nid]
    # return redirect('/index')
    return redirect(url_for('idx'))
动态路由(路径传参,get传参)

@app.route('/index')

def index():

pass

路径传参:

@app.route('/index/<name>')

def index():

pass

@app.route('/index/<int:nid>')

def index(nid):

pass

get传参

from flask import requesr

@app.route('/index')

def index():

username= reques.args.get("")获取url中的参数数据

username = request.form.get("")获取表单的数据

返回数据

@app.route('/index')

def login():

return render_template("模板文件")

return jsonify()

return redirect("/index/")

return redirect(url_for('index'))

return str

模板处理

{{x}}

{% for item in list %}

{{item}}

{% endfor %}

相关推荐
ThreeYear_s37 分钟前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
银色的白2 小时前
工作记录:人物对话功能开发与集成
vue.js·学习·前端框架
新中地GIS开发老师4 小时前
三维GIS开发cesium智慧地铁教程(4)城市白模加载与样式控制
学习·arcgis·智慧城市·webgl·gis开发·webgis·地理信息科学
Studying 开龙wu4 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
软件开发技术深度爱好者4 小时前
HTML版英语学习系统
学习·html
卜及中4 小时前
【Redis/1-前置知识】分布式系统概论:架构、数据库与微服务
数据库·redis·架构
nenchoumi31194 小时前
UE5 学习系列(二)用户操作界面及介绍
windows·学习·ue5·机器人
NULL指向我5 小时前
香橙派3B学习笔记9:Linux基础gcc/g++编译__C/C++中动态链接库(.so)的编译与使用
笔记·学习
ThreeYear_s5 小时前
基于FPGA的PID算法学习———实现PID比例控制算法
学习·算法·fpga开发