说明

  • 操作系统:Windows 10
  • Python 版本:3.7x
  • 虚拟环境管理器:virtualenv
  • 代码编辑器:VS Code

实验目标

完善环境配置,添加 异常请求 处理

实现

400、404 和 500 处理

首先,在 todolist\app\templates\errors 目录下创建一个 400.html 文件,示例代码如下所示:

{% extends 'base.html' %} {% block content %}
<div class="text-center animated fadeInDown">
<h1>400</h1>
<h3> 错误请求!! !</h3>
<div>
<a href="{{ url_for('index') }}">返回首页</a>
</div>
</div> {% endblock %}

todolist\app\templates\errors 目录下创建一个 404.html 文件,示例代码如下所示:

{% extends 'base.html' %} {% block content %}
<div class="text-center animated fadeInDown">
<h1>404</h1>
<h3> 页面未能够找到!! !</h3>
<div>
抱歉,页面好像去火星啦!
</div>
</div> {% endblock %}

todolist\app\templates\errors 目录下创建一个 500.html 文件,示例代码如下所示:

{% extends 'base.html' %} {% block content %}
<div class="text-center animated fadeInDown">
<h1>500</h1>
<h3> 内部异常!! !</h3>
<div>
<a href="{{ url_for('index') }}">返回首页</a>
</div>
</div> {% endblock %}

接着,在 todolist\app 目录下创建 errors.py 文件,,注册 400、 404 、500 路由处理函数,示例代码如下所示:

from flask import render_template
from app import app @app.errorhandler(400)
def bad_request(e):
return render_template('errors/400.html'), 400 @app.errorhandler(404)
def page_not_found(e):
return render_template('errors/404.html'), 404 @app.errorhandler(500)
def internal_server_error(e):
return render_template('errors/500.html'), 500

添加 CLI

todolist\app 目录下创建 commands.py 文件,示例代码如下所示:

import click
from app import app, db
from app.models import User, Thing @app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
if drop:
db.drop_all()
db.create_all()
print("Initialized database.") @app.cli.command()
@click.option('--username', prompt=True, help='The username used to login.')
@click.option('--email', prompt=True, help='The email used to Identity.')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password used to login.')
def admin(username, email, password):
db.create_all()
user = User.query.first()
if user:
print("Updating user...")
user.name = username
user.email = email
user.generate_password_hash(password)
else:
print("Creating user...")
user = User(name="hippieZhou")
user.email = email
user.generate_password_hash(password)
db.session.add(user)
db.session.commit()
print('Done.')

此时,可以将 VS Code 的终端却换至该项目根目录下,可执行上面我们自定义的相关目录,如下图所示:

使用前需要先进入到 app 中,具体可参考 下面的 todolist\app\__init__.py 代码。

完善 Config 配置

首先,修改 todolist\config.py 文件,示例代码如下所示:

import os

basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = "you will never known it." class DevelpmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get(
'DEV_DATABASE_URL') or 'sqlite:///' + os.path.join(basedir, 'todo.sqlite') class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = os.environ.get(
'SQLALCHEMY_DATABASE_URI') or 'mysql+pymysql://root:mysql@127.0.0.1:3306/todo' config = {
'development': DevelpmentConfig,
'production': ProductionConfig
}

接着,修改 todolist\app\__init__.py 文件,示例代码如下所示:

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config app = Flask(__name__)
app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app) login_manager.login_view = 'login'
login_manager.login_message = '你必须登陆后才能访问该页面'
login_manager.login_message_category = "info" @login_manager.user_loader
def load_user(user_id):
from app.models import User
user = User.query.get(int(user_id))
return user @app.context_processor
def inject_user():
from app.models import User
user = User.query.first()
return dict(user=user) from app import views, errors,commands

最后,修改 todolist\manage.py 文件,示例代码如下所示:

from app import app

if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)

自此,我们的项目结构和代码已经进一步完善了,完整项目结构如下图所示:

最后,我们可以在 Shell 窗口中执行 flask run 命令即可将我们的网站运行起来。

