本案例中直接使用sqlalchemy,没有使用flask-sqlalchemy来做的
1.引入包文件
from flask
import Flask, render_template,url_for,redirect
import flask
from sqlalchemy
import create_engine, Column, String, Integer, Text, DateTime, ForeignKey
from sqlalchemy.ext.declarative
import declarative_base
from sqlalchemy.orm
import sessionmaker, relationship
import datetime
app = Flask(__name__)
app.debug =
True
DB_URI =
"mysql+mysqldb://root:root@127.0.0.1:3306/python?charset=utf8"
engine = create_engine(DB_URI)
Base = declarative_base(engine)
session = sessionmaker(engine)()
2.创建一个用户表的映射
class Author(Base):
__tablename__ =
"author"
authorid = Column(Integer, primary_key=
True, autoincrement=
True)
authorname = Column(String(
100), nullable=
False)
def __repr__(self):
return "<Author authorid='%s' authorname='%s'>"%(self.authorid,self.authorname)
3.创建文章表的映射
class Article(Base):
__tablename__ =
"article"
articleid = Column(Integer, primary_key=
True, autoincrement=
True)
articletitle = Column(String(
100), nullable=
False)
articlecontent = Column(Text)
createTime = Column(DateTime, default=datetime.datetime.now())
author_id = Column(Integer, ForeignKey(
"author.authorid"))
author = relationship(
"Author", backref=
"articles")
def __repr__(self):
return "<Article author_id='%s' author='%s'>"%(self.author_id,self.author)
4.创建数据库
# 创建数据表
Base
.metadata.create_all()
5.路由页面展示
@app.route('/')
def index():
data = session.query(Article).all()
dataset = {
"data":data
}
return render_template(
"index.html",**dataset)
@app.route("/addarticle/", methods=["GET", "POST"])
def addarticle():
if flask.request.method ==
"GET":
return render_template(
"addarticle.html")
else:
authorname = flask.request.form.get(
'authorname')
title = flask.request.form.get(
'title')
content = flask.request.form.get(
'content')
author = session.query(Author).filter(Author.authorname == authorname).first()
if not author:
author = Author(authorname=authorname)
article = Article(articletitle=title, articlecontent=content)
article.author = author
session.add(article)
session.commit()
return redirect(url_for(
"index"))
@app.route("/authorlist/<int:authorid>")
def authorlist(authorid):
user = session.query(Author).get(authorid)
articles = user.articles
dataSet = {
"data":articles
}
return render_template(
"author.html",**dataSet)
if __name__ ==
'__main__':
app.run()
6.完整的demo
from flask
import Flask, render_template,url_for,redirect
import flask
from sqlalchemy
import create_engine, Column, String, Integer, Text, DateTime, ForeignKey
from sqlalchemy.ext.declarative
import declarative_base
from sqlalchemy.orm
import sessionmaker, relationship
import datetime
app = Flask(__name__)
app.debug =
True
DB_URI =
"mysql+mysqldb://root:root@127.0.0.1:3306/python?charset=utf8"
engine = create_engine(DB_URI)
Base = declarative_base(engine)
session = sessionmaker(engine)()
class Author(Base):
__tablename__ =
"author"
authorid = Column(Integer, primary_key=
True, autoincrement=
True)
authorname = Column(String(
100), nullable=
False)
def __repr__(self):
return "<Author authorid='%s' authorname='%s'>"%(self.authorid,self.authorname)
class Article(Base):
__tablename__ =
"article"
articleid = Column(Integer, primary_key=
True, autoincrement=
True)
articletitle = Column(String(
100), nullable=
False)
articlecontent = Column(Text)
createTime = Column(DateTime, default=datetime.datetime.now())
author_id = Column(Integer, ForeignKey(
"author.authorid"))
author = relationship(
"Author", backref=
"articles")
def __repr__(self):
return "<Article author_id='%s' author='%s'>"%(self.author_id,self.author)
Base.metadata.create_all()
@app.route('/')
def index():
data = session.query(Article).all()
dataset = {
"data":data
}
return render_template(
"index.html",**dataset)
@app.route("/addarticle/", methods=["GET", "POST"])
def addarticle():
if flask.request.method ==
"GET":
return render_template(
"addarticle.html")
else:
authorname = flask.request.form.get(
'authorname')
title = flask.request.form.get(
'title')
content = flask.request.form.get(
'content')
author = session.query(Author).filter(Author.authorname == authorname).first()
if not author:
author = Author(authorname=authorname)
article = Article(articletitle=title, articlecontent=content)
article.author = author
session.add(article)
session.commit()
return redirect(url_for(
"index"))
@app.route("/authorlist/<int:authorid>")
def authorlist(authorid):
user = session.query(Author).get(authorid)
articles = user.articles
dataSet = {
"data":articles
}
return render_template(
"author.html",**dataSet)
if __name__ ==
'__main__':
app.run()
7.补充html页面内容
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
<link href="http://cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div style="margin: 30px 0;overflow: hidden">
<a class="btn btn-primary" href="{{ url_for('addarticle') }}" style="float: right">新增文章</a>
</div>
<table class="table table-hover">
<thead>
<tr>
<th class="text-center" style="border-bottom: 1px solid #eceeef">NO.</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">标题</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">内容</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">作者</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">时间</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td class="text-center">{{ item.articleid }}</td>
<td>{{ item.articletitle }}</td>
<td>{{ item.articlecontent }}</td>
<td><a href="{{ url_for('authorlist',authorid=item.author_id) }}">{{ item.author.authorname }}</a></td>
<td class="text-center">{{ item.createTime }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
templates/addarticle.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title
</title>
<link href="http://cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="col-md-6">
<form action="" method="post" role="form" class="form-horizontal">
<div class="form-group">
<label>作者:
</label>
<input type="text" placeholder="请输入作者名" name="authorname" class="form-control"/>
</div>
<div class="form-group">
<label>标题:
</label>
<input type="text" placeholder="请输入标题" name="title" class="form-control"/>
</div>
<div class="form-group">
<label>内容:
</label>
<textarea class="form-control" cols="5" rows="5" style="resize: none" placeholder="请输入文章内容" name="content"></textarea>
</div>
<div class="form-group">
<input type="submit" value="新增" class="btn btn-success">
</div>
</form>
</div>
</div>
</body>
</html>
templates/author.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>作者全部书籍</title>
<link href="http://cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h3 class="text-danger text-center">作者:({{ data[0].author.authorname }})所有文章列表</h3>
<div style="margin:0 0 30px 0;overflow: hidden">
<a class="btn btn-primary" href="{{ url_for('index') }}" style="float: right">返回主页</a>
</div>
<table class="table table-hover">
<thead>
<tr>
<th class="text-center" style="border-bottom: 1px solid #eceeef">NO.</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">标题</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">内容</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">作者</th>
<th class="text-center" style="border-bottom: 1px solid #eceeef">时间</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td class="text-center">{{ item.articleid }}</td>
<td>{{ item.articletitle }}</td>
<td>{{ item.articlecontent }}</td>
<td>{{ item.author.authorname }}</td>
<td class="text-center">{{ item.createTime }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>