FastAPI環(huán)境部署

測試環(huán)境

  • 安裝 uvicorn
    Uvicorn,是一個閃電般快速的ASGI服務(wù)器,基于uvloop和httptools構(gòu)建。
pip install uvicorn
  • 命令行啟動
uvicorn main:app --host 0.0.0.0 --port 80 --reload
  • 腳本中啟動
if __name__ == '__main__':
    uvicorn.run(
        app='main:app',
        host="0.0.0.0",
        port=8899,
        workers=4,
        reload=True,
        debug=True)
  • uvicorn 幫助說明
uvicorn --help
Usage: uvicorn [OPTIONS] APP

Options:
  --host TEXT                     Bind socket to this host.  [default:
                                  127.0.0.1]
  --port INTEGER                  Bind socket to this port.  [default: 8000]
  --uds TEXT                      Bind to a UNIX domain socket.
  --fd INTEGER                    Bind to socket from this file descriptor.
  --reload                        Enable auto-reload.
  --reload-dir TEXT               Set reload directories explicitly, instead
                                  of using the current working directory.
  --reload-delay FLOAT            Delay between previous and next check if
                                  application needs to be. Defaults to 0.25s.
                                  [default: 0.25]
  --workers INTEGER               Number of worker processes. Defaults to the
                                  $WEB_CONCURRENCY environment variable if
                                  available, or 1. Not valid with --reload.
  --loop [auto|asyncio|uvloop]    Event loop implementation.  [default: auto]
  --http [auto|h11|httptools]     HTTP protocol implementation.  [default:
                                  auto]
  --ws [auto|none|websockets|wsproto]
                                  WebSocket protocol implementation.
                                  [default: auto]
  --ws-max-size INTEGER           WebSocket max size message in bytes
                                  [default: 16777216]
  --lifespan [auto|on|off]        Lifespan implementation.  [default: auto]
  --interface [auto|asgi3|asgi2|wsgi]
                                  Select ASGI3, ASGI2, or WSGI as the
                                  application interface.  [default: auto]
  --env-file PATH                 Environment configuration file.
  --log-config PATH               Logging configuration file. Supported
                                  formats: .ini, .json, .yaml.
  --log-level [critical|error|warning|info|debug|trace]
                                  Log level. [default: info]
  --access-log / --no-access-log  Enable/Disable access log.
  --use-colors / --no-use-colors  Enable/Disable colorized logging.
  --proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.
  --forwarded-allow-ips TEXT      Comma seperated list of IPs to trust with
                                  proxy headers. Defaults to the
                                  $FORWARDED_ALLOW_IPS environment variable if
                                  available, or '127.0.0.1'.
  --root-path TEXT                Set the ASGI 'root_path' for applications
                                  submounted below a given URL path.
  --limit-concurrency INTEGER     Maximum number of concurrent connections or
                                  tasks to allow, before issuing HTTP 503
                                  responses.
  --backlog INTEGER               Maximum number of connections to hold in
                                  backlog
  --limit-max-requests INTEGER    Maximum number of requests to service before
                                  terminating the process.
  --timeout-keep-alive INTEGER    Close Keep-Alive connections if no new data
                                  is received within this timeout.  [default:
                                  5]
  --ssl-keyfile TEXT              SSL key file
  --ssl-certfile TEXT             SSL certificate file
  --ssl-keyfile-password TEXT     SSL keyfile password
  --ssl-version INTEGER           SSL version to use (see stdlib ssl module's)
                                  [default: 2]
  --ssl-cert-reqs INTEGER         Whether client certificate is required (see
                                  stdlib ssl module's)  [default: 0]
  --ssl-ca-certs TEXT             CA certificates file
  --ssl-ciphers TEXT              Ciphers to use (see stdlib ssl module's)
                                  [default: TLSv1]
  --header TEXT                   Specify custom default HTTP response headers
                                  as a Name:Value pair
  --version                       Display the uvicorn version and exit.
  --app-dir TEXT                  Look for APP in the specified directory, by
                                  adding this to the PYTHONPATH. Defaults to
                                  the current working directory.  [default: .]
  --factory                       Treat APP as an application factory, i.e. a
                                  () -> <ASGI app> callable.  [default: False]
  --help                          Show this message and exit.

生產(chǎn)環(huán)境

  • 安裝 進(jìn)程管理器gunicorn
pip install gunicorn
pip install uvloop
pip install httptools

查看使用的命令

gunicorn -h 
  • 啟動方式

Gunicorn 是成熟的,功能齊全的服務(wù)器,Uvicorn 內(nèi)部包含有 Guicorn 的 workers 類,允許你運(yùn)行 ASGI 應(yīng)用程序,這些 workers 繼承了所有 Uvicorn 高性能的特點(diǎn)。

使用 Guicorn 來進(jìn)行進(jìn)程管理,我們可以動態(tài)增加或減少進(jìn)程數(shù)量,平滑地重啟工作進(jìn)程,或者升級服務(wù)器而無需停機(jī)。

在生產(chǎn)環(huán)境中,Guicorn 大概是最簡單的方式來管理 Uvicorn 了,生產(chǎn)環(huán)境部署我們推薦使用 Guicorn 和 Uvicorn 的 worker 類

gunicorn main:app -b 0.0.0.0:8899 -w 4 -k uvicorn.workers.UvicornWorker --daemon 

獲取Gunicorn進(jìn)程樹

pstree -ap|grep gunicorn

重啟Gunicorn任務(wù)

kill -HUP 30080

gunicorn的參數(shù)詳解

-c CONFIG    : CONFIG,配置文件的路徑,通過配置文件啟動;生產(chǎn)環(huán)境使用;

-b ADDRESS   : ADDRESS,ip加端口,綁定運(yùn)行的主機(jī);

-w INT, --workers INT:用于處理工作進(jìn)程的數(shù)量,為正整數(shù),默認(rèn)為1;

-k STRTING, --worker-class STRTING:要使用的工作模式,默認(rèn)為sync異步,可以下載eventlet和gevent并指定

--threads INT:處理請求的工作線程數(shù),使用指定數(shù)量的線程運(yùn)行每個worker。為正整數(shù),默認(rèn)為1。

--worker-connections INT:最大客戶端并發(fā)數(shù)量,默認(rèn)情況下這個值為1000。

--backlog int:未連接的最大數(shù)量,即等待服務(wù)的客戶的數(shù)量。默認(rèn)2048個,一般不修改;

-p FILE, --pid FILE:設(shè)置pid文件的文件名,如果不設(shè)置將不會創(chuàng)建pid文件


--access-logfile FILE   :  要寫入的訪問日志目錄

--access-logformat STRING:要寫入的訪問日志格式

--error-logfile FILE, --log-file FILE  :  要寫入錯誤日志的文件目錄。

--log-level LEVEL   :   錯誤日志輸出等級。


--limit-request-line INT   :  HTTP請求頭的行數(shù)的最大大小,此參數(shù)用于限制HTTP請求行的允許大小,默認(rèn)情況下,這個值為4094。值是0~8190的數(shù)字。

--limit-request-fields INT   :  限制HTTP請求中請求頭字段的數(shù)量。此字段用于限制請求頭字段的數(shù)量以防止DDOS攻擊,默認(rèn)情況下,這個值為100,這個值不能超過32768

--limit-request-field-size INT  :  限制HTTP請求中請求頭的大小,默認(rèn)情況下這個值為8190字節(jié)。值是一個整數(shù)或者0,當(dāng)該值為0時,表示將對請求頭大小不做限制


-t INT, --timeout INT:超過這么多秒后工作將被殺掉,并重新啟動。一般設(shè)定為30秒;

--daemon,-D: 是否以守護(hù)進(jìn)程啟動,默認(rèn)false;

--chdir: 在加載應(yīng)用程序之前切換目錄;

--graceful-timeout INT:默認(rèn)情況下,這個值為30,在超時(從接收到重啟信號開始)之后仍然活著的工作將被強(qiáng)行殺死;一般使用默認(rèn);

--keep-alive INT:在keep-alive連接上等待請求的秒數(shù),默認(rèn)情況下值為2。一般設(shè)定在1~5秒之間。

--reload:默認(rèn)為False。此設(shè)置用于開發(fā),每當(dāng)應(yīng)用程序發(fā)生更改時,都會導(dǎo)致工作重新啟動。

--spew:打印服務(wù)器執(zhí)行過的每一條語句,默認(rèn)False。此選擇為原子性的,即要么全部打印,要么全部不打印;

--check-config   :顯示現(xiàn)在的配置,默認(rèn)值為False,即顯示。

-e ENV, --env ENV: 設(shè)置環(huán)境變量;
  • 以配置文件的方式啟動
    gunicorn.conf
import multiprocessing

# 并行工作進(jìn)程數(shù)(multiprocessing.cpu_count()線程數(shù),官方說可以有:核心數(shù)*2+1個)
workers = multiprocessing.cpu_count() * 2 + 1 
# 指定每個工作者的線程數(shù)
threads = 2
# 監(jiān)聽內(nèi)網(wǎng)端口5000
bind = '127.0.0.1:5000'
# 設(shè)置守護(hù)進(jìn)程,推薦將進(jìn)程交給supervisor管理(以守護(hù)進(jìn)程形式來運(yùn)行Gunicorn進(jìn)程,true其實(shí)就是將這個服務(wù)放到后臺去運(yùn)行,故此處設(shè)置false,交給supervisor開守護(hù)進(jìn)程,因?yàn)閟upervisor不支持后臺進(jìn)程)
daemon = 'false'
# 工作模式協(xié)程
worker_class = 'gevent'
# 設(shè)置最大并發(fā)量
worker_connections = 2000
# 設(shè)置進(jìn)程文件目錄
pidfile = '/var/run/gunicorn.pid'
# 設(shè)置訪問日志和錯誤信息日志路徑
accesslog = '/var/log/gunicorn_acess.log'
errorlog = '/var/log/gunicorn_error.log'
# 日志級別,這個日志級別指的是錯誤日志的級別,而訪問日志的級別無法設(shè)置
loglevel = 'warning'

啟動unicorn

gunicorn -c gunicorn.conf main:app
  • 推薦用supervisor管理gunicorn

用于管理gunicorn,將其當(dāng)作自己的子進(jìn)程啟動;當(dāng)gunicorn由于異常等停止運(yùn)行后,supervisor可以自動重啟gunicorn

supervisor為c/s架構(gòu),supervisord 是服務(wù)端,supervisorctl 是客戶端

supervisord啟動成功后,可以通過supervisorctl客戶端控制進(jìn)程,啟動、停止、重啟

supervisor_gunicorn.ini

[program:supervisor-gunicorn]  
user = root
directory = /root/gunicorn_demo/
command = /usr/local/python3/bin/gunicorn main:app -b 0.0.0.0:8899 -w 4 -k uvicorn.workers.UvicornWorker
autostart = true
startsecs = 10
redirect_stderr = true
stdout_logfile = /var/log/supervisor_gunicorn.log

更詳細(xì)參數(shù)部署可參考 Supervisord安裝和配置

參考文檔:
https://www.uvicorn.org/deployment/#gunicorn
https://www.cnblogs.com/mazhiyong/p/13384785.html
https://www.cnblogs.com/shijingjing07/p/9110619.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容