Last active
June 28, 2023 18:24
-
-
Save wshayes/f0ae5cfa65c87dc2e9092d6c634d2912 to your computer and use it in GitHub Desktop.
[FastAPI Single File Demo] Example fastapi single file testable example #fastapi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.7 | |
import logging | |
import uvicorn | |
from fastapi import FastAPI | |
from starlette.responses import RedirectResponse | |
from starlette.testclient import TestClient | |
log = logging.getLogger(__name__) | |
log.setLevel(logging.DEBUG) | |
app = FastAPI() | |
@app.get("/") | |
def read_main(): | |
return {"message": "Hello World from main app"} | |
@app.get("/test/{check:path}") | |
def test_slash(check: str): | |
"""Test if forward slash can be captured | |
https://fastapi.tiangolo.com/tutorial/path-params/#path-convertor | |
""" | |
return {"message": check} | |
subapi = FastAPI(openapi_prefix="/subapi") | |
@subapi.get("/sub") | |
async def read_sub(): | |
return {"message": "Hello World from sub API"} | |
@subapi.get("/redirect") | |
async def redirect(): | |
url = app.url_path_for("redirected") | |
response = RedirectResponse(url=url) | |
return response | |
@subapi.get("/redirected") | |
async def redirected(): | |
log.debug("REDIRECTED") | |
return {"message": "you've been redirected"} | |
app.mount("/subapi", subapi) | |
client = TestClient(app) | |
def test_redirect_subapi(): | |
url = app.url_path_for("redirect") | |
response = client.get(url) | |
assert response.json() == {"message": "you've been redirected"} | |
if __name__ == "__main__": | |
uvicorn.run("fastapi_test:app", host="127.0.0.1", port=5000, log_level="info") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From: https://github.com/tiangolo/fastapi/issues/23#issuecomment-597631374 | |
# The following works with the pycharm debugger with reload running in a docker-compose remote interpreter | |
from fastapi import FastAPI | |
import uvicorn | |
app = FastAPI() | |
@app.get("/") | |
def root(): | |
a = "a" | |
b = "b" + a | |
return {"hello world": b} | |
if __name__ == '__main__': | |
uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True) | |
# Notice the it's "main:app" and not app otherwise you get an error: | |
# WARNING: You must pass the application as an import string to enable 'reload' or 'workers'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment