fastapi-course's People
Forkers
alomdaelmasry pearcee mauropdev maxcodextc riccardosic anarcypher hieufromwaterloo sahilt20 tizbid wadeea89 scoinhawk mrcee95 satishkumarboddu theonomimc maenthenk paglipay iglee2000jp manrodri develop-python paytam yasir2000 tafeni ck-h mmlynarik vinodkandula shaikhzhas tareqmahin adi0687 okpoudel arjunadilan rohalpraveen chatchai-komrangded zbraiterman anbarasanv nicktids oehs7 jubrandt dennisobel tomaszszyborski gamontero rubensmachado-dev prendkola ericarthuang alok29011999 sruthikomravolu aishanii gitavk doebialale mulaievarh neyoobaba csk544 rodrigonca amitsdalal oyedemilade troncorp inalireza mirai-plus billmanai thiru-pathi stephentmk isingh14 adarsh666 niraj876 mariocukovic martinrovang qoolfly kwsweeney jdeemer hwlberd andromarket abu-sufyan1 sunnag7 jessiealopay ioanszilagyi kirkdort44 kevinamiri avinashhsinghh princerajeev21 data-science-ai-open-source tuxnotes abhishek-yadav884 tons613 vkajith techristo sam2500 vdnew hrrymasonleg5 muralimopidevi yusufmohammad mkabil123 pyturn arpitsharma9 arvindcletus bs25255 bicyclemark abubakarr99 sanvu88 syerabati s-vision yakagi17fastapi-course's Issues
token data data type issue
getting a error when doing a post request for creating a post when trying to verify post, unable to set token data
self.pydantic_validator.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for TokenData
using TIMESTAMP in the created_at column fails with sqlite database
Congratulations on a job well done; that is an incredible series.
I recently run into an issue when using the TIMESTAMP with SQLite database.
Here's a brief of what's up.
With this ;
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()')
An exception is raised.
def do_execute(self, cursor, statement, parameters, context=None):
> cursor.execute(statement, parameters)
E sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "(": syntax error
E [SQL:
E CREATE TABLE posts (
E id INTEGER NOT NULL,
E title VARCHAR NOT NULL,
E content VARCHAR NOT NULL,
E published BOOLEAN DEFAULT 'TRUE' NOT NULL,
E created_at TIMESTAMP DEFAULT now() NOT NULL,
E PRIMARY KEY (id)
E )
E
E ]
E (Background on this error at: https://sqlalche.me/e/14/e3q8)
However, modifying the column to use DateTime works for both;
created_at = Column(DateTime(timezone=True), default=func.now())
Is there any chance that a fix for this will be available?
current_user.id has no id attribute
new_post = models.Post(owner_id=current_user.id, ** post.
Why I always can't get attribute "id" in current_user.id.
I spend many time to find arror , can someboy tell me why.
thanks you.
307 Response code
fastapi-course/tests/test_users.py
Line 27 in d8059d9
I had to modify "/login" to "/login/" to get a 200 Http Response, otherwise you will be redirected and the assertion will raise an error.
res = client.post("/login", data={"username": test_user['email'], "password": test_user['password']})
> assert res.status_code == 200
E assert 307 == 200
E +307
E -200
tests\test_users.py:92: AssertionError
================================================================== short test summary info ==================================================================
FAILED tests/test_users.py::test_login - assert 307 == 200```
OAuth2PasswordRequestForm error in the code
OAuth2PasswordRequestForm gives an error of 422: uprocessable entity, I don't know what this is, but I am sure, it's a problem with the implementation.
How docker postgres creates tables
We have alembic setup with multiple revisions and we create table using 'alembic upgrade head' when we deploy manually in ubuntu VM.
But when you were showing how to deploy using docker, I see we never use alembic command to create tables. But still postgres works as expected. How is that?
Unable to stop server
When I am running server using following command i am unable to stop it using ctrl + c
uvicorn backend.main:app --port 8001 --reload
i have to kill terminal to stop the server
How to solve this ?
Alternatives to Heroku Free Tier
If you found a new service which provides a viable alternative to Heroku Free Tier, feel free to share it here.
My create_at with sqlalqemy in schema is creating issue
Type of current_user in routers/post.py should be models.User
First of all, thanks for your great YouTube FastAPI lessons!!!
(https://www.youtube.com/watch?v=0sOvCWFmrtA)
This course enables me writing cool backend code of my blogsite.
I found a type errors in this code.
https://github.com/Sanjeev-Thiyagarajan/fastapi-course/blob/main/app/routers/post.py
routers/post.py
on line 19, 41, 57, 73, and 98.
A variable current_user
's type should be models.User. (but it was declared as integer type)
Following error found while build this project on latest python
Collecting orjson==3.6.1
Using cached orjson-3.6.1.tar.gz (746 kB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'error'
error: subprocess-exited-with-error
× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
Checking for Rust toolchain....
Cargo, the Rust package manager, is not installed or is not on PATH.
This package requires Rust and Cargo to compile extensions. Install it through
the system's package manager or via https://rustup.rs/
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
`pip install -r requirements.txt` fails on mac due to psycopg2
Hi, nice project! However, out of the box, users may find compatibility issues due to psycopg2
, which is notoriously a bit finnicky. Initially, when I tried to pip install psycopg2
, I got some errors like
pg_config is required to build psycopg2 from source. Please add the directory
containing pg_config to the $PATH or specify the full executable path with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
If you prefer to avoid building psycopg2 from source, please install the PyPI
'psycopg2-binary' package instead.
However, I had no issue with psycopg2-binary
. You may want to make a note of it in the readme and/or make psycopg2-binary
the default. You may mention this in the videos - I admit I haven't watched them yet! But I know a lot of folks just like to jump straight into the codebase.
Error AttributeError: 'User' object has no attribute 'username' occurs in get_current_user
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(database.get_db)):
credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"})
token = verify_access_token(token, credentials_exception)
user = db.query(models.User).filter(models.User.id == token.id).first()
if user is None:
raise credentials_exception
return user
I tried to debug this error for hours but i couldnt.
i tried changing the last part for the use to use the db driver instead of SQLAlchemy
cursor.execute("""SELECT * FROM users WHERE id = %s;""", (token.id,))
user = cursor.fetchone()
It worked .I dont understand how .Somebody help me understand this .Is a problem with SQLAlchemy
or its my code .I really tried to retrace my steps but could find any problem
error occurs about this point of the video
Pydantic validation failing for all posts endpoint
When I try to validate the get all posts endpoint with: response_model=List[schemas.PostOut]
I get an error "unable to seralize unknown type" I'm using Pydantic 2.2.1
ModuleNotFoundError: No module named '_tkinter'
2022-01-16T14:39:40.120585+00:00 app[web.1]: File "", line 1007, in _find_and_load
2022-01-16T14:39:40.120599+00:00 app[web.1]: File "", line 986, in _find_and_load_unlocked
2022-01-16T14:39:40.120613+00:00 app[web.1]: File "", line 680, in _load_unlocked
2022-01-16T14:39:40.120627+00:00 app[web.1]: File "", line 850, in exec_module
2022-01-16T14:39:40.120657+00:00 app[web.1]: File "", line 228, in _call_with_frames_removed
2022-01-16T14:39:40.120671+00:00 app[web.1]: from .routers import post, users, auth, vote
2022-01-16T14:39:40.120685+00:00 app[web.1]: File "/app/./app/routers/post.py", line 4, in
2022-01-16T14:39:40.120686+00:00 app[web.1]: from .. import schemas, models, oauth2
2022-01-16T14:39:40.120700+00:00 app[web.1]: from turtle import st
2022-01-16T14:39:40.120714+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/turtle.py", line 107, in
2022-01-16T14:39:40.120714+00:00 app[web.1]: import tkinter as TK
2022-01-16T14:39:40.120744+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/tkinter/init.py", line 37, in
2022-01-16T14:39:40.120744+00:00 app[web.1]: import _tkinter # If this fails your Python may not be configured for Tk
2022-01-16T14:39:40.120770+00:00 app[web.1]: ModuleNotFoundError: No module named '_tkinter'
2022-01-16T14:39:42.317479+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-01-16T14:39:42.480091+00:00 heroku[web.1]: Process exited with status 137
I'm getting this error when i'm trying to deploy application in heroku.
I'v tried adding tkinter into requirements.txt and redeploy but it doesn't work.
Import issue
While issue python 3.10. Get an issue of import.
"from ..database import Base" - attempted relative import beyond top-level package
Also router get an issue.
Error in accessing "/docs" of Fastapi | FastAPI Prefix & Tags: Part #60 Python API Course
Everything was working fine but when I tried to access ("http://127.0.0.1:8000/docs",) it is giving me this error
Issue in video: https://www.youtube.com/watch?v=4zwUOOrcihk&list=PL8VzFQ8k4U1L5QpSapVEzoSfob-4CR8zM&index=62
INFO: 127.0.0.1:65341 - "GET /docs HTTP/1.1" 200 OK
INFO: 127.0.0.1:65341 - "GET /openapi.json HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\KHUSHI\Desktop\Projects\Fast API\venv\Lib\site-packages\fastapi\encoders.py", line 152, in jsonable_encoder
data = dict(obj)
^^^^^^^^^
TypeError: 'ModelField' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\KHUSHI\Desktop\Projects\Fast API\venv\Lib\site-packages\fastapi\encoders.py", line 157, in jsonable_encoder
data = vars(obj)
^^^^^^^^^
TypeError: vars() argument must have _dict_ `attribute```
Virtual Environment Setup
Issue with -cffi and psycopg2
Looks like these 2 doesnt work .psycopg2-binary is there but not sure if it break it?
CFFI any idea?
serialize_response
I was trying to do the same what you did with the response_model and i created
Schema
class UserCreate(BaseModel):
email: EmailStr
password: str
class UserOut(BaseModel):
id: str
email: EmailStr
created_at: datetime
class Config:
orm_mode = True
Model
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True),
nullable=False, server_default=text('now()'))
Router
@router.get("/{id}", response_model=schemas.UserOut)
def get_user(id: int, db: Session = Depends(get_db)):
user = db.query(models.User).filter(models.User.id == id).first()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=" this id is not found")
return {"message": user}
Libs
anyio==3.6.2
bcrypt==4.0.1
click==8.1.3
dnspython==2.3.0
email-validator==1.3.1
fastapi==0.89.1
greenlet==2.0.1
h11==0.14.0
httptools==0.5.0
idna==3.4
passlib==1.7.4
psycopg2==2.9.5
pydantic==1.10.4
python-dotenv==0.21.1
PyYAML==6.0
sniffio==1.3.0
SQLAlchemy==1.4.23
starlette==0.22.0
typing_extensions==4.4.0
uvicorn==0.20.0
uvloop==0.17.0
watchfiles==0.18.1
websockets==10.4
Error :
in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 3 validation errors for UserOut
response -> id
field required (type=value_error.missing)
response -> email
field required (type=value_error.missing)
response -> created_at
field required (type=value_error.missing)
Question :
am I missing something here, i did the samething but i still get this error.
Server Error on creating users for duplicated emails
Server Error on creating users for duplicated emails, the api returns:
DETAIL: Key (email)=([email protected]) already exists.
To solve this, it should be included this code into create_user function in routers\user.py
this_email_count = db.query(models.User).filter(models.User.email == user.email).count()
if this_email_count > 0:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Email already used")
Unable to run on AWS EC2 Windows machine in production
First of all thanks for providing such a good course that too for free, coming back to the issue, i need to run the project on windows aws ec2 instance, i got all the files on my server it runs on server but 1) i need it to run without constantly keeping the cmd window open and it should use my domain name as host, please help
There is a issue of vars and __dict__ when performing join to get posts count
I have resolved it,
since it gives a error of so i have simple typecasted it to a dictionary, but now we know we have to return a list but a dict is unhashable
so again typecast it to list
the code being
list(dict(results))
But,
results = db.query(models.PostModel, func.count(models.Vote.post_id).label("votes")).join(
models.Vote, models.Vote.post_id == models.PostModel.id, isouter=True).group_by(models.PostModel.id).filter(models.PostModel.title.contains(search)).limit(limit).offset(skip).all()
when i am doing this the ditionary is not updating properly hence giving an error , if i do it with the resolved way then i dont get count of votes , probably because it is not updating with the dictionary , but when i do the way you told it gives up this error ,
func.count(models.Vote.post_id).label("votes")
this part is not getting updated to the dictionary
main.py my_posts 'key/value' issue
After typing the following script: my_posts = [{"title": "title of post 1", "content": "content of post 1", "id": 1},
{"favorite foods", "content": "I like pizza", "id": 2}]
Key/value pairs are not allowed within a set Pylance is the error message I am receiving with I like pizza and 2.
Here are the libraries I have imported:
from typing import Optional
from fastapi import FastAPI
from fastapi.params import Body
from pydantic import BaseModel
I would appreciate any insight regarding this issue.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.