I can successfully add new student data
@router.post("/",response_description="Student data added into the database")
async def add_student_data(student: StudentSchema= Depends(),file: UploadFile=File(None)):
I have made upload file as optional.
class StudentSchema(BaseModel):
fullname:str = Field(...)
email: EmailStr = Field(...)
course_of_study: str = Field(...)
year: int = Field(...,gt=0,lt=9)
gpa: float = Field(..., le= 4.0)
image: Optional[str]
For crud operation, I want to upload file if not added previously, replace new one if added or want to left blank"null"
class UpdateStudentModel(BaseModel):
fullname: Optional[str]
email: Optional[EmailStr]
course_of_study : Optional[str]
year : Optional[int]
gpa: Optional[float]
image: Optional[str]
In route
@router.put("/{id}")
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: UploadFile=File(None)):
print(file)
Everytime it prompts error when i left blank (for file upload) during update
Did not find CR at end of boundary (40)
In swagger
{
"detail": "There was an error parsing the body"
}
@router.put("/{id}")
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file: Optional[UploadFile]=File(None)):
print(file)
req={k:v for k ,v in req.dict().items() if v is not None}
@ekundayo-ab Have you looked at https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app for how they do it there? The api routes have just logic to deal with inputs, and some permissions. And then the meat of the logic is separate in crud. I like to have all the routes defined with the definition of the endpoint together, and then logic elsewhere. So you can end up with something like this:
@app.put("/items/{item_id}", response_model=ItemResponse)
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
return crud.item.update_item(id, item)
Its still just the routes, but it tells you input / output. So its a bit more friendly when reading the code.
def test_create_area(client, fake_login_superuser):
response = client.post(
"/api/v1/areas",
data={
"descricao": "Agronomia"
}
)
assert response.status_code == 200
{'detail': [{'loc': ['body', 0], 'msg': 'Expecting value: line 1 column 1 (char 0)', 'type': 'value_error.jsondecode', 'ctx': {'msg': 'Expecting value', 'doc': 'descricao=Agronomia', 'pos': 0, 'lineno': 1, 'colno': 1}}]}
class AreaCreate(BaseModel):
descricao: str
class Config:
orm_mode = True
@r.post("/areas", response_model=Area, response_model_exclude_none=True)
async def area_create(
request: Request,
area: AreaCreate,
db=Depends(get_db),
):
"""
Create a new area
"""
return await create_area(db, area)
from routers import router
app = FastAPI()
app.include_router(router)
# Handler for api calls
@app.middleware("http")
async def api_process(request: Request, call_next):
try:
if path in endpoints_list:
# ... validation logics here ...
response = await call_next(request) # calls the endpoints with corresponding path
# ... process the response ...
except Exception as ex:
# ... process exception ...
handler = Mangum(app)
@router.get("/index")
def sample_endpoint(request: Request):
try:
query_params= request.query_params
body = request.body
# ....
return Response(
status_code = 200,
content=json.dumps(response_body)
)
except Exception as ex:
# ... process exception ...
Request
object and extract query_params
and body
data myself, I would like to use more explicit parameters such as item_id: int
, customer_name: str
, and so on for each endpoints. Since I am using middleware decorator for the lambda function to forward the request to path provided, I am not sure how to do it other than passing in the whole Request object from lambda function. Would this be possible?
=== === ===
Hello Here!
a bit of topic question, but I still try it here:
in setup.py
i neeed the keras-contrib@https://github.com/keras-team/keras-contrib.git
as REQUIRES_INSTALL
package.
Everyting works fine when installing with pip -r ...
, BUT when tha package is built as wheel, then
ERROR: Could not find a version that satisfies the requirement keras-contrib (from superduperpack==0.3.5) (from versions: none)
ERROR: No matching distribution found for keras-contrib (from superduperpack==0.3.5)
Help appreciated!
@eseglem thank you for replying to me
this is the error
?[33mWARNING?[0m: Detected file change in 'main.py'. Reloading...
email-validator not installed, email fields will be treated as str.
To install, run: pip install email-validator
Process SpawnProcess-5:
Traceback (most recent call last):
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\multiprocessing\process.py", line 108, in run
self._target(self._args, *self._kwargs)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\subprocess.py", line 61, in subprocess_started
target(sockets=sockets)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\main.py", line 407, in run
loop.run_until_complete(self.serve(sockets=sockets))
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\main.py", line 414, in serve
config.load()
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\config.py", line 300, in load
self.loaded_app = import_from_string(self.app)
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\importer.py", line 23, in import_from_string
raise exc from None
File "C:\Users\rquitain\AppData\Roaming\Python\Python38\site-packages\uvicorn\importer.py", line 20, in import_from_string
module = importlib.import_module(module_str)
File "c:\users\rquitain\appdata\local\programs\python\python38\lib\importlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File ".\main.py", line 2, in <module>
from fastapi.responses import JSONResponses
ran pip list and found these versions
(ConvergedApp) C:\Users\rquitain\Documents\GitHub\fbprophet-forecasting-api>pip list
uvicorn 0.12.1
fastapi 0.61.1
also yes im using the environment i made but installed there firstly fast api and ran pip list on that environment
Can anyone help me deploy https://github.com/long2ice/fastapi-admin frontend and backend on a single heroku app.
Yarn build is creating the files inside /dist but my fastapi is trying to access "GET /js/app.2e733260.js HTTP/1.1" 404 and getting 404
I did app.mount("/dist", StaticFiles(directory="dist"))