如何在 apache2 上 运行 FastAPI?
How to run FastAPI on apache2?
我已经使用 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>
但无济于事。
我尝试通过屏幕会话 运行ning gunicorn,但我也无法访问它。
我试过 运行 以编程方式对其进行设置,但无济于事:
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
我知道这是一个非常宽泛的提问方式,但我真的很困惑。
如何 运行 在 Apache2 上使用 fastapi 构建 api?
感谢您的帮助。
以防万一其他人在这里偶然发现,这就是我所做的,这就是它对我有用的方式。
这是关于 b/c 网上没有太多我能找到的关于问候的信息
在 linux 上部署 fastapi —— 特别是 ubuntu 18.04.4 —— 使用 apache2
没有其他的东西。当我没有说别的的时候,我的意思是 docker、caddy 或
无论如何。
通常的事情必须事先完成,这些是:
- 创建 api 将使用的数据库
- 安装虚拟环境
- 从 requirements.txt
安装必要的依赖项
- scp 或从 github 克隆 api
的生产代码
- 将api的生产代码放在/var/www/
- 你可以使用 gunicorn 作为实际的服务器,而 apache 是一个可以将你连接到它的反向代理(记住 cd 到包含模块 1st 的实际目录也可以使用屏幕)
- 通过 "a2enmod proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html" 将 apache2 设置为反向代理
- 实际输入服务器 conf 文件并启用它(示例在底部提供)
- 总是做好备份
正在运行的示例 apache 配置文件:
<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"
编辑:我根本没有在此处放置任何安全机制
WSGI 服务器与 FastAPI 不兼容,FastAPI 仅在 ASGI 服务器中运行,gunicorn 和所有其他 WSGI 服务器只是与 ASGI worker 深度实施 PEP 标准,它们仍然作为 ASGI 与 worker 一起工作。
我已经使用 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>
但无济于事。
我尝试通过屏幕会话 运行ning gunicorn,但我也无法访问它。
我试过 运行 以编程方式对其进行设置,但无济于事:
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
我知道这是一个非常宽泛的提问方式,但我真的很困惑。
如何 运行 在 Apache2 上使用 fastapi 构建 api?
感谢您的帮助。
以防万一其他人在这里偶然发现,这就是我所做的,这就是它对我有用的方式。 这是关于 b/c 网上没有太多我能找到的关于问候的信息 在 linux 上部署 fastapi —— 特别是 ubuntu 18.04.4 —— 使用 apache2 没有其他的东西。当我没有说别的的时候,我的意思是 docker、caddy 或 无论如何。
通常的事情必须事先完成,这些是:
- 创建 api 将使用的数据库
- 安装虚拟环境
- 从 requirements.txt 安装必要的依赖项
- scp 或从 github 克隆 api 的生产代码
- 将api的生产代码放在/var/www/
- 你可以使用 gunicorn 作为实际的服务器,而 apache 是一个可以将你连接到它的反向代理(记住 cd 到包含模块 1st 的实际目录也可以使用屏幕)
- 通过 "a2enmod proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html" 将 apache2 设置为反向代理
- 实际输入服务器 conf 文件并启用它(示例在底部提供)
- 总是做好备份
正在运行的示例 apache 配置文件:
<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"
编辑:我根本没有在此处放置任何安全机制
WSGI 服务器与 FastAPI 不兼容,FastAPI 仅在 ASGI 服务器中运行,gunicorn 和所有其他 WSGI 服务器只是与 ASGI worker 深度实施 PEP 标准,它们仍然作为 ASGI 与 worker 一起工作。