flask+sqlalchemy查改删

Posted 学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

  

  

以上是关于flask+sqlalchemy查改删的主要内容,如果未能解决你的问题,请参考以下文章

C#里配置文件的增查改删

C#里配置文件的增查改删

“增查改删”的语句

Vue+Spring Data JPA+MySQL 增查改删

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

Python Web开发:后端开发中的增查改删处理