Passing request.status_code and datetime to sqlite database using fastapi and tortoise

464 views Asked by At

I'm trying to learn how to use fastapi with tortoise to make an sqlite database. So my plan was to send an url to the api and the server should make an GET request against the url and send back the id, url, response(code) and date (datetime) and also save it in the sqlite database. I have made the code so i can pass all parameters as an json: Example:

curl -X POST "http://127.0.0.1:8000/data" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"url\":\"http://somesite.com\",\"response\":\"200\",\"date\":\"2020-12-15 22:53\"}"

The code:

import requests
from tortoise. models import Model
from datetime import datetime
from tortoise.contrib.fastapi import register_tortoise
from tortoise import fields
from fastapi import FastAPI
from tortoise.contrib.pydantic import pydantic_model_creator


app = FastAPI()


class Data(Model):
    id = fields.IntField(pk=True)
    url = fields.CharField(80, unique=False)
    response = fields.CharField(4, unique=False)
    date = fields.CharField(50, unique=False)


Data_pydantic = pydantic_model_creator(Data, name='Datamod')
Data_pydantic_in = pydantic_model_creator(Data, name='Datamodin', exclude_readonly=True)



@app.get('/')
async def index():
    return {'Hi': 'World'}

@app.post('/data')
async def response(data: Data_pydantic_in):
    databbj = await Data.create(**data.dict(exclude_unset=True))
    return await  Data_pydantic.from_tortoise_orm(databbj)

register_tortoise(
    app,
    db_url='sqlite://db.sqlite3',
    modules={'models': ['root']},
    generate_schemas=True,
    add_exception_handlers=True
)

But how can i make the api only require the url and make the server make the request and pass the other data to the api?

0

There are 0 answers