flask web 01--基础入门案例

该博客介绍了如何利用Python的Flask框架创建一个基础的Web应用,展示包括输出信息、加载数据、添加数据等功能。通过模拟数据而非实际数据库操作,实现了页面的交互。案例包含hello、get_item、list_item和add_item四个功能,涉及HTML模板的使用,以及GET和POST请求的处理。
摘要由CSDN通过智能技术生成

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/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)


@app.route('/get_item/')
@app.route('/get_item/<name>')
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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, add_item</title>
</head>
<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
    <tr>
        <td align="center" class="biaoti" height="60">新增日志告警</td>
    </tr>
    <tr>
        <td align="right" height="25">当前时间: {{ post['date_time'] }}</td>
    </tr>
</table>

<form method="post">
<table  width="100%" border="0" cellspacing="1" cellpadding="4" bgcolor="#f5f5dc" align="center">
    <tr>
        <td align="left" width="15%">告警参数</td>
        <td align="left">内容</td>
    </tr>
    <tr>
        <td align="left" height="25">deploy_name </td>
        <td align="left" height="25"> <input type="text" name="deploy_name" value="{{ post['deploy_name'] }}">  </td>
    </tr>
    <tr>
        <td align="left" height="25">search_condition </td>
        <td align="left" height="25"> <input type="text" name="search_condition" value="{{ post['search_condition'] }}"> </td>
    </tr>
    <tr>
        <td align="left" height="25">search_time_from </td>
        <td align="left" height="25"><input type="text" name="search_time_from" value="{{ post['search_time_from'] }}"> </td>
    </tr>
    <tr>
        <td align="left" height="25">search_step </td>
        <td align="left" height="25"><input type="text" name="search_step" value="{{ post['search_step'] }}"> </td>
    </tr>
    <tr>
        <td align="left" height="25">resend_period </td>
        <td align="left" height="25"><input type="text" name="resend_period" value="{{ post['resend_period'] }}"> </td>
    </tr>
    <tr>
        <td align="left" height="25">threshold </td>
        <td align="left" height="25"><input type="text" name="threshold" value="{{ post['threshold'] }}"> </td>
    </tr>
</table>
<table  width="100%" border="0" cellspacing="1" cellpadding="4" align="center">
    <tr>
        <td align="left" width="15%"><input name="add" type="submit" value="添加"></td>
    </tr>
</table>
</form>

<form method="get">
    <table  width="100%" border="0" cellspacing="1" cellpadding="4" align="center">
        <tr>
            <td align="left"><input name="refresh" type="submit" value="刷新"></td>
        </tr>
    </table>
</form>
</body>
</html>

vim get_item.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, get_item</title>
</head>
<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
    <tr>
        <td align="center" class="biaoti" height="60">查看日志告警</td>
    </tr>
    <tr>
        <td align="right" height="25">当前时间: {{ post['date_time'] }}</td>
    </tr>
</table>

<table  width="100%" border="0" cellspacing="1" cellpadding="4" bgcolor="#f5f5dc" align="center">
    <tr>
        <td align="left" width="15%">告警参数</td>
        <td align="left">内容</td>
    </tr>
    <tr>
        <td align="left" height="25">deploy_name </td>
        <td align="left" height="25"> {{ post['deploy_name'] }} </td>
    </tr>
    <tr>
        <td align="left" height="25">search_condition </td>
        <td align="left" height="25">{{ post['search_condition'] }} </td>
    </tr>
    <tr>
        <td align="left" height="25">search_time_from </td>
        <td align="left" height="25">{{ post['search_time_from'] }} </td>
    </tr>
    <tr>
        <td align="left" height="25">search_step </td>
        <td align="left" height="25">{{ post['search_step'] }} </td>
    </tr>
    <tr>
        <td align="left" height="25">resend_period </td>
        <td align="left" height="25">{{ post['resend_period'] }} </td>
    </tr>
    <tr>
        <td align="left" height="25">threshold </td>
        <td align="left" height="25">{{ post['threshold'] }} </td>
    </tr>
</table>

</body>
</html>

vim list_item.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, list_item</title>
</head>
<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
    <tr>
        <td align="center" class="biaoti" height="60">日志告警接入统计表</td>
    </tr>
    <tr>
        <td align="right" height="25">当前时间: {{ posts['date_time'] }}</td>
    </tr>
</table>

<table  width="100%" border="0" cellspacing="1" cellpadding="4" bgcolor="#f5f5dc" align="center">
  <tr>
      <td>deploy_name</td>
      <td>search_time_from</td>
      <td>search_step</td>
      <td>resend_period</td>
      <td>threshold</td>
      <td>search_condition</td>
  </tr>
    {% for post in posts['data'] %}
     <tr>
      <td width="15%">{{ post['deploy_name'] }}</td>
      <td width="10%">{{ post['search_time_from'] }}</td>
      <td width="10%">{{ post['search_step'] }}</td>
      <td width="10%">{{ post['resend_period'] }}</td>
      <td width="10%">{{ post['threshold'] }}</td>
      <td width="45%">{{ post['search_condition'] }}</td>
     </tr>
    {% endfor %}
</table>

</body>
</html>

vim hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Flask</title>
</head>
<body>
<div align="center">
    {% if name %}
    <h1>Hello, {{ name }}!</h1>
    {% else %}
    <h1>Hello, World!</h1>
    {% endif %}
</div>
</body>
</html>

3.3 测试结果

主页:
在这里插入图片描述
列表:
在这里插入图片描述
查看:
在这里插入图片描述
添加:
在这里插入图片描述
添加后返回信息
在这里插入图片描述

4 注意事项

  1. 前端提交数据的时候,使用html的form表单+action+method属性可以实现多种数据交互。

5 说明

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昕光xg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值