#對整個應用做初始化操作 #主要工作: # 1.構建Flask的應用以及各種配置 #2.構建SQLAlchemy的應用 from flask import Flask from flask_sqlalchemy import SQLAlchemy import pymysql import eventlet from flask_mqtt import Mqtt from datetime import timedelta from flask_jwt_extended import JWTManager from flask_socketio import SocketIO jwt = JWTManager() #綠化(綠色線程)所有系統模組,實現IO多路複用 eventlet.monkey_patch() pymysql.install_as_MySQLdb() #設置上傳文件路徑 UPLOAD_FOLDER = 'app/static/farm_img' #設置允許文件副檔名 ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg', 'gif']) def create_app(): global UPLOAD_FOLDER app = Flask(__name__) #配置啟動模式為調適模式 # app.config['DEBUG'] = True #配置數據庫的連接字符串 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://sixth:skyeye@52.69.200.169:3306/Sixth' #配置數據庫內容再更新時自動提交 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True #配置session所需要的秘鑰 app.config['SECRET_KEY'] = 'you guess' # template 有修改後,會自動去更新 app.config['TEMPLATES_AUTO_RELOAD'] = True # 如果设置成True(默认情况),Flask - SQLAlchemy将会追踪对象的修改并且发送信号。这需要额外的内存, 如果不必要的可以禁用它 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True #資料库连接池的大小。默认是数据库引擎的默认值 (通常是5) app.config['SQLALCHEMY_POOL_SIZE'] = 100 #指定資料库连接池的超时时间。默认是 10 app.config['SQLALCHEMY_POOL_TIMEOUT'] = 60 * 60 #自动回收连接的秒数。这对 MySQL 是必须的,默认 情况下 MySQL 会自动移除闲置 8 小时或者以上的连接。 需要注意地是如果使用 MySQL 的话, Flask-SQLAlchemy 会自动地设置这个值为 2 小时 app.config['SQLALCHEMY_MAX_OVERFLOW'] = 15 #設置session有效期為31天 # app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=31) #設置上傳文件的路徑 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # 如果超過檔案大小限制,Flask將會拋出RequestEntityTooLarge的例外錯誤。 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB # 設定 JWT 密鑰 app.config['JWT_SECRET_KEY'] = 'this-should-be-change' jwt.init_app(app) # app.config['JWT_TOKEN_LOCATION'] = ['headers', 'query_string'] # app.config['JWT_TOKEN_LOCATION'] = ['query_string'] # app.config['JWT_QUERY_STRING_NAME'] = 'jwt' app.config['PROPAGATE_EXCEPTIONS'] = True app.config['SECRET'] = 'my secret key' #MQTT相關設置 app.config['MQTT_BROKER_URL'] = '60.250.156.234' app.config['MQTT_BROKER_PORT'] = 1883 app.config['MQTT_USERNAME'] = 'aisky-client' app.config['MQTT_PASSWORD'] = 'aiskyc' #將發送ping到代理的時間間隔設置60秒 app.config['MQTT_KEEPALIVE'] = 60 #出於測試目的將TLS設置為禁用 app.config['MQTT_TLS_ENABLED'] = False #數據庫的初始化 db = SQLAlchemy(app) db.init_app(app) mqtt = Mqtt(app) socketio = SocketIO(app, cors_allowed_origins='*') #將main藍圖程序與app關聯到一起 from .main import main as main_blueprint app.register_blueprint(main_blueprint) #將user藍圖程序與app關聯到一起 from .user import user as user_blueprint app.register_blueprint(user_blueprint) return app, db, mqtt, socketio