栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

flask web 01--基础入门案例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

flask web 01--基础入门案例

flask web 01--基础入门案例
  • 1 介绍
  • 2 功能说明
  • 3 源码分析
    • 3.1 功能
    • 3.2 源码
    • 3.3 测试结果
  • 4 注意事项
  • 5 说明

1 介绍

最近由于需要,开始补了一些python web相关的技能,考虑到高效和简洁,就补了一些flask web开发的基础知识。此处为一个简单的案例,主要结合Flask 和 html,实现了一些基础的数据查询和添加。为了减少代码量,此处就模拟了一些数据,并未使用实际的db的增删查改。
即便案例很简单,也分享在此处,以便于自己和有需要的读者查阅!

2 功能说明

本案例主要包括输出hello信息、加载单条数据、按表加载数据、添加数据等4个小功能。其对应的代码结构如下所示:

├── app.py
└── templates
    ├── add_item.html  添加数据
    ├── get_item.html  加载数据
    ├── hello.html     显示传入的参数
    └── list_item.html 列举数据
3 源码分析 3.1 功能

main() 充当菜单功能;
hello(name=None) 输出hello world 或者 hello ${name};
get_item(name=None) 获取 name=${name} 的数据,此处直接模拟一条数据,实际中需要在db中查数据;
list_item() 获取数据并输出表格中,此处模拟了两条数据,实际汇总需要在db中查找;
add_item() 添加条数据,实际中拿到post的数据后还需要将其insert到db中;

3.2 源码

vim app.py

#!/usr/bin/python3 

import datetime
import json

from flask import Flask
from flask import render_template
from flask import request, redirect

app = Flask(__name__)


@app.route('/')
def main():
    ret = {
        "function": "hello, main page!",
        "/add_item/": "add an alert",
        "/list_item/": "list all alerts",
        "/get_item/[item_name]": "get an alert",
        "/hello/[name]": "say hello",
    }
    return json.dumps(ret)


@app.route('/hello/')
@app.route('/hello/')
def hello(name=None):
    return render_template('hello.html', name=name)


@app.route('/get_item/')
@app.route('/get_item/')
def get_item(name=None):
    # function: get an item from db
    post_data = {
        "deploy_name": "test014",
        "search_condition": "search_condition",
        "search_time_from": "now-5m",
        "search_step": "60",
        "resend_period": "30m",
        "threshold": "5"
    }
    date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    post_data['date_time'] = date_time
    return render_template("get_item.html", post=post_data)


@app.route('/list_item/')
def list_item():
    date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # function: get all items from db
    post_data = [
        {
            "deploy_name": "test014",
            "search_condition": "test014 search_condition",
            "search_time_from": "now-5m",
            "search_step": "60",
            "resend_period": "30m",
            "threshold": "5"
        },
        {
            "deploy_name": "elk-001",
            "search_condition": "[{"wildcard":{"hostname.keyword":{"value":"elk-001-*"}}},"
                                "{"term":{"level.keyword":{"value":"ERROR"}}},{"range":{"timestamp":"
                                "{"gte":"now-1m","lte":"now"}}}]",
            "search_time_from": "now-5m",
            "search_step": "60",
            "resend_period": "30m",
            "threshold": "5"
        }
    ]

    return render_template("list_item.html", posts={'data': post_data, 'date_time': date_time})


@app.route('/add_item/', methods=['GET', 'POST'])
def add_item():
    if request.method == "GET":
        # function: get an item from db
        post_data = {
            "deploy_name": "test014",
            "search_condition": "search_condition",
            "search_time_from": "now-5m",
            "search_step": "60",
            "resend_period": "30m",
            "threshold": "5"
        }
        date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        post_data['date_time'] = date_time
        return render_template("add_item.html", post=post_data)

    if request.method == "POST":
        post_data = {
            "deploy_name": request.form['deploy_name'],
            "search_condition": request.form["search_condition"],
            "search_time_from": request.form["search_time_from"],
            "search_step": request.form["search_step"],
            "resend_period": request.form["resend_period"],
            "threshold": request.form["threshold"]
        }
        # function: save data to db
        return json.dumps(post_data)


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

vim add_item.html




    
    Hello, add_item



新增日志告警
当前时间: {{ post['date_time'] }}
告警参数 内容
deploy_name
search_condition
search_time_from
search_step
resend_period
threshold

vim get_item.html




    
    Hello, get_item



查看日志告警
当前时间: {{ post['date_time'] }}
告警参数 内容
deploy_name {{ post['deploy_name'] }}
search_condition {{ post['search_condition'] }}
search_time_from {{ post['search_time_from'] }}
search_step {{ post['search_step'] }}
resend_period {{ post['resend_period'] }}
threshold {{ post['threshold'] }}

vim list_item.html




    
    Hello, list_item



日志告警接入统计表
当前时间: {{ posts['date_time'] }}
{% for post in posts['data'] %} {% endfor %}
deploy_name search_time_from search_step resend_period threshold search_condition
{{ post['deploy_name'] }} {{ post['search_time_from'] }} {{ post['search_step'] }} {{ post['resend_period'] }} {{ post['threshold'] }} {{ post['search_condition'] }}

vim hello.html




    
    Hello Flask


{% if name %}

Hello, {{ name }}!

{% else %}

Hello, World!

{% endif %}
3.3 测试结果

主页:

列表:

查看:

添加:

添加后返回信息

4 注意事项
  1. 前端提交数据的时候,使用html的form表单+action+method属性可以实现多种数据交互。
5 说明

测试软件环境:
python 3.8
flask 2.0.1
参考文档:
flask.palletsprojects.com/en/2.0.x/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/316131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号