Flask之Flask-sqlalchemy模块的导入方式

from flask import Flask,render_template,request,redirect
#SQLALchemy
from flask_sqlalchemy import SQLAlchemy
import os ,datetime

app = Flask(__name__)
1、数据库路径
basedir = os.path.abspath(os.path.dirname(__file__))
#print(__file__) #D:/flask/blog/models.py
#print(os.path.dirname(__file__))  #D:/flask/blog
#print(basedir)  #D:\flask\blog

2、实例化数据库连接

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' +os.path.join(basedir,'blog.sqlite')
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

3.每次请求结束后,都会提交数据库变动

app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

4.创建SQLAlchemy
db = SQLAlchemy(app)

5.文章类
class Article(db.Model):
	__tablename__ = 'article'
	id = db.Column(db.Integer,primary_key = True)
	title = db.Column(db.String(32))
	picture = db.Column(db.String(32))
	time = db.Column(db.DATETIME) #时间
	description = db.Column(db.TEXT) #描述
6.同步数据库
db.create_all()

@app.route('/')
def index():
	return render_template('index.html')

@app.route('/article_list/')
def article_list():
	article_list = Article.query.all()
	print(article_list) #[
,
] print(locals()) #{'article_list': [
,
]} return render_template('newslistpic.html',**locals()) #关键字传参 @app.route('/add_article/',methods = ['GET','POST']) def add_article(): if request.method == 'POST': #1.获取表单提交过来的数据 form_data = request.form #获取文本数据 file_data = request.files #获取图片数据 title = form_data.get('title') description = form_data.get('description') picture = file_data.get('picture') time = datetime.datetime.now() #2.保存到数据库 article = Article( title = title, description = description, time = time, picture = '/static/img/' +picture.filename #图片名称例如 1.png ) #3.保存上传图片 picture.save('static/img/' + picture.filename) session = db.session session.add(article) return redirect('/article_list/') return render_template('add_article.html') if __name__ == ''__main__‘’: app.run()

你可能感兴趣的:(FLASK)