Flask 系列之 优化项目结构的更多相关文章

  1. vue 快速入门 系列 —— Vue(自身) 项目结构

    其他章节请看: vue 快速入门 系列 Vue(自身) 项目结构 前面我们已经陆续研究了 vue 的核心原理:数据侦测.模板和虚拟 DOM,都是偏底层的.本篇将和大家一起来看一下 vue 自身这个项目 ...

  2. ABP架构学习系列一 整体项目结构及目录

    本系列是基于aspnetboilerplate-0.8.4.0版本写的,其中原因是由于较高的版本太抽象难以理解和分析,对于还菜菜的我要花更多的时间去学习. abp的源码分析学习主要来源于 HK Zha ...

  3. flask开发restful api系列(7)-蓝图与项目结构

    如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restful api的最明显效果就是版本控制:而 ...

  4. 【Flask】 项目结构说明

    项目结构 Flask的一大优势就是其极其轻量化.但是也需要注意到,如果我们要用Flask做一个大项目的话,把所有代码写在一个文件里肯定是不合适的.非常难以维护.但是和Django这种框架又不一样,Fl ...

  5. React Native 系列(三) -- 项目结构介绍

    前言 本系列是基于React Native版本号0.44.3写的,相信大家看了本系列前面两篇文章之后,对于React Native的代码应该能看懂一点点了吧.本篇文章将带着大家来认识一下React N ...

  6. flask实战-个人博客-虚拟环境、项目结构

    个人博客 博客是典型的CMS(Content Management system,内容管理系统),通常由两部分组成:一部分是博客前台,用来展示开放给所有用户的博客内容:另一部分是博客后台,这部分内容仅 ...

  7. 一个比较良好的flask项目结构

    一个比较良好的flask项目结构 project/ app/                    # 整个程序的包目录 static/                 # 静态资源文件 js/    ...

  8. 架构系列:ASP.NET 项目结构搭建

    我们头开始,从简单的单项目解决方案,逐步添加业务逻辑的约束,从应用逻辑和领域逻辑两方面考虑,从简单的单个项目逐步搭建一个多项目的解决方案.主要内容:(1)搭建应用逻辑和领域逻辑都简单的单项目 (2)为 ...

  9. Vue.js系列之项目结构说明

    转:https://www.jb51.net/article/111658.htm 前言 在上一篇项目搭建文章中,我们已经下载安装了node环境以及vue-cli,并且已经成功构建了一个vue-cli ...

随机推荐

  1. swust oj 1052

    输出利用先序遍历创建的二叉树中的指定结点的双亲结点 1000(ms) 10000(kb) 2415 / 5575 利用先序递归遍历算法创建二叉树并输出该二叉树中指定结点的双亲结点.约定二叉树结点数据为 ...

  2. 在线生成透明ICO图标神器

    此神器的链接为:http://ico.duduxuexi.com/ 大家可以将这个网址收藏好,本人亲测十分好用!对我们的ios,安卓以及windows开发都有极大的好处.

  3. [Swift]LeetCode174. 地下城游戏 | Dungeon Game

    The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. ...

  4. [Swift]LeetCode296. 最佳开会地点 $ Best Meeting Point

    A group of two or more people wants to meet and minimize the total travel distance. You are given a ...

  5. [Swift]LeetCode661. 图片平滑器 | Image Smoother

    Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother t ...

  6. [Swift]LeetCode695. 岛屿的最大面积 | Max Area of Island

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...

  7. [Swift]LeetCode816. 模糊坐标 | Ambiguous Coordinates

    We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)".  Then, we re ...

  8. Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json

    需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0,  "data": {},  "msg": ...

  9. Python内置函数(30)——hex

    英文文档: hex(x) Convert an integer number to a lowercase hexadecimal string prefixed with “0x”, for exa ...

  10. 「造个轮子」——cicada 源码分析

    前言 两天前写了文章<「造个轮子」--cicada(轻量级 WEB 框架)> 向大家介绍了 cicada 之后收到很多反馈,也有许多不错的建议. 同时在 GitHub 也收获了 80 几颗 ...