flask+sqlalchemy查改删

效果:

main.py

1# coding: utf-8
from sqlalchemy import CheckConstraint, Column, Integer, Text, or_
from sqlalchemy.schema import FetchedValue
from flask_sqlalchemy import SQLAlchemy
from flask import Flask,url_for,redirect,render_template,request,flash,current_app
import os,sys

app =  Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘sqlite:///test.db‘
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = True

db = SQLAlchemy(app)

class Teacher(db.Model):
    __tablename__ = ‘Teachers‘
    Id = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.Text)
    Age = db.Column(db.Integer)
    Country = db.Column(db.Text)

    def __init__(self,Name,Age,Country):
        self.Name = Name
        self.Age = Age
        self.Country = Country
@app.route(‘/‘, methods=[‘GET‘])
def home():
    article = Teacher.query.all()
    return render_template(‘show_article.html‘,article=article)
@app.route(‘/search‘)
def search():
    keyword = request.args.get(‘keyword‘)
    print(keyword)
    result = Teacher.query.filter(or_(Teacher.Name==keyword,Teacher.Age==keyword,Teacher.Country==keyword)).all()
    if result:
        return render_template(‘show_article.html‘, article=result)
    else:
        return ‘No content was found!‘
@app.route(‘/list/update/<id>‘,methods=[‘GET‘,‘POST‘])
def modi(id):
    if request.method==‘GET‘:
        result = Teacher.query.filter_by(Id=id).first_or_404()
        return render_template(‘update_article.html‘,article=result)
    else:
        Name = request.form[‘Name‘]
        Age = request.form[‘Age‘]
        Country = request.form[‘Country‘]
        result =  Teacher.query.filter_by(Id=id).update({‘Name‘:Name, ‘Age‘:Age,‘Country‘:Country})
        db.session.commit()
        return redirect(‘/‘)
@app.route(‘/<id>‘,methods=[‘GET‘,‘DELETE‘])
def remove_record(id):
    if request.method==‘GET‘:
        result = Teacher.query.filter_by(Id=id).first.or_404
        return render_template(‘show_article.html‘, article=result)
    else:
        result = Teacher.query.filter_by(Id=id).delete()
        db.session.commit()
        return  ‘‘,204
@app.route(‘/favicon.ico‘)
def favicon():
    return send_from_directory(os.path.join(app.root_path, ‘static‘),
                               ‘favicon.ico‘, mimetype=‘image/vnd.microsoft.icon‘)
if __name__ ==‘__main__‘:
    app.run(port=8081)

show_article.html

<!DOCTYPE HTML>
<html>
<head>
<link href="//www.w3cschool.cn/statics/plugins/bootstrapold/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<link rel="shortcut icon" href="{{ url_for(‘static‘, filename=‘favicon.ico‘) }}">
</head>
<body>
<!-- Jinja模板语法 -->
<div>
    <form method="GET" action="{{ url_for(‘search‘) }}" />
        <input type="text" Name="keyword" />
        <input type="submit" />
        <span><a href="{{ url_for(‘home‘) }}">Home</a></span>
    </form>

</div>
<table style="width:240px" class="table table-striped" >
    <thead>
        <tr >
            <th style="width:120px">Name</th>
            <th style="width:60px">Age</th>
            <th style"width:60px">Country</th>
        </tr>
    </thead>
    <tbody>
        {% if article %}
            {% for article in article%}
            <tr>
                <td>{{article.Name}}</td>
                <td>{{article.Age}}</td>
                <td>{{article.Country}}</td>
                <td><span class="label label-info"><a href="/list/update/{{article.Id}}" style="color:white">修改</a></span></td>
                <td><span class="label label-success"><a href="#" class="btn-delete" aid="{{article.Id}}" style="color:white">删除</a></span></td>
            </tr>
            {% endfor %}
    </tbody>
        {% else %}
            <p>No content was found!</p>
        {% endif %}

<script type="text/javascript">
    $(‘a.btn-delete‘).on(‘click‘,function(evt){
        evt.preventDefault();
        var aid = $(this).attr(‘aid‘);
        $.ajax({
            url: "/" + aid,
            type: "DELETE",
            contentType:"application/json",
            success:function(resp){
                window.open("/","_self");
            },
            error:function(resp){
                alert("删除博文失败!详情:" + resp.message);
            }
        })
    });
</script>
</table>
</body>
</html>

  

update_article.html

