一、Flask-HelloWorld项目结构
二、基本操作
1. app.py
import numpy as np
from flask import *
from util import *
import json
from flask_sqlalchemy import SQLAlchemy
# 解决python3数据库连接问题
# MySQLdb只支持Python2.*,还不支持3.* 可以用PyMySQL代替。
import pymysql
pymysql.install_as_MySQLdb()
from util.ReslutReturn import *
# 指明工程文件,代表当前py文件所在目录为工程目录 __name__ == '__main__'
app = Flask(__name__,static_folder='static',static_url_path='/static',template_folder='templates')
# 配置对象加载配置信息
class DefaultConfig(object):
"""
默认配置
"""
KEY = 'wskh45700037'
# 设置app配置
# app.config.from_object(DefaultConfig)
app.config.from_pyfile('setting.py')
# 创建蓝图对象
user_bp = Blueprint('user',__name__)
# 注册蓝图
app.register_blueprint(user_bp,url_prefix="/user")
# 数据库配置 绑定app
db = SQLAlchemy(app)
# 创建数据库模型类
class CbyUser(db.Model):
"""
user表
"""
__tablename__ = "cby_user"
id = db.Column(db.String,primary_key=True)
name = db.Column(db.String)
nick_name = db.Column(db.String)
password = db.Column(db.String)
email = db.Column(db.String)
phone = db.Column(db.String)
identity_id = db.Column(db.String)
detail = db.Column(db.String)
insert_time = db.Column(db.String)
update_time = db.Column(db.String)
def asDict(self):
return {"id":self.id,"name":self.name,"nick_name":self.nick_name,"password":self.password,"email":self.email,"phone":self.phone,"identity_id":self.identity_id,"detail":self.detail}
# 全局异常处理
@app.errorhandler(500)
def errorHandle(e):
return error("全局异常捕获!")
# 指定异常捕获
@app.errorhandler(ZeroDivisionError)
def zero_error(e):
return error("除数不能为0!")
# 定义视图
@app.route('/')
# @app.post()
# @app.get()
# @app.delete()
# @app.put()
def hello_world():
key = app.config["KEY"]
print(key)
return 'Hello World!'
@app.route('/aaa')
def hello_Blueprint():
key = app.config["KEY"]
print(key)
return 'Hello user_bp!'
@app.route("/user/<int:userId>")
def getUserById(userId):
return str(userId)
@app.route("/testR/<int:userId>")
def testR(userId):
user = User()
userJson = user.asJson()
lis = [userJson,userJson,userJson,userJson,userJson]
r = ok("message",lis)
# r = error()
return r
@app.route("/testDb")
def testDb():
userList = CbyUser.query.all()
userDictList = []
for i in range(len(userList)):
userDictList.append(userList[i].asDict())
print(userDictList)
return ok("查询成功",userDictList)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, bytes):
return str(obj, encoding='utf-8')
else:
return super(MyEncoder, self).default(obj)
class User:
def __init__(self):
self.name = "wskh"
self.id = '111'
def asJson(self):
return {"name":self.name,"id":self.id}
if __name__ == '__main__':
# 以5454端口运行
app.run(port=5454)
2. setting.py
这里面用来写一些关于数据库的连接配置
# -*-coding:utf-8-*-
# 密钥 随便设置
KEY = "wskh66666666666666666"
# jdbc:mysql://localhost:3306/cby?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
# "mysql://root:mysql@127.0.0.1:3306/cby"
SQLALCHEMY_DATABASE_URI = "mysql://%s:%s@%s/%s" % ('用户名', '密码', 'ip', '数据库名称')
# 设置这一项是每次请求结束后都会自动提交数据库中的变动
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
3. ReslutReturn.py
统一信息返回处理
# -*-coding:utf-8-*-
success_code = 200
error_code = 500
def ok(message="请求成功",data=None):
dic = {'code':success_code,'message':message,'data':data}
return dic
def error(message = "请求失败",data=None):
dic = {'code':error_code,'message':message,'data':data}
return dic
# 三、效果展示 运行app.py ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/dc56f2b067b245149503b2e9caf6b58b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAV1NLSDA5Mjk=,size_20,color_FFFFFF,t_70,g_se,x_16) 点击下方链接 ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/b2b9e0f2a049410e8e69b66dad7db0f9.png) ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/7fcd5942ecf04d6bbd925a74e0ef6708.png) 可以看到hellworld成功显示了! 继续在网址后追加/testDb 测试和数据库的连接(完整url:http://127.0.0.1:5454/testDb) ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/753f8e3174aa4ccebfe10c220d1693c3.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAV1NLSDA5Mjk=,size_20,color_FFFFFF,t_70,g_se,x_16) 可以看到数据库信息正常返回了! 而且之前设定的统一结果返回中的成功状态码200也成功加入其中了! ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/9c968b6e2f5b4ec5adca3b58b054bd93.png) 好啦!关于flask的简单入门就到此结束了,喜欢的小伙伴可以点个关注,后续会不定时更新~