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

相关推荐
Elastic 中国社区官方博客5 小时前
在 Elasticsearch 中使用 Mistral Chat completions 进行上下文工程
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
容器( ु⁎ᴗ_ᴗ⁎)ु.。oO6 小时前
Magentic-ui 学习
学习
_李小白6 小时前
【OPENGL ES 3.0 学习笔记】延伸阅读:VAO与VBO
笔记·学习·elasticsearch
编程爱好者熊浪6 小时前
两次连接池泄露的BUG
java·数据库
南宫乘风7 小时前
基于 Flask + APScheduler + MySQL 的自动报表系统设计
python·mysql·flask
微露清风7 小时前
系统性学习C++-第九讲-list类
c++·学习·list
海边夕阳20068 小时前
【每天一个AI小知识】:什么是零样本学习?
人工智能·经验分享·学习
TDengine (老段)8 小时前
TDengine 字符串函数 CHAR 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
qq7422349848 小时前
Python操作数据库之pyodbc
开发语言·数据库·python
姚远Oracle ACE8 小时前
Oracle 如何计算 AWR 报告中的 Sessions 数量
数据库·oracle