Jensuchan / sqlite_exercise

0 stars 0 forks source link

AttributeError: 'generator' object has no attribute 'add' #2

Open Dev93junho opened 6 months ago

Dev93junho commented 6 months ago

The original code occured AttributeError: 'generator' object has no attribute 'add' from "/image"

@app.post("/image")
async def upload_image(file: UploadFile):
    UPLOAD_DIR = "./image"
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)

    content = await file.read()
    filename = file.filename
    filesize = len(content)

    random_uuid = str(uuid.uuid4())
    print(random_uuid)
    save_filename = random_uuid+"_"+filename

    with open(os.path.join(UPLOAD_DIR, save_filename), "wb") as fp:
        fp.write(content)

    image = models.Image(uuid=random_uuid, save_dir=UPLOAD_DIR, img_category=None, img_name=filename, img_size=filesize)

    DATABASE_URL = "sqlite:///image.db"
    metadata = database.MetaData()

    #DB
    # engine = create_engine(DATABASE_URL, echo=True)
    # SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    # Base.metadata.create_all(bind=engine)
    # db = SessionLocal()
    # db = get_db()
    # db.add(image)
    # db.commit()
    # db.close()

    # if not os.path.exists(UPLOAD_DIR):
    #     os.makedirs(UPLOAD_DIR)

    # content = await file.read()
    # with open(os.path.join(UPLOAD_DIR, save_filename), "wb") as fp:
    #     fp.write(content)

    #image = Image(uuid= random_uuid, img_category=None, save_dir=folder_name, img_name=filename, img_size=file.size)

    # with open(os.path.join(target_dir, filename), "wb") as fp:
    #     fp.write(content)

    response = RedirectResponse(url=f"/success?save_filename={save_filename}", status_code=303)

    return response
Dev93junho commented 6 months ago

follow this code

@app.post("/image")
async def upload_image(file: UploadFile, db: Session = Depends(database.get_db)):
    UPLOAD_DIR = "./image"
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)

    content = await file.read()
    filename = file.filename
    filesize = len(content)

    random_uuid = str(uuid.uuid4())
    print(random_uuid)
    save_filename = random_uuid+"_"+filename

    with open(os.path.join(UPLOAD_DIR, save_filename), "wb") as fp:
        fp.write(content)

    image = models.Image(uuid=random_uuid, save_dir=UPLOAD_DIR, img_category=None, img_name=filename, img_size=filesize)

    # DATABASE

    db.add(image)
    db.commit()

    #

    response = RedirectResponse(url=f"/success?save_filename={save_filename}", status_code=303)

    return response