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 %}

相关推荐
码农郁郁久居人下12 分钟前
Redis的配置与优化
数据库·redis·缓存
架构文摘JGWZ15 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
小齿轮lsl19 分钟前
PFC理论基础与Matlab仿真模型学习笔记(1)--PFC电路概述
笔记·学习·matlab
Aic山鱼1 小时前
【如何高效学习数据结构:构建编程的坚实基石】
数据结构·学习·算法
qq11561487071 小时前
Java学习第八天
学习
天玑y1 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
MuseLss1 小时前
Mycat搭建分库分表
数据库·mycat
2301_789985941 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习
橄榄熊1 小时前
Windows电脑A远程连接电脑B
学习·kind
Hsu_kk2 小时前
Redis 主从复制配置教程
数据库·redis·缓存