I've developed an api using fastapi that will act as a wrapper that receives sms requests and call the sms api to send said sms and now I'm ready to deploy it. This is the code:
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")
I want to deploy it on apache b/c it's the only thing I can get my hand onto in my country. I'm using python3.8.9 with fastapi version 0.65.2 and apache/2.4.29, but for the life of me I can't get it to work. I've written an apache conf file and enabled that as such:
<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>
but no avail.
I tried running gunicorn via a screen session but I couldn't access it either.
I tried running it programmatically as such but no avail:
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
I understand this is a very broad way to ask, but I'm truly stumped.
How do I run an api built using fastapi on Apache2?
Thank you for your assistance.