一、Flask基础
1.1、路由 route 装饰器原理
@app.route(’’,methods=[]) 装饰器是通过调用 Flask 中的 add_url_rule() 注册路由方法实现。
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
1.2、Flask视图函数 return 与 普通函数 return 区别
Flask视图函数 return 返回内容是经过了Flask封装的 Response 对象。其中包含了很多 HTTP 请求头中的内容。
# _*_ coding:utf-8 _*_
from flask import Flask, make_response
app = Flask(__name__)
app.config.from_object('config.config')
@app.route('/index')
def index():
response = make_response('{"a":123}', 404) # 通过 make_response 实例化 response 对象
headers = {
'content-type': 'text/json',
'location':'http://www.baidu.com'
'status code':404
}
response.headers = headers
return response
# return '返回内容',404,headers
# return jsonify() # jsonify方法返回json数据类型。
# return render_teplate() # 返回模板
# return redirect() # 重定向
if __name__ == "__main__":
app.run()
1.3、配置文件大小写问题
如果,在配置文件配置“Debug=True”时,通过 app.config[‘DEBUG’] 获取配置的值,会得到 False;但是通过 app.config[‘Debug’] 获取配置的值,会报错,是什么原因呢?
- app.config[‘DEBUG’] 会得到 False? 因为DEBUG 是 config 中的一个默认参数,默认就是Flask。
- app.config[‘Debug’] 会报错?因为通过 app.config.from_object() 关联配置文件,规定所有配置项key值必须大写。
1.3.1、注册配置文件的几种方式
A、app.config.from_pyfile('./config/secure.py') # py文件
app.config.from_object("app.config.setting") # 模块形式
B、app.config.from_object("app.config.setting.Setting") # 类的形式
C、app.config.from_json('./config/config.json') # json文件
A、py文件、模块形式
DEBUG=True
B、类的形式
class Setting:
DEBUG=True
C、Json 文件形式
{
"DEBUG":"True"
}
二、ViewModel模型使用
2.1、什么是ViewModel模型
ViewModel 是将数据库的原始数据结构重新编辑结构,保存为前端页面所需要的数据。
2.2、为什么要使用ViewModel模型
- 统一返回数据结构。
- 对数据进行预处理,返回更符合前端页面需要的数据。
ViewModel 代码编写的方式:
class ArcticleViewModel:
def __init__(self):
pass
def colviewmodel(self, data):
# 定义返回到前端页面的数据格式
coldata = {
'id': data['id'],
'reid': data['reid'],
'typename': data['typename'],
'typedir': data['typedir'],
'seotitle': data['seotitle'],
'description': data['description'],
'keywords': data['keywords']
}
return coldata
三、进程与线程
进程:分配资源,内存资源,一个进程可以包含一个或者多个线程。
线程:利用 CPU 执行代码,必须属于一个进程,不能分配资源,可以访问进程资源。
为什么Python不能充分利用CPU多核的优势?
因为python中有个GIL锁机制,导致了这个问题,同一时刻只能在一个CPU核上面执行一个线程。
扫描二维码关注公众号,回复:
5951144 查看本文章
CIL锁的作用?
保证操作线程的安全,只支持 cpython 解释器。
Flask解决多线程问题?
线程隔离,意义在于是当前线程能够正确引用到他自己所创建的对象,而不是引用其他线程所创建的对象。
# _*_ coding:utf-8 _*_
from flask import Flask, make_response
app = Flask(__name__)
app.config.from_object('config.config')
@app.route('/index')
def index():
return 'hello word'
if __name__ == "__main__":
app.run(threaded=True,process=1)
# Threaded 启用多线程
# process 开启进程个数