Python 是否可以在不启动/停止服务器、调用os.kill或使用命令行的情况下关闭Flask应用程序?

Python 是否可以在不启动/停止服务器、调用os.kill或使用命令行的情况下关闭Flask应用程序?,python,flask,Python,Flask,我需要在Flask服务器上启动和停止一个简单的Python应用程序,在该应用程序运行并修改主目录中的文件之后。该应用程序位于G云上。我研究过类似的问题,包括使用命令行、操作系统和http.server停止应用程序。在我的案例中,这些方法都不起作用。最好的选择似乎是向包含request.environment.get函数的应用程序路由发出请求,我在这里尝试过这样做。但是脚本触发了以下回溯:TypeError:view函数没有返回有效的响应。返回类型必须是字符串、dict、tuple、响应实例或WS

我需要在Flask服务器上启动和停止一个简单的Python应用程序,在该应用程序运行并修改主目录中的文件之后。该应用程序位于G云上。我研究过类似的问题,包括使用命令行、操作系统和http.server停止应用程序。在我的案例中,这些方法都不起作用。最好的选择似乎是向包含request.environment.get函数的应用程序路由发出请求,我在这里尝试过这样做。但是脚本触发了以下回溯:
TypeError:view函数没有返回有效的响应。返回类型必须是字符串、dict、tuple、响应实例或WSGI可调用,但它是响应。
类型错误:shutdown\u server()接受0个位置参数,但提供了2个
。我是否可以使用脚本关闭应用程序,而不启动/停止服务器(即使用http.server)?如果是,我做错了什么

from flask import Flask, render_template, request, jsonify
import urllib.request, urllib.parse, urllib.error
from urllib.request import urlopen
from bs4 import BeautifulSoup
import textwrap
from hidden import consumer_key, consumer_secret, access_token, access_token_secret
import tweepy
from tweepy import TweepError
import requests

app = Flask(__name__, template_folder = 'templates')
app.config.update(
   SERVER_NAME = "127.0.0.1:8080"
)

@app.route('/')

def check_status():
   with open('app_status.txt') as f:
       status = f.read()
   status = status.rstrip()
   status = int(status)
   if status == 1:
       with open('app_status.txt', 'w+') as f:
           f.write(F'0')
       print('exiting')    
       return requests.get('http://127.0.0.1:8080/shutdown')
   if status == 0:
       return get_chunk()

def get_chunk():

   ...

   # Create the app's weboutput by rendering an html template

   if tweet:
       with open('app_status.txt', 'w+') as f:
           f.write(F'1')
       with app.app_context():
           return render_template('index.html', excrpt = chunk_wrp), requests.get('http://127.0.0.1:8080/shutdown')
           
         
@app.route("/shutdown", methods=['GET'])

def shutdown():
   shutdown_func = request.environ.get('werkzeug.server.shutdown')
   if shutdown_func is None:
       raise RuntimeError('Not running werkzeug')
   shutdown_func()
   return "Shutting down..."

if __name__ == '__main__':
   app.run(host='127.0.0.1', port=8080, debug=True, use_reloader=True)

通过查看mod_wsgi文档,可以得到终止守护进程的代码。目前,这似乎正在发挥作用:

import signal
import os
#...#
def shutdown():
    return os.kill(os.getpid(), signal.SIGINT)

为什么您希望
stop
会被呼叫?那么,
app\u status.py
是如何集成到这个系统中的呢?你到底想解决什么问题?这似乎是一个非常复杂的方法来实现一些可以用更直接的方式解决的问题。谢谢,MatsLindh。我删除了stop()调用,所以希望问题已经解决。正在使用App_status.py建立关闭条件。是的,这无疑比必要的更复杂。也许可以使用全局变量来代替。但我更关心的是关机问题,你的解释是你需要关机才能重新启动进程;为什么需要重新启动该过程?这将告诉我们应该如何做,以及使用什么工具。通常没有很好的理由从Flask内部终止进程,而是在必要时要求wsgi服务器(例如gunicorn)处理重新启动。谢谢,MatsLindh。我的计划是在从主目录中的更新文件导入新数据后,使用cron作业每天运行一次服务。每个实例都会更新该文件。这就是一些复杂问题的原因。另外,我想避免服务无缘无故地一直运行。听起来Flask不适合您想要做的事情。使用Flask,而不是在必要时通过cron运行python脚本的原因是什么?