当我通过$ uvicorn example:app或$ gunicorn -w 4 -k uvicorn.workers.UvicornWorker从命令行运行uvicorn服务器时,如何将优化标志-OO传递给Python解释器?任何帮助都将不胜感激!
发布于 2022-02-13 12:34:04
例如,我们有以下应用程序:
from fastapi import FastAPI
app = FastAPI()
@app.on_event('startup')
async def startup_event():
print('__debug__', __debug__)独角兽可以这样运行:
$ python -O -m uvicorn example:app
INFO: Started server process [49759]
INFO: Waiting for application startup.
__debug__ False
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)持枪人与:
$ python -O -m gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker example:app
[2022-02-13 15:17:39 +0300] [49801] [INFO] Starting gunicorn 20.1.0
[2022-02-13 15:17:39 +0300] [49801] [INFO] Listening at: http://127.0.0.1:8000 (49801)
[2022-02-13 15:17:39 +0300] [49801] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2022-02-13 15:17:39 +0300] [49802] [INFO] Booting worker with pid: 49802
[2022-02-13 15:17:39 +0300] [49802] [INFO] Started server process [49802]
[2022-02-13 15:17:39 +0300] [49802] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49802] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49804] [INFO] Booting worker with pid: 49804
[2022-02-13 15:17:39 +0300] [49805] [INFO] Booting worker with pid: 49805
[2022-02-13 15:17:39 +0300] [49804] [INFO] Started server process [49804]
[2022-02-13 15:17:39 +0300] [49804] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49804] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49805] [INFO] Started server process [49805]
[2022-02-13 15:17:39 +0300] [49805] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49805] [INFO] Application startup complete.
[2022-02-13 15:17:39 +0300] [49806] [INFO] Booting worker with pid: 49806
[2022-02-13 15:17:39 +0300] [49806] [INFO] Started server process [49806]
[2022-02-13 15:17:39 +0300] [49806] [INFO] Waiting for application startup.
__debug__ False
[2022-02-13 15:17:39 +0300] [49806] [INFO] Application startup complete.发布于 2022-02-04 06:01:37
您可能需要以编程方式运行uvicorn,然后使用-O运行代码。
# main.py
import uvicorn
class App:
...
app = App()
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=5000)然后用python -O main.py运行它
验证代码是否实际使用-O标志运行的一种方法是使用断言。断言语句从优化的代码中删除,因此您可以在main.py中的某个地方添加这段代码。
try:
assert False
except AssertionError:
print("Warning: code is not optimized")
else:
print("Running optimized code")https://stackoverflow.com/questions/64858127
复制相似问题