如何在apache2上运行FastAPI?

问题描述 投票:0回答:3

我已经使用 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 上,这是我在我的国家唯一能接触到的东西。我正在使用 python3.8.9 和 fastapi 版本 0.65.2 和 apache/2.4.29,但我一生都无法让它工作。我已经编写了一个 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.x apache2 gunicorn fastapi asgi
3个回答
16
投票

以防万一其他人在这里偶然发现,这就是我所做的,这就是它对我的作用。 这是因为我在网上找不到太多关于这方面的信息 使用 apache2 在 linux(特别是 ubuntu 18.04.4)上部署 fastapi 没有其他东西。当我不说其他东西时,我指的是 docker、caddy 或 不管怎样。

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

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

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


0
投票

WSGI 服务器与 FastAPI 不兼容,FastAPI 仅在 ASGI 服务器中运行,gunicorn 和所有其他 WSGI 服务器只是与 ASGI 工作人员深入实现 PEP 标准,它们仍然与工作人员一起作为 ASGI 工作。


0
投票

应该可以使用 ASGIMiddleware 将 ASGI 应用程序转换为 WSGI 应用程序,例如与 a2wsgi.

请参阅示例https://github.com/fnep/example_fastapi_behind_apache_using_wsgi

© www.soinside.com 2019 - 2024. All rights reserved.