我正在尝试学习如何将fastapi与tortoise一起使用来制作 sqlite 数据库。所以我的计划是向 api 发送一个 url,服务器应该对 url 发出 GET 请求,然后发回 id、url、响应(代码)和日期(日期时间),并将其保存在 sqlite 数据库中。我已经编写了代码,所以我可以将所有参数作为 json 传递: 示例:
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\"}"
编码:
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
)
但是我怎样才能让 api 只需要 url 并让服务器发出请求并将其他数据传递给 api?