1. Flask概述
python的一个框架,目录结构随意
https://www.cnblogs.com/HarryChis/p/11123462.html
pip安装
2.编写
https://www.cnblogs.com/hongdanni/p/11922575.html
3.项目实战
3.1目录
/flask
/static
/templates
show_entries.html
login.html
layout.html
flask.py
schema.sql
3.2步骤
1、 创建文件夹(以上目录)
2、 创建数据库表
3、 创建flask.py
4、 数据库设置
def connect_db():
“”“Connects to the specific database.”""
rv = sqlite3.connect(app.config[‘DATABASE’])
rv.row_factory = sqlite3.Row //用sqlite3.Row来表示数据库中的行
return rv
//sqlite3 轻量级数据库 ,Python库内置的(不需要安装任何服务器端/客户端软件,也不需要运行某个服务,只要你在Python中导入库并开始编程),
5、 连接数据库
def get_db():
“”“Opens a new database connection if there is none yet for the
current application context.
“””
if not hasattr(g, ‘sqlite_db’):
g.sqlite_db = connect_db()
return g.sqlite_db
//首次调用的时候会为当前环境创建一个数据库连接,调用成功后返回已经建 立好的连接
关闭数据库
@app.teardown_appcontext
def close_db(error):
“”“Closes the database again at the end of the request.”""
if hasattr(g, ‘sqlite_db’):
g.sqlite_db.close()
6、 创建数据库
我们可以创建一个名为 init_db 的函数来初始化数据库。 只需要把这个函数放在 flaskr.py 里的 connect_db 函数的后面:
def init_db():
with app.app_context(): //建立应用环境
db = get_db() //打开应用提供的资源
with app.open_resource(‘schema.sql’, mode=‘r’) as f: //open用于执行脚本
db.cursor().executescript(f.read())
db.commit()
7、 显示函数
@app.route(’/’) // 路由
def show_entries():
cur = g.db.execute(‘select title, text from entries order by id desc’)// 执行sql语句
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()] // 把位于最上方的记录作为字典返回给show_entries.html
return render_template(‘show_entries.html’, entries=entries)
8、 添加函数
@app.route(’/add’, methods=[‘POST’])
def add_entry(): //定义一个函数
if not session.get(‘logged_in’): //用户登入检查
abort(401) // 生成SIGABRT信号 os.abort
g.db.execute(‘insert into entries (title, text) values (?, ?)’,
[request.form[‘title’], request.form[‘text’]])
g.db.commit()
flash(‘New entry was successfully posted’)
return redirect(url_for(‘show_entries’))
9、 页面设计(HTML文件)
使用Jinja2 作为模板引擎
4 遇到的问题及解决办法
1 ‘list’ object has no attribute ‘words’
list列表对象没有words这个属性
senwords = Senword.query.filter_by(dept_id=current_user.dept_id).all()
_out_senword = ''
for senword in senwords:
_out_senword = _out_senword + senword.words + '、'
return render_template('manage/hl_editInfo.html', temp=tempObj, this_data=this_data, senwords=_out_senword)
转为字符串
2 local variable ‘tempObj’ referenced before assignment
局部变量’tempObj’在赋值前被引用
同样的方法写了两遍