Flask 知識點補充

一、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’] 獲取配置的值,會報錯,是什麼原因呢?

  1. app.config[‘DEBUG’] 會得到 False? 因爲DEBUG 是 config 中的一個默認參數,默認就是Flask。
  2. 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結構導圖

  1. 統一返回數據結構。
  2. 對數據進行預處理,返回更符合前端頁面需要的數據。

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核上面執行一個線程。

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 開啓進程個數

相關文章

Flask 模塊基礎篇
Python Threading 線程模塊用法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章