<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="{{ url_for(‘static‘, filename=‘favicon.ico‘) }}">
</head>
<body>
    <div>
        <form action="/list/update/{{article.Id}}" method="POST">

                <label>Name:<label>
                <input type="text" name="Name" value="{{article.Name}}" />
                <br><br>
                <label>Age:</label>
                <input type="text" name="Age" value="{{article.Age}}" />
                <br><br>
                <label>Country:</label>
                <input type="text" name="Country" value="{{article.Country}}" />
                <br><br>
                <input type=submit />
        </table>
        <tbody>
        </form>
    </div>
<body>
</html>

  

  

原文地址:https://www.cnblogs.com/luoye00/p/12176074.html

时间: 2024-10-13 07:27:45

flask+sqlalchemy查改删的相关文章

EF里单个实体的增查改删以及主从表关联数据的各种增删 改查

本文目录 EF对单个实体的增查改删 增加单个实体 查询单个实体 修改单个实体 删除单个实体 EF里主从表关联数据的各种增删改查 增加(增加从表数据.增加主从表数据) 查询(根据主表找从表数据.根据从表找主表数据) 修改(修改从表的外键) 删除(删除主从表关系.删除主表数据.删除主从表数据.修改从表数据外键) 补充内容 SaveChanges方法提交多次操作 DbSet.Add方法返回当前实体 源码和系列文章导航 注:本章节多次演示了各种删除,要重复查看效果,需要解开注释初始化数据方法. 一.EF

ThinkPHP 增 查 改 删

1 返回主页 2 SYsunyi 3 4 博客园 5 首页 6 新随笔 7 联系 8 订阅 9 管理 10 11 随笔 - 0 文章 - 0 评论 - 0 12 ThinkPHP--栏目增删改查ADSF 13 复制代码 14 15 <?php 16 /** 17 * 栏目发布 18 */ 19 //V层,action/name值 20 action = " :U( ' Admin/Cat/Cateadd ' )"; 21 22 /** 23 * 添加栏目数据 24 * C层,写相

Django 学习笔记(七)数据库基本操作(增查改删)

一.前期准备工作,创建数据库以及数据表,详情点击<Django 学习笔记(六)MySQL配置> 1.创建一个项目 2.创建一个应用 3.更改settings.py 4.更改models.py 5.同步数据 二.安装IPython方便debug sudo apt-get install ipython3 安装成功后用python manage.py shell 会自动进入Ipython交互解释器中,没有安装Ipython只有前两行代码,只进入到Python shell 中. Python 3.5

ThinkTP 增 查 改 删

<?php //ThinkTP框架增加以Admin/contooler/catcontroller.class.php**和Admin/view/cat/cateadd.html为例. // 在cateadd.hmtl的from action 中写传输语句 {:U('Admin/cat/cateadd')} //Admin/conroller/catcaotroller.class.php控制器 namespace Admin/controller; use Think/cintroller;

存储过程_查-改-删

一.存储过程的查询 1.通过数据字典表查询 存储过程的定义信息保存在数据字典表information_schema.routines中: mysql> select ROUTINE_NAME, ROUTINE_TYPE -> from information_schema.ROUTINES -> where ROUTINE_SCHEMA='db1'; +----------------+--------------+ | routine_name | routine_type | +--

“增查改删”的语句

select * from UserInfor --查找所有字段 select username,UserId from UserInfor -- 查找username,UserId两个字段 select top 2* from UserInfor where (Major='计算机' or Major='土木工程') and Sex=0 order by Age desc --降序 select top 2* from UserInfor where major in('计算机','土木工程'

数据库的增查改删(二)

desc aa;select * from bb;/*给aa表格增加sgender列,在指定位置*/alter table bb add ss int first;alter table bb add sge char(3) after sage;/*给aa表格删除sgender列*/alter table aa drop sgender;alter table bb drop column sge;/*修改列的名字*/alter table aa change sage age;/*修改列的数

c++中的顺序表写法,主要实现(增删查改,构造函数,运算符重载)

本文的内容主要是,利用c++写出顺序表,并对写出的代码进行测试, 主要实现的功能:实现对顺序表的增删查改, 要写的函数:构造函数,赋值运算符重载,析构函数.在编写代码过程中应注意到深浅拷贝问题. 下面是顺序表的类函数: #pragma once #include<iostream> using namespace std; typedef int DataType; class SeqList { public: SeqList(); SeqList(DataType *array, size

Dom的增删查改以及常用事件

dom的增删查改 // 查 var _input = document.getElementById('_input'); var _div = document.getElementsByClassName('_div'); var _div2 = document.getElementsByTagName('div'); var _radio = document.getElementById('_radio'); // 改 input.value = '随便'; div.style.hei