创建蓝图目录
- 在 info 目录下创建 modules Package,创建完成如下:
- 在 modules 文件夹下创建 index 文件夹, 并在此文件夹下创建 views.py 文件,将 manage.py 中定义的路由拷贝至该文件中。
@app.route('/index')
def index():
return 'index'
暂时忽略报错,此处的index文件夹就是一个模块,此处这样设置是参照后续 Django 项目目录结构设置,views 存放当前模块所有的视图函数
- 到这一步 manage.py 中内容基本上都抽取完成,剩余内容如下:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db
app = create_app('development')
# 添加扩展命令行
manager = Manager(app)
# 数据库迁移
Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
- 在 index 文件夹中的 init.py创建其自已的蓝图
from flask import Blueprint
index_blu = Blueprint("index", __name__)
from . import views
- 在 views.py 中导入蓝图,并使用该蓝图注册路由
from . import index_blu
@index_blu.route('/index')
def index():
return 'index'
- 将上一步创建出来的蓝图注册到 app 中
def create_app(config_name):
...
# 注册蓝图
from info.modules.index import index_blu
app.register_blueprint(index_blu)
return app
数据库表分析及创建
数据库表迁移
- 确认当前配置的数据库是否存在
mysql> use information;
注:constants.py 是当前项目中要使用的一些常量,预先定义好的,models.py 文件中需要使用到该文件中的一些常量
- 并在 manage.py 中导入 models
form info import models
在迁移的时候以便能读取到对应模型
- 执行数据库迁移
$ python manage.py db init
$ python manage.py db migrate -m"initial"
$ python manage.py db upgrade
- 查看数据库表是否创建完成
mysql> show tables;
- 执行导入初始分类的 SQL 语句
mysql> source info_info_category.sql
注意:生成的迁移文件不需要提交到 git 保存,所以需要在 .gitignore 文件中添加以下内容以便忽略迁移所生成的系列文件:
migrations
测试数据的添加
- 先添加分类测试数据
mysql> source 路径/information_info_category.sql
- 再添加新闻测试数据
mysql> source 路径/information_info_news.sql
静态文件导入
- 在项目 info 目录下创建 static 文件夹
- 将前端人员开发好的 news 和 admin 两个静态文件夹拖入到项目
news 文件夹内代表新闻前台页面
admin 文件夹内代表新闻的后台页面
- 运行项目,使用浏览器访问:http://127.0.0.1:5000/static/news/index.html 查看效果
注册根路由
创建模板目录
- 在 static 同级目录创建 templates 文件夹,并在此目录下创建 news 文件夹用于存放新闻前台模板文件
- 设置 templates 目录成模板目录属性
- 此步可以省略,只是在 Pycharm 中标识该目录为模板目录
- 操作方式:右键点击 templates 目录,选择 Mark Directory as -> Template Folder
- 如果没有设置模板语言,会弹出是否设置模板语言,点击 Yes,跳转到模板语言设置界面,设置模板语言为 Jinja2
添加模板并创建根路由视图函数
- 使用 Pycharm 将 static/news/index.html 文件移动到 templates/news/ 目录下,并在 index.py 中添加根路由访问视图
from . import index_blu
from flask import render_template
@index_blu.route('/')
def index():
return render_template('news/index.html')
运行,访问根路由测试
网站图标展示
- 自定义视图函数,访问网站图标,send_static_file 是系统访问静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
return current_app.send_static_file('news/favicon.ico')
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/77007.html