Created
January 28, 2021 13:05
-
-
Save Refffy/6ed448491115cb28e8708e96059c2e45 to your computer and use it in GitHub Desktop.
This file contains 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 fastapi import APIRouter, FastAPI, File, UploadFile | |
import databases | |
from schema import PostSchema | |
from posts import Post | |
import shutil | |
PSQL_URL = "postgresql://usr_name:password@localhost:5432/db_name" | |
db = databases.Database(PSQL_URL) | |
app = FastAPI() | |
router = APIRouter( | |
responses={404: {"description": "Not found"}} | |
) | |
@ router.post('/api/shares/upload', response_model=PostSchema) | |
async def upload_post(post: PostSchema, file: UploadFile = File(...)): | |
query = '''INSERT INTO Post(usr_name, title, tags, created_at) | |
VALUES (:usr_name, :title, :tags, :created_at)''' | |
with open("images/"+file.filename, "wb") as img: | |
shutil.copyfileobj(file.file, img) | |
url = str("images/"+file.filename) | |
values = { | |
"usr_name": post.usr_name, | |
"title": post.title, | |
"tags": post.tags, | |
"created_at": post.created_at | |
} | |
_id = await db.execute(query, values) | |
return {**post.dict(), "id": _id, "url": url} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment