文档章节

Flask

greister
 greister
发布于 2015/08/04 15:02
字数 1224
阅读 117
收藏 0

How To Structure Large Flask Applications

https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications

Introduction

There are many methods and conventions for structuring Python web applications. Although certain frameworks are shipped with tools (for scaffolding) to automate -- and ease -- the task (and the headaches), almost all solutions rely on packaging / modularizing applications as the codebase gets distributed [logically] across related files and folders.

The minimalist web application development framework Flask, has its own - blueprints.

In this DigitalOcean article, we are going to see how to create an application directory, and structure it to work with re-usable components created with Flask's blueprints. These pieces allow (and simplify) the maintenance and the development of application components greatly.

Glossary

  1. Flask: The Minimalist Application Development Framework

  2. Our Choices In This Article

  3. Preparing The System For Flask

    Prepare The Operating System Setting up Python, pip and virtualenv

  4. Structuring The Application Directory

    Creating Application Folder Creating A Virtual Environment Creating Application Files Installing Flask

  5. Working With Modules And Blueprints (Components)

    Module Basics Module Templates

  6. Creating The Application (run.py, init.py, etc.)

    Edit run.py using nano Edit config.py using nano

  7. Creating A Module / Component

Step 1: Structuring The Module Step 2: Define The Module Data Model(s) Step 3: Define Module Forms Step 4: Define Application Controllers (Views) Step 5: Set Up The Application in “app/init.py” Step 6: Create The Templates Step 7: See Your Module In Action

## Flask: The Minimalist Application Development Framework

Flask is a minimalist (or micro) framework which refrains from imposing the way critical things are handled. Instead, Flask allows the developers to use the tools they desire and are familiar with. For this purpose, it comes with its own extensions index and a good amount of tools already exist to handle pretty much everything from log-ins to logging.

It is not a strictly "conventional" framework and relies partially on configuration files, which frankly make many things easier when it comes to getting started and keeping things in check.

Our Choices In This Article

As we have just been over in the previous section, Flask-way of doing things involves using the tools you are most comfortable with. In our article, we will be using -- perhaps -- the most common (and sensible) of choices in terms of extensions and libraries (i.e. database extraction layer). These choices will involve:

  • SQLAlchemy (via Flask-SQLAlchemy)
  • WTForms (via Flask-WTF)

#### Flask-SQLAlchemy

Adds SQLAlchemy support to Flask. Quick and easy.

This is an approved extension.

Flask-WTF offers simple integration with WTForms. This integration includes optional CSRF handling for greater security.

This is an approved extension.

Author: Anthony Ford (created by Dan Jacob)
PyPI Page: Flask-WTF
Documentation: Read docs @ packages.python.org
On Github: [ajford/flask-wtf](https://github.com/mitsuhiko/flask-wtf)

## Preparing The System For Flask

Before we begin structuring a large Flask application, let's prepare our system and download (and install) Flask distribution.

Note: We will be working on a freshly instantiated droplet running the latest version of available operating systems (i.e. Ubuntu 13). You are highly advised to test everything on a new system as well - especially if you are actively serving clients.

Prepare The Operating System

In order to have a stable server, we must have all relevant tools and libraries up-to-date and well maintained.

To ensure that we have the latest available versions of default applications, let's begin with updates.

Run the following for Debian Based Systems (i.e. Ubuntu, Debian):

aptitude    update
aptitude -y upgrade

To get the necessary development tools, install “build-essential” using the following command:

aptitude install -y build-essential python-dev python2.7-dev

如果要使用python3,虽然Flask不建议使用。

Setting up Python, pip and virtualenv

On Ubuntu and Debian, a recent version of Python interpreter - which you can use - comes by default. It leaves us with only a limited number of additional packages to install:

  • python-dev (development tools)
  • pip (to manage packages)
  • virtualenv (to create isolated, virtual

Note: Instructions given here are kept brief. To learn more, check out our how-to article on pip and virtualenv: Common Python Tools: Using virtualenv, Installing with Pip, and Managing Packages.

pip

pip is a package manager which will help us to install the application packages that we need.

Run the following commands to install pip:

curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python -
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python -

export PATH="/usr/local/bin:$PATH"

Note: 你也可也使用 apt-get install python-pip

virtualenv

It is best to contain a Python application within its own environment together with all of its dependencies. An environment can be best described (in simple terms) as an isolated location (a directory) where everything resides. For this purpose, a tool called virtualenv is used.

Run the following to install virtualenv using pip:

  sudo pip install virtualenv

Structuring The Application Directory

We will use the exemplary name of LargeApp as our application folder. Inside, we are going to have a virtual environment (i.e. env) alongside the application package (i.e. app) and some other files such as “run.py” for running a test (development) server and “config.py” for keeping the Flask configurations.

The structure - which is given as an example below - is highly extensible and it is built to make use of all helpful tools Flask and other libraries offer. Do not be afraid when you see it, as we explain everything step by step by constructing it all.

~/LargeApp |-- run.py |-- config.py |__ /env # Virtual Environment |__ /app # Our Application Module |-- init.py |-- /module_one |-- init.py |-- controllers.py |-- models.py
|__ /templates |__ /module_one |-- hello.html |__ /static |__ .. |__ . |__ .. |__ .

Creating Application Folders

Let's start with creating the main folders we need.

Run the following commands successively to perform the task:

mkdir ~/LargeApp
mkdir ~/LargeApp/app
mkdir ~/LargeApp/app/templates
mkdir ~/LargeApp/app/static   

Our current structure:

~/LargeApp |__ /app # Our Application Module |__ /templates |__ /static

Creating A Virtual Environment

Using a virtual environment brings with it a ton of benefits. You are highly suggested to use a new virtual environment for each one of of your applications. Keeping the virtualenv folder inside your application's is a good way of keeping things in order and tidy.

cd         ~/LargeApp
virtualenv env

**Note: ** 如果要使用python3: virtualenv -p /usr/bin/python3 py3env python3 要先下载下来。

激活虚拟环境

source  env/bin/activate

Note: 要在此目录下才能激活

Creating Application Files

In this step, we will form the basic application files before moving on to working with modules and blueprints.

Run the following to create basic application files:

touch ~/LargeApp/run.py
touch ~/LargeApp/config.py
touch ~/LargeApp/app/__init__.py

Our current structure:

~/LargeApp |-- run.py |-- config.py |__ /env # Virtual Environment |__ /app # Our Application Module |-- init.py |__ /templates |__ /static

Installing Flask And Application Dependencies

Once we have everything in place, to begin our development with Flask, let's download and install it using pip.

Run the following to install Flask inside the virtual environment env.

cd ~/LargeApp
pip install flask
pip install flask-sqlalchemy
pip install flask-wtf

Note: Here we are downloading and installing Flask without activating the virtual environment. However, given that we are using the pip from the environment itself, it achieves the same task. If you are working with an activated environment, you can just use pip instead. 已经修改为激活后的环境。

And that's it! We are now ready to build a larger Flask application modularized using blueprints.

© 著作权归作者所有

greister
粉丝 0
博文 41
码字总数 24526
作品 0
济宁
私信 提问
Flask插件与资源整理

flask-script 支持命令行选相 使用示例 flask-bootstrap 集成Bootstrap flask-moment 本地化日期和时间 flask-wtf网络表单类防止跨站伪请求CSRF flask-sqlalchemy数据库框架ORM或ODM转换 数据...

晴难自控
2017/11/19
0
0
在aliyun linux 上,安装caravel,创建admin用户时报 unable to import caravel Error: invalid syntax (views.py, line 613)

根据官网文档,在aliyun linux 上安装caravel,在执行fabmanager create-admin --app caravel命令,录入邮箱后,出现问题: Added Permission menu access on Permission on Views/Menus to ......

剑无虚
2016/04/15
2.5K
6
Flask Web开发新手指南

Flask框架是Python开发的一个基于Werkzeug和Jinja 2的web开发微框架,它的优势就是极其简洁,但又非常灵活,而且容易学习和应用。因此Flask框架是Python新手快速开始web开发最好的选择,此外...

汇智网教程
2018/12/10
193
0
在flask中使用flask-migrate管理数据库

Flask-Migrate是一个为Flask应用处理SQLAlchemy数据库迁移的扩展,使得可以通过Flask的命令行接口或者Flask-Scripts对数据库进行操作。 安装 pip3 install Flask-Migrate 例子:test.py 上述代...

小家雀
2018/12/06
146
0
熟悉Flask框架------第一天(调试模式、路由、模板渲染等)

http://docs.jinkan.org/docs/flask/quickstart.html 1、一个最小的应用 hello.py 默认端口为5000,直接访问http://127.0.0.1:5000/ 关闭服务器:Ctrl+C PS:如果禁用了debug模式或所在网络的用...

YJ_
2017/11/22
13
0

没有更多内容

加载失败,请刷新页面

加载更多

检查字符串是否不为空且不为空

如何检查字符串是否不为null也不为空? public void doStuff(String str){ if (str != null && str != "**here I want to check the 'str' is empty or not**") { /* handl......

javail
6分钟前
7
0
No module named 'apscheduler.schedulers'

关于 ModuleNotFoundError: No module named 'apscheduler.schedulers' 和 ModuleNotFoundError: No module named 'apscheduler' 的问题,网上有不少解决。大多数都是因为,文件起名与模块名......

開援带碼
28分钟前
27
0
如何查看Android的系统版本?

有谁知道我怎么能检查系统版本(例如1.0 , 2.2 ,等)编程? #1楼 我无法对答案发表评论,但是Kaushik的答案存在一个严重错误:SDK_INT与系统版本不同,但实际上是指API级别。 if(Build.VER...

技术盛宴
53分钟前
35
0
引入AI变量,精准农业正在加速豹变?

  不久前,“江苏省脱贫率达 99.99%,尚未脱贫人数仅剩 6 户、17 人”这样一则新闻刷屏。“把这 17 个人迁出,江苏就全省脱贫”、“最后这 6 户人家拖了后腿”,在网民们的调侃和质疑声背后...

水果黄瓜
56分钟前
41
0
Elasticsearch系列---结构化搜索

概要 结构化搜索针对日期、时间、数字等结构化数据的搜索,它们有自己的格式,我们可以对它们进行范围,比较大小等逻辑操作,这些逻辑操作得到的结果非黑即白,要么符合条件在结果集里,要么...

清茶豆奶
今天
69
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部