Python Flask快速入门教程(1)——搭建一个简单的web项目

之前没怎么接触过python,因实习期间接触到flask,只知道它是一个轻量级的基于 Python 的框架,扩展性非常良好。准备写一些文章来记录一下学习过程中的点点滴滴


1、环境准备

因为电脑是win10,所以准备anaconda来配置python3环境

如果不清楚的话,大家可以参考我之前的文章:

win10 Anaconda和Pycharm的安装与配置

win10下用Anaconda安装TensorFlow,并在pycharm中使用(超简单)

anaconda pip和conda安装包 及虚拟环境(conda&virtualenv)的巧妙使用

2、安装flask

很简单


#创建新的虚拟环境
conda create --name python35 python=3.5 

# 激活某个环境
activate python37    

#安装flask
pip install flask       

3、项目目录结构

注意:

  • app ——Flask 程序保存在此文件夹中
  • controller  接口编写文件 保存在此文件夹中
  • test.py 接口编写文件
  • models.py: 对象的定义
  • templates:存放的是模板文件,必须与__init__.py同级
  • __init__.py 
  • __init__.py 文件的作用是将文件夹变为一个Python模块,Python 中的每个模块的包中,都有__init__.py 文件。

  • 通常__init__.py 文件为空,但是我们还可以为它增加其他的功能。我们在导入一个包时,实际上是导入了它的__init__.py文件。这样我们可以在__init__.py文件中批量导入我们所需要的模块,而不再需要一个一个的导入。

  • requirements.txt —— 列出了所有的依赖包,以便于在其他电脑中重新生成相同的环境
  • run.py: 启动运行文件
  • migrations ——包含数据库迁移脚本(安装了 flask-migrate 后自动生成)
  • tests ——单元测试放在此文件夹下
  • config.py 存储配置
  • manage.py 启动程序或者其他任务
  • gun.conf Gunicorn 配置文件

在命令行中依次使用以下命令来安装 Flask 扩展:

pip install flask-script
pip install flask-sqlalchemy
pip install flask-migrate

注意:flask-script 可以自定义命令行命令,用来启动程序或其它任务;flask-sqlalchemy 用来管理数据库的工具,支持多种数据库后台;flask-migrate 是数据库迁移工具,该工具命令集成到 flask-script 中,方便在命令行中进行操作。

别忘了在requirements.txt中添加包名及版本

首先是__init__.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask

app = Flask(__name__)

from app.controller import test

在这里声明了app对象,同时指明在test.py中我们引用了app

test.py(接口文件):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import jsonify
from flask import render_template
from app import app


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

@app.route("/hello", methods=['GET', ])
def hello():
    return jsonify(msg="hello world!")

@app.route('/test/<username>')
def profile(username):
    return jsonify(who=username)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>111</title>
</head>
<body>

this is index.html

</body>
</html>

启动文件:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from app import app


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)

4、测试

5、补充

直接在终端使用如下命令即可创建 requirements.txt 文件:

pip freeze > requirements.txt

以后在新的环境装环境:

pip install -r requirements.txt

参考:

https://dormousehole.readthedocs.io/en/latest/

http://docs.jinkan.org/docs/flask/quickstart.html#static-files

猜你喜欢

转载自blog.csdn.net/qq_41603102/article/details/88785930