Forums

How to deploy a FastAPI endpoint using pythonanywhere?

https://stackoverflow.com/questions/75495360/how-to-deploy-a-fastapi-endpoint-using-pythonanywhere

I have been trying to deploy EasyOCR (it's fine if it works on CPU) with FastAPI endpoints such that anyone can use it via https POST request. It runs fine on my local host but when I have been facing challenges in deploying it using pythonanywhere. I added the additional requirements like pip install easyocr, pip install python-multipart==0.0.5.

The following is my code-

import io
import logging
import re

from fastapi import FastAPI, APIRouter, Request, File, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
import easyocr

import PIL
from PIL import Image, ImageOps
import numpy

app = FastAPI()
router = APIRouter()
ocr = easyocr.Reader(["en"])
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ocr")


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.post("/ocr")
async def do_ocr(request: Request, file: UploadFile = File(...)):
    if file is not None:
        imgFile = numpy.array(PIL.Image.open(file.file).convert("RGB"))
        res = ocr.readtext(imgFile)

        # return array of strings
        return [item[1] for item in res]

    return {"error": "missing file"}


app.include_router(router)
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)

I am getting the error in the logs-

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/somyatomar15/main.py", line 82, in <module>
    uvicorn.run(app)
  File "/usr/local/lib/python3.10/site-packages/uvicorn/main.py", line 463, in run
    server.run()
  File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 60, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 633, in run_until_complete
    self.run_forever()
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 600, in run_forever
    self._run_once()
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1896, in _run_once
    handle._run()
  File "/usr/local/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 77, in serve
    await self.startup(sockets=sockets)
  File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 158, in startup
    sys.exit(1)
SystemExit: 1

PythonAnywhere supports currently only WSGI web apps, ASGI is at the top of our priority list, but it's not available yet, so FastAPI would not work. We'll let you know, when it will be ready.

Hi, I just signed up for PythonAnywhere with the intention to use it as a small API server for some internal functions. Not having FastAPI was quite a disappointment. Any update on the timeline for having it available?

It's very very high on our list. No timeline right now though

It's very high on the list for literally ages now. At least a plan/timeline is really needed now.

Unfortunately we can't provide a timeline at this point.

How about now? Is it available?

We are currently doing a private, limited test of FastAPI apps that can be created by API only. If you are interested in helping with testing, email us at support@pythonanywhere.com

I just wasted 2 hours on trying to understand what the hell was going on and why i couldn't run my little endpoint using FastAPI. JUST WRITE SOMEWHERE "FastAPI is not yet supported".

@mvavassori sorry for the confusion! FastAPI is not supported officialy via our UI yet, but it's in ALPHA stage of testing. If you'd like to participate in the testing, please contact us at support@pythonanywhere.com.

How about now ? Is it ready yet ? thanks

No

Is it ready?

Not yet

Is it ready now?

No

Now ready is it?

Not yet

You cannot use .run(app) it will be supported in the Web tab (?) when ready.

That is true, but in this case it wouldn't be a problem. When we run your code as a web app, that part of the code will not be executed if it is inside a if __name__ == "__main__": clause.

Does pythonanywhere support FastAPI now?

Does pythonanywhere support FastAPI now?

We are running a beta test for it; there's a basic UI, and sites work on subdomains of PythonAnywhere. We also have partial support for custom domains -- but they're currently HTTP-only. If you would like to give it a go, drop us a line at support@pythonanywhere.com.

Great to hear asynchronous web framework support is coming! Which async frameworks are going to be supported? I assume FastAPI and Quart (native async version of Flask) should be the top 2 priorities?

Cheers!

Upcoming work should support most if not all asgi web frameworks though FastAPI will be the focus of the first release

is it available now ? FastAPI ?

There is limited support in beta right now -- check out this help page.

is it available now ? FastAPI ?

Take a look at https://help.pythonanywhere.com/pages/ASGICommandLine

value for $DOMAIN_SOCKET empty. Its ok? it won't let me run it :(

What makes you think that it's empty?

I did everything according to the instructions for fastapi: /home/MYUSERNAME/.virtualenvs/my_venv/bin/uvicorn --app-dir /home/MYUSERNAME/my_fastapi --uds $DOMAIN_SOCKET main:app

but got an error: Error: Missing argument 'APP'

if enter $DOMAIN_SOCKET it will be an empty line. I tried to manually write the value into it as in the guide: DOMAIN_SOCKET=/var/sockets/MYUSERNAME.pythonanywhere.com/app.sock

but I get an error that there is no such path

Hey there!

I’ve set up a FastAPI app using the "ASGICommandLine" page instructions, and it’s working well. But after deploying my site, I noticed that the FastAPI endpoint is being redirected from HTTPS to HTTP, which is causing mixed content errors on my site.

Normally, other web apps have a "Force HTTPS" option in their UI, but since ASGI sites on PythonAnywhere don’t have a web UI, I can’t apply this setting.

Could you help me figure out how to fix this and make sure my FastAPI endpoint handles HTTPS correctly?

There is no "Force HTTPS" option for asgi apps yet. It's on the way.

Got it about the "Force HTTPS" option not being available yet. Is there any other way to force HTTPS for ASGI apps in the meantime? Maybe a command or workaround that could help with the mixed content issue?

I'm a bit confused when you say that "the FastAPI endpoint is being redirected from HTTPS to HTTP" -- could you give some more details about that? With our default configuration, you should be able to run on HTTPS or HTTP without being automatically switched from one to the other.

Regarding your specific question -- I think that HTTPSRedirectMiddleware might be what you're looking for.

@THEDAN320 -- it looks like your message got dropped. The DOMAIN_SOCKET variable is only defined in the context of a running ASGI website, not in consoles. If you're getting errors like Error: Missing argument 'APP', it sounds like you're trying to run your FastAPI site in a console. Check the documentation at https://help.pythonanywhere.com/pages/ASGICommandLine again; it tells you how to create a website using a particular command, using the pa website helper script.

I understand. It was my carelessness. Thank you!

No problem, glad to help!

Hello, I have tried to run my site using the pa helper, but it dosen't run. (my_venv) 22:02 ~ $ pa website create --domain MYUSER.pythonanywhere.com --command '/home/MYUSER/.virtualenvs/my_venv/bin/uvicorn main:app --uds $DOMAIN_SOCKET' < All done! Your site is now live at fulexai.pythonanywhere.com. > \ ~<:>>>>>>>>> (my_venv) 22:03 ~ $ pa website get domain name enabled ------------- ---------

but it dosen't run, please help :(

What exactly is the issue? It looks ok to me.

Sorry for hijacking this post. I have been trying to host a flask app to act as an api backend for my nextjs project. While it works when run on local host, i am unable to access the url when the call headers are added. However, the url itself exists. I am sure I am doing something widely wrong, and I appreciate nay insights.

We would need more details, and maybe the url to hit and see.

Hi fjl, thanks for your reply! my url is ' https://thechosenmenace.pythonanywhere.com/ ', and it displays the initial msg "invalid crime type" as nothing is called just yet to the api. What I want to do is access https://thechosenmenace.pythonanywhere.com/api/home?crime=${searchQuery}&group_by=${groupBy}, so I can have the backend do its work and return me some numbers. Unfortunately, I only get a no-url found error.

Hi, i just got it to work. I stupidly left the /api/home which does not make sense when using pythonanywhere. I hope this helps anyone who suffers from the same problem

Glad to hear that you made it!