我尝试过使用信号、击键记录、多重处理来关闭服务器,但没有任何运气。我希望这个 Flask 应用程序运行,从redirect_uri 返回代码,然后退出服务器并继续主流程。这是我到目前为止所拥有的。
import webbrowser
from flask import Flask, request
app = Flask(__name__)
server = Process
code = ''
client_id = "4325234352342324"
redirect_uri = "http://localhost:80/shutdown"
@app.route('/')
def data():
data = request.args
return data
@app.after_request
def write_file():
code = request.args['code']
f = open('code.txt', 'w')
f.write(code)
@app.before_first_request
def before_request():
webbrowser.open(f"https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code")
@app.route('/shutdown')
def server_shutdown():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
if __name__ == '__main__':
app.run(host='localhost', port=80)
我看到您尝试使用过时的选项关闭服务器(我说的是
server_shutdown
功能)。因此,在此补丁之后,
werkzeug.server.shutdown
已被弃用。目前,最好按照 Werkzeug 文档 中的描述进行操作。当然,那里没有 Flask 应用程序,但更改代码以满足您的需求并不困难。我还发现 Flask github 讨论中提出了一个类似的问题,这也应该对你有帮助。
UPD [03.07.2022]
好吧,机器人说我可以添加一些东西,但不太可能需要任何文章或文档等材料,因为我已经添加了可能对提出问题的人和我提出问题的人有用的所有信息来源。用于解决这个问题。所以我决定添加一些代码。在这里:
import multiprocessing
from flask import Flask, request
def github_oauth(q: multiprocessing.Queue) -> None:
app = Flask(...)
# here you describe your endpoint(s)
app.run('localhost', 80)
if __name__ == "__main__":
q = multiprocessing.Queue()
p = multiprocessing.Process(target=github_oauth, args=(q,))
p.start()
print("waiting")
code = q.get(block=True)
p.terminate()
print(code)
# do something else...
因此,你只需要正确编写Flask应用程序的逻辑即可。当你这样做时,你将能够通过
requests
库或通过浏览器或其他东西发出单个请求,然后继续在主流程中做一些事情