Solve the problem of importing flask project in Windows background script to start deployment

Using the terminal window cmd to start the python+flask program on windows will cause the package import error. This is due to the problem of the personal project architecture. Here, the create_app function is placed in the init.py file in the src directory, which leads to the failure. The src module can be run directly in pycharm, but not here. Generally speaking, it is ok. There is no problem running in a virtual environment on Linux.
Insert picture description here
init.py

import os

from flask import Flask
from flask_cors import CORS


def create_app():
    app = Flask(__name__)  # 创建1个Flask实例
    PIC_FOLDER = os.path.join(app.root_path, 'static')
    CORS(app, resources=r'/*')
    # 3. register bluePrint
    from com.callElevator import callElevator_blu
    app.register_blueprint(callElevator_blu)
    return app

main.py

from src import create_app
# 创建应用
app = create_app()

if __name__ == '__main__':
    """ server host/port"""
    connectHost = config.LOCAL_SERVER_HOST
    connectPort = config.LOCAL_SERVER_PORT

    """ start flask """
    app.run(host=connectHost, port=connectPort, debug=True)

The above import method is not working on windows

Solution: Create the create_app function directly in the main.py file and use it directly.

main.py

def create_app():
    app = Flask(__name__)  # 创建1个Flask实例
    PIC_FOLDER = os.path.join(app.root_path, 'static')
    CORS(app, resources=r'/*')
    # 3. register bluePrint
    from com.callElevator import callElevator_blu
    app.register_blueprint(callElevator_blu)
    return app

logger = MyLogger(prepareLogging("smartHomeService", consts.LOG_DIR))
# 创建应用
app = create_app()

if __name__ == '__main__':
    # conMQttClientThread = threading.Thread(target=connectMQttClient)
    # conMQttClientThread.start()
    connectMQttClient(logger)

    """ server host/port"""
    connectHost = config.LOCAL_SERVER_HOST
    connectPort = config.LOCAL_SERVER_PORT

    """ start flask """
    app.run(host=connectHost, port=connectPort, debug=True)

Insert picture description here
As you can see, the project started successfully using the .bat file!

Attach the code of the .bat script file

title=smartHomeService-V1.0
color 0F
rem @echo off
cd %~dp0
set cd=%~dp0
set PY_HOME=D:\Install\Python3.5.3
set PYTHONPATH=D:\Install\Env\ElevDispatching\Lib\site-packages;
set PATH=%PATH%;%PY_HOME%;%PY_HOME%/Scripts;%cd%/Scripts
@echo on
cd src
python main.py

Guess you like

Origin blog.csdn.net/qq_43030934/article/details/107333532