![](/img/trans.png)
[英]How to run Uvicorn FastAPI server as a module from another Python file?
[英]How to run flask server from another module?
我正在嘗試從另一個模塊運行 flask 服務器,然后關閉服務器(這不是應用程序的重點),目前 webserver.py 的代碼看起來像這樣
from flask import Flask, render_template
from flask_classful import FlaskView
import os
from werkzeug.utils import secure_filename
from flask import request
host = 'localhost'
debug = True
app = Flask (__name__)
app.config
@app.route('/')
def main():
return render_template("index.html")
def run():
if __name__ == 'Refactor2':
app.run(ssl_context = (r"path_to_cert", r"path_to_key"), host = "localhost", port = 443)
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
def shutdownServer():
shutdown_server()
return "Server is shutting down"
然后我嘗試在以下模塊(名為 Refactor2)中運行它:
import webserver
class buyer:
def __init__(self, email, password):
self.email = email
self.password = password
def server_run(self):
run()
print("Server has been started")
但是,服務器沒有運行,我無法導航到網頁。 沒有顯示錯誤消息。
__name__
給出當前模塊的名稱。 所以在你的run()
方法__name__
可能解析為webserver
。 我建議將名稱作為變量從server_run()
傳遞給run()
)
網絡服務器.py
def run(name):
if name == 'Refactor2':
app.run(ssl_context = (r"path_to_cert", r"path_to_key"), host = "localhost", port = 443)
重構2
import webserver
class buyer:
def __init__(self, email, password):
self.email = email
self.password = password
def server_run(self):
run(__name__)
print("Server has been started")
請注意,如果 Refactor2 在 package 中,您可能會得到一個帶點的模塊名稱,例如“src.Refactor2”。 傳遞一個更明確的名稱來運行可能會更好,就像你重命名 Refactor2 一樣,你也需要在 webserver.py 中更新你的硬代碼。 就像是
def server_run(self):
webserver.run('buyer')
print("Server has been started")
和
(網絡服務器.py)
def run(name):
if name == 'buyer':
app.run(ssl_context = (r"path_to_cert", r"path_to_key"), host = "localhost", port = 443)
編輯:不確定您是否提供了完整的代碼示例,但看起來您可能沒有在server_run()
中調用正確的run()
方法 - 看起來應該在我編輯的 webserver 模塊上調用它回答反映
啟動 Flask 應用程序似乎是一種不尋常的方式,但除此之外......
假設您使用python Refactor2.py
運行它, __name__
將是'webserver'
。
這可以用一個最小的例子來證明:
$ cat webserver.py
def run():
print (__name__)
$ cat Refactor2.py
import webserver
webserver.run()
$ python Refactor2.py
webserver
因此,在您的webserver
模塊中,您可以這樣做:
def run():
if __name__ == 'webserver':
app.run(ssl_context = (r"path_to_cert", r"path_to_key"), host = "localhost", port = 443)
要不就:
def run():
app.run(ssl_context = (r"path_to_cert", r"path_to_key"), host = "localhost", port = 443)
並稱它為:
import webserver
# ...
class buyer:
# ...
def server_run(self):
webserver.run()
print("Server has been started")
當然,在服務器( webserver.run
調用)完成並且服務器停止之前,實際上不會到達“服務器已啟動”。
同樣,這似乎是一種奇怪的啟動應用程序的方式。 我建議您研究有關如何在生產中運行 Flask 的文檔,因為您似乎想要實現的是編排系統的工作,而不是 python 流程本身。 在生產環境中,您應該使用像 gunicorn 這樣的 WSGI 服務器,而不是開發服務器 ( app.run
)。 當然,也許你已經知道了;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.