来自网易云课堂的知了课堂
1.)增删改查
config.py
# -*- coding:utf8 -*-
import os
basedir = os.path.abspath(os.path.dirname(__file__))
#print(basedir) #E:\Web\tonghuashun\stock\app
class Config:
# mysql_conf = dict(
# host = '127.0.0.1',
# database = 'tonghuashun',
# user = 'root',
# password = '297002372as',
# port = 3306,
# charset = "utf8")
# mysqlurl = "mysql://root:297002372as@127.0.0.1/tonghuashun?charset=utf8"
@staticmethod
def init_app(app):
pass
SECRET_KEY = os.environ.get("SECRET_KEY") or 'you guess and guess'
class DevelopmentConfig(Config):
DEBUG= True
MAIL_SERVER = "297002372@qq.com"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:297002372as@127.0.0.1:3306/tonghuashun?charset=utf8"
SQLALCHEMY_TRACK_MODIFICATIONS= False
config = {
"defalut":DevelopmentConfig
}
#固定名 SQLALCHEMY_DATABASE_URI
run.py
from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from config import config
app = Flask(__name__)
app.config.from_object(config["defalut"])
db = SQLAlchemy(app)
#
# 创建article表
# create table article(
# id int primary ke autoincrement,
# title varchar(100) not null,
# content text not null,
# )
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False) #varchar和char都是对应db.String
contenet = db.Column(db.Text,nullable=False)
#
# db.create_all() #创建模型,创建表。
@app.route("/index")
def hell():
#增
#1.新建一个实例。
#2.使用add
#3.提交
# article_1 = Article(title="aaa",contenet="bbb")
# db.session.add(article_1)
# #做了一层事务操作,所以要提交。
# db.session.commit()
#查
#result = Article.query.filter(Article.title=="aaa").first()
#Article.query.filter(Article.title=="aaa")的返回是一个Query对象,
# 如果取第一个数据,就使用result.first()
#print(result) #[<Article 1>]返回一个Article的数据的数组。
#print(result.title)
#print(result.contenet)
"""
[<Article 1>]
aaa
bbb
"""
#改
#1.先把你要更改的数据查找出来。
#2.吧这条数据,需要修改的地方进行修改
#3.事务提交
# article_1 = Article.query.filter(Article.title=="aaa").first()
# article_1.title = 'new title'
# db.session.commit()
#删
#1.先把删除的数据查找出来
#2.吧这条数据删除掉
#3.做事务提交
#article_1 = Article.query.filter(Article.title == "new title").first()
#db.session.delete(article_1)
#db.session.commit()
return render_template("index.html")
@app.route("/lg")
def login():
return render_template("login.html")
@app.route("/base")
def test():
return render_template("base.html")
if __name__=="__main__":
app.run(debug=True)
2.外键约束:
不合理的:
from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from config import config
app = Flask(__name__)
app.config.from_object(config["defalut"])
db = SQLAlchemy(app)
# 用户表
# create table users(id int primary key autoincrement,
# username varchar(100) not null
# )
#
# 文章表:
# create table article (
# id int primary key autoincrement,
# title varchar(100) not null,
# content text not null,
# author_id int,
# foreign key `author_id` references `users.id`
# )
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
contenet = db.Column(db.Text,nullable=False)
author_id = db.Column(db.Integer,db.ForeignKey("users.id")) #需要这一条
#db.create_all()
@app.route("/index")
def hell():
# user_1 = User(username="zk")
# db.session.add(user_1)
# db.session.commit()
# article_1 = Article(title='aaa',contenet='bbb',author_id=1)
# db.session.add(article_1)
# db.session.commit()
article = Article.query.filter(Article.title =="aaa").first()
authid = article.author_id
user = User.query.filter(User.id ==authid).first()#需要修改的地方
print(user.username)
return render_template("index.html")
@app.route("/lg")
def login():
return render_template("login.html")
@app.route("/base")
def test():
return render_template("base.html")
if __name__=="__main__":
app.run(debug=True)
另外一种:
from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from config import config
app = Flask(__name__)
app.config.from_object(config["defalut"])
db = SQLAlchemy(app)
# 用户表
# create table users(id int primary key autoincrement,
# username varchar(100) not null
# )
#
# 文章表:
# create table article (
# id int primary key autoincrement,
# title varchar(100) not null,
# content text not null,
# author_id int,
# foreign key `author_id` references `users.id`
# )
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
contenet = db.Column(db.Text,nullable=False)
author_id = db.Column(db.Integer,db.ForeignKey("users.id"))
author = db.relationship('User',backref=db.backref("article")) #backref反向引用
#db.create_all()
@app.route("/index")
def hell():
article = Article.query.filter(Article.title == "aaa").first()
username = article.author.username
print(username)
return render_template("index.html")
@app.route("/lg")
def login():
return render_template("login.html")
@app.route("/base")
def test():
return render_template("base.html")
if __name__=="__main__":
app.run(debug=True)
3。查找数据
from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from config import config
app = Flask(__name__)
app.config.from_object(config["defalut"])
db = SQLAlchemy(app)
# 用户表
# create table users(id int primary key autoincrement,
# username varchar(100) not null
# )
#
# 文章表:
# create table article (
# id int primary key autoincrement,
# title varchar(100) not null,
# content text not null,
# author_id int,
# foreign key `author_id` references `users.id`
# )
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(100),nullable=False)
contenet = db.Column(db.Text,nullable=False)
author_id = db.Column(db.Integer,db.ForeignKey("users.id"))
author = db.relationship('User',backref=db.backref("article")) #backref反向引用
#db.create_all()
@app.route("/index")
def hell():
# article = Article(title="111",contenet="2222",author_id=1)
# db.session.add(article)
# db.session.commit()
# username = article.author.username
user = User.query.filter(User.username=='zk').first()
result = user.article
print(result)
for x in result:
print(x.title)
return render_template("index.html")
@app.route("/lg")
def login():
return render_template("login.html")
@app.route("/base")
def test():
return render_template("base.html")
if __name__=="__main__":
app.run(debug=True)