首页 > 解决方案 > 如何在 apache2 上运行 FastAPI?

问题描述

我已经使用 fastapi 开发了一个 api,它将充当接收短信请求并调用短信 api 发送所述短信的包装器,现在我已准备好部署它。这是代码:

import logging

import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.trustedhost import TrustedHostMiddleware

import verifier

logging.basicConfig(
    format='%(asctime)s - %(funcName)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

# get logger
logger = logging.getLogger(__name__)


bot_verifier = None


class DataForBot(BaseModel):
    number: str
    msg_txt: str


def get_application():
    app = FastAPI(title='bot_wrapper', version="1.0.0")

    return app


app = get_application()


@app.on_event("startup")
async def startup_event():
    global bot_verifier
    try:
        bot_verifier = await verifier.Verifier.create()
    except Exception as e:
        logger.error(f"exception occured during bot creation -- {e}", exc_info=True)


@app.post('/telegram_sender/')
async def send_telegram_msg(data_for_bot: DataForBot):
    global bot_verifier
    if not bot_verifier:
        bot_verifier = await verifier.Verifier.create()
    else:
        dict_data = data_for_bot.dict()
        try:
            if await bot_verifier.send_via_telegram(dict_data):
                return {'status': "success", 'data': data_for_bot}
            else:
                raise HTTPException(status_code=404, detail="unable to send via telegram, perhaps user has not started the bot")
        except Exception as e:
            logger.error(f"{e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Something went wrong, please contact server admin")

我想在 apache b/c 上部署它,这是我在我的国家唯一可以接触到的东西。我正在使用带有 fastapi 版本 0.65.2 和 apache/2.4.29 的 python3.8.9,但对于我的生活,我无法让它工作。我编写了一个 apache conf 文件并启用它:

<VirtualHost *:80>
    ServerName gargarsa.sms.local
    ServerAdmin webmaster@localhost
    ServerAlias gargarsa.sms.local
    
    DocumentRoot /var/www/verify_bot_api/
    ServerAlias gargarsa.sms.local

    <Directory /var/www/verify_bot_api/src/app/>
        Order deny,allow
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/gargarsa.sms.local-error.log
    LogLevel debug
    CustomLog ${APACHE_LOG_DIR}/gargarsa.sms.local-access.log combined
</VirtualHost>

但无济于事。

我尝试通过屏幕会话运行 gunicorn,但我也无法访问它。

我尝试以编程方式运行它,但无济于事:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

我知道这是一个非常广泛的提问方式,但我真的很难过。

如何在 Apache2 上运行使用 fastapi 构建的 api?

谢谢您的帮助。

标签: python-3.xapache2gunicornfastapiasgi

解决方案


以防其他人在这里偶然发现,这就是我所做的,这就是它对我的工作方式。这是关于 b/c 的,网上没有很多信息——我可以找到——关于在 linux 上部署 fastapi——特别是 ubuntu 18.04.4——使用 apache2 而没有其他东西。当我说没有其他东西时,我的意思是码头工人、球童或其他任何东西。

通常的事情必须事先完成,这些是:

  1. 创建 api 将使用的数据库
  2. 安装虚拟环境
  3. 从 requirements.txt 安装必要的依赖项
  4. scp 或从 github 克隆 api 的生产代码
  5. 将api的生产代码放在/var/www/
  6. 您可以使用 gunicorn 作为实际服务器,而 apache 是可以将您连接到它的反向代理(请记住 cd 到包含模块 1st 的实际目录也可以使用 screen )
  7. 通过“a2enmod proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html”将 apache2 设置为反向代理
  8. 实际键入服务器 conf 文件并启用它(底部提供的示例)
  9. 始终进行备份

参考: https ://www.vioan.eu/blog/2016/10/10/deploy-your-flask-python-app-on-ubuntu-with-apache-gunicorn-and-systemd/

运行示例 apache conf 文件:

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerName server-name
    ServerAdmin webmaster@localhost
    ServerAlias server-alias
    
    #DocumentRoot /document/root/

    <Proxy *>
        AuthType none
        AuthBasicAuthoritative Off
        SetEnv proxy-chain-auth On
        Order allow,deny
        Allow from all
    </Proxy>

    ProxyPass / http://127.0.0.1:port/
    ProxyPassReverse / http://127.0.0.1:port/
    #ProxyPass /api http://127.0.0.1:port/api
    #ProxyPassReverse /api http://127.0.0.1:port/api

    <Directory /document/root/>
        Order deny,allow
        Allow from all
    </Directory>

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/server-error.log
    LogLevel debug
    CustomLog ${APACHE_LOG_DIR}/server-access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

要运行实际的 api:

gunicorn api:app -w 1 -k uvicorn.workers.UvicornWorker -b "127.0.0.1:port"

编辑:我在这里根本没有放置任何安全机制


推荐阅读