安装包
1.app的__init__.py文件 项目中所有app的配置存放
import os
from flask import Flask
from flask_restplus import Api
from flask_sqlalchemy import SQLAlchemy
from config import config
app = Flask(__name__)
app.config.from_object(config[os.getenv('CONFIG_NAME') or 'default'])
#初始化SQLAlchemy
db = SQLAlchemy(app)
from .api.views import api as ns1
api = Api(
title='hello world',
version = '2.0.0',
description = 'hello world',
)
api.add_namespace(ns1,path='/api')
api.init_app(app)
2.api下的views文件
from flask import jsonify
from flask_restplus import Namespace, Resource
from app import db
from app.models.user import User
api = Namespace('api',description='hello视图')
@api.route('/index/users')
class Hello(Resource):
def get(self):
user_detail =[]
user_list = db.session.query(User).all()
for user in user_list:
print(user)
user_detail.append({
"user":user.id,
'name':user.name,
'email':user.email,
'age':user.age
})
context = {
'code':0000,
'msg':'success',
'data':user_detail
}
return jsonify(context)
3.models
from app import db
class User(db.Model):
__tablename__ = 'tb_user'
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.String(64), unique=True, name='name', doc='名字')
email = db.Column(db.String(128), name='email', doc='邮箱')
age = db.Column(db.Integer, name='age', doc='年龄')
def __repr__(self):
return '({},{},{},{})'.format(self.id, self.name, self.email, self.age)
if __name__ == '__main__':
db.create_all()
4.manager.py、config.py文件
4.1config.py
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS =True
SECRET_KEY = os.environ.get('SECRET_KEY') or 'helloworld'
FLASK_COVERAGE=True
class DevelopConfig(Config):
SQLALCHEMY_DATABASE_URI = 'postgres://alen:123456@127.0.0.1:5432/dbtornado'
config = {
'development':DevelopConfig,
'default':DevelopConfig,
}
4.2 manager.py
from app import app
from flask_script import Manager
manager = Manager(app)
COV =None
import os
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=False,include='app/*')
COV.start()
if __name__ == '__main__':
# for rule in app.url_map.iter_rules():
# rule = rule # type:Rule
# print(rule.rule,rule.methods,rule.endpoint)
manager.run()