Here's a self-contained, minimal, reproducible, example with my use case:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
/.{"Hello": "World"}.{"Hello": "Sara"}.To know the FastAPI version use:
python -c "import fastapi; print(fastapi.__version__)"
To know the Python version use:
python --version
Can you share your code snippet please. I can't say what's wrong here without example :)
from typing import List
from fastapi import Depends, FastAPI, Request, HTTPException, Form
from sqlalchemy.orm import Session
import os
import models
from database import SessionLocal, engine
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
basepath = 'static/'
urls=[]
for entry in os.listdir(basepath):
urls.append(entry)
class Senddata(BaseModel):
is_sarcastic: bool
cnt:int
clip_url:str
is_audio_rgt:bool
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def check_url(db: Session, url: str):
print(db.query(models.Sarcasm).filter(models.Sarcasm.clip_url == url).first())
return db.query(models.Sarcasm).filter(models.Sarcasm.clip_url == url).first()
@app.post("/postdata/", response_model=Senddata)
def postdata(send:Senddata, db: Session = Depends(get_db)):
data = models.Sarcasm()
for i in send:
url=check_url(db, i)
if url:
continue
else:
data.clip_url = url
db.add(data)
db.commit()
return {"code": "sucess"}
postdata(urls)
Error is this.
File ".main.py", line 53, in
postdata(urls)
File ".main.py", line 43, in postdata
url=check_url(db, i)
File ".main.py", line 37, in check_url
print(db.query(models.Sarcasm).filter(models.Sarcasm.clip_url == url).first())
AttributeError: 'Depends' object has no attribute 'query'
Can you share your code snippet please. I can't say what's wrong here without example :)
you can check now :)
Your mistake is calling postdata directly at line 53. FastAPI handles dependencies when you make http request. So you should launch you app uvicorn main:app and then make request to postdata. If you want to test API route from code, you should use TestClient
Is the problem resolved @ganeshmastud? If it is, do you mind closing the issue?
Thanks for the help here @SirTelemak ! :clap: :bow:
If that solves the original problem, then you can close this issue @ganeshmastud :heavy_check_mark:
Most helpful comment
Can you share your code snippet please. I can't say what's wrong here without example :)