我想使用Flask 作为巨 Python 脚本的一部分.我想执行一些命令,然后运行FlaskTM服务器发送文件,并在10秒或更长时间后关闭服务器并继续运行脚本.

在执行Shut_Down函数后,出现一个错误,直到我在终端按下ctrl-c,REST脚本才会执行.以下是我的代码

from flask import send_from_directory, abort 
from flask import Flask
import socket
from flask import request
from flask_apscheduler import APScheduler


hostName= socket.gethostname()
ipAddr= socket.gethostbyname(hostName)
app= Flask(__name__)
app.config["CLIENT_IMAGES"]="photo"

socketio = SocketIO(app)
sched=APScheduler()
counter=0

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')    
    func()

@app.route("/")
def index():
    return "Hello World"


@app.route("/get-image/<string:image_name>") 
def get_image(image_name):    
    try:
        return send_from_directory(app.config["CLIENT_IMAGES"], "photo.jpg", as_attachment=True)
        
    except FileNotFoundError:
        abort(404)

if __name__=="__main__":
    sched.add_job(id='Job1',func=shutdown_server, trigger='interval', seconds=5)
    sched.start()
    #app.run()
    #socketio.run(app,host="0.0.0.0", port=4998,allow_unsafe_werkzeug=True)
    app.run(host=ipAddr, port='5000',debug= False) #,use_reloader=False 
    #os.system("start /b python app.py")
    #os.system("python "+ "app.py &" )
counter+=1
print("ALohaaa")

以下是错误:

Job "Job1 (trigger: interval[0:00:05], next run at: 2023-10-09 09:59:57 EEST)" raised an exception
Traceback (most recent call last):
  File "C:\Users\userName\anaconda3\Lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\users\ userName \desktop\jetson\camera test\mix\qr prog test\try03.py", line 21, in shutdown_server
    func = request.environ.get('werkzeug.server.shutdown')
           ^^^^^^^^^^^^^^^
  File "C:\Users\ userName \anaconda3\Lib\site-packages\werkzeug\local.py", line 311, in __get__
    obj = instance._get_current_object()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ userName \anaconda3\Lib\site-packages\werkzeug\local.py", line 508, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.

推荐答案

当您想要停止应用程序时,您可以显示关闭您的FASK应用程序的终结点,并通过cURL调用它

@app.route('/shutdown', methods=['POST'])
def shutdown():
   print("Shutting down gracefully...")
   os.kill(os.getpid(), signal.SIGINT)
   return 'Server shutting down...'

用curl 这样称呼它

curl -X POST http://localhost:5000/shutdown

你可以探索更多的选项HERE.

Python相关问答推荐

这些变量是否相等,因为它们引用相同的实例,尽管它们看起来应该具有不同的值?

使用Python从HTTP打印值

如何从不同长度的HTML表格中抓取准确的字段?

只需使用Python在图像中保留 colored颜色 范围区域

ValueRight:参数目标和输出必须具有相同的形状.接收:目标.形状=(无,512),输出.形状=(无,3)

使用itertools出现第n个子串

具有多个组的条形图的不同y标度

无法使用python.h文件; Python嵌入错误

使用from_pandas将GeDataFrame转换为polars失败,ArrowType错误:未传递numpy. dype对象

Polars:使用列值引用when / then表达中的其他列

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

cv2.matchTemplate函数匹配失败

将输入聚合到统一词典中

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

计算天数

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

将标签移动到matplotlib饼图中楔形块的开始处