1、环境准备
因为电脑是win10,所以准备anaconda来配置python3环境
2、安装flask很简单
#创建新的虚拟环境 conda create --name python35 python=3.5 # 激活某个环境 activate python37 #安装flask pip install flask3、项目目录结构
注意:
- app ——Flask 程序保存在此文件夹中
- controller 接口编写文件 保存在此文件夹中
- test.py 接口编写文件
- models.py: 对象的定义
- templates:存放的是模板文件,必须与__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/') def profile(username): return jsonify(who=username)
index.html:
111 this is index.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
更多python相关文章请关注python自学网。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)