├── .gitignore ├── 13.قسمت سیزدهم - Create User ├── db │ ├── __init__.py │ ├── models.py │ ├── hash.py │ ├── db_user.py │ └── database.py ├── requirements.txt ├── FastApi.db ├── schemas.py ├── main.py └── router │ ├── user.py │ └── blog_get.py ├── 16.قسمت شانزدهم - Api Article ├── db │ ├── __init__.py │ ├── hash.py │ ├── db_article.py │ ├── database.py │ ├── models.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── main.py ├── router │ ├── article.py │ ├── user.py │ └── blog_get.py └── schemas.py ├── 17.قسمت هفدهم - Error Handler ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── exceptions.py ├── router │ ├── article.py │ ├── user.py │ └── blog_get.py ├── main.py └── schemas.py ├── 18.قسمت هجدهم - Custom Response ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── exceptions.py ├── router │ ├── article.py │ ├── product.py │ ├── user.py │ └── blog_get.py ├── main.py └── schemas.py ├── 20. قسمت بیستم - Authentication ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── FastApi.db ├── exceptions.py ├── requirements.txt ├── router │ ├── article.py │ ├── user.py │ └── blog_get.py ├── Note ├── auth │ ├── oauth2.py │ └── authentication.py ├── main.py └── schemas.py ├── 14.قسمت چهاردهم - Read Update Delete User ├── db │ ├── __init__.py │ ├── models.py │ ├── hash.py │ ├── database.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── schemas.py ├── main.py └── router │ ├── user.py │ └── blog_get.py ├── 21. قسمت بیست و یکم - Verify user Token ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── FastApi.db ├── exceptions.py ├── requirements.txt ├── router │ ├── article.py │ ├── user.py │ └── blog_get.py ├── main.py ├── schemas.py └── auth │ └── authentication.py ├── 22. قسمت بیست و دوم - File - UploadFile ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── test │ ├── test.txt │ ├── image1.png │ └── image2.jpg ├── FastApi.db ├── files │ └── image2.jpg ├── exceptions.py ├── requirements.txt ├── router │ ├── file.py │ ├── article.py │ ├── user.py │ └── blog_get.py ├── main.py ├── schemas.py └── auth │ └── authentication.py ├── 24. قسمت بیست و چهارم - Async - Await ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── FastApi.db ├── files │ ├── image1.png │ └── image2.jpg ├── exceptions.py ├── requirements.txt ├── router │ ├── article.py │ ├── file.py │ ├── user.py │ └── blog_get.py ├── schemas.py ├── main.py └── auth │ └── authentication.py ├── 12.قسمت دوازدهم - Database - ORM Sqlalchemy ├── db │ ├── __init__.py │ ├── models.py │ └── database.py ├── requirements.txt ├── FastApi.db ├── main.py └── router │ └── blog_get.py ├── 15.قسمت پانزدهم - Relationship - Table Article ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── main.py ├── schemas.py └── router │ ├── user.py │ └── blog_get.py ├── 19.قسمت نوزدهم - Header - Cookie - Form Data ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── requirements.txt ├── FastApi.db ├── exceptions.py ├── router │ ├── article.py │ ├── user.py │ └── blog_get.py ├── main.py └── schemas.py ├── 25. قسمت بیست و پنجم - MiddleWare - Error CORS ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── FastApi.db ├── exceptions.py ├── requirements.txt ├── note ├── router │ ├── article.py │ ├── file.py │ ├── user.py │ └── blog_get.py ├── schemas.py └── auth │ └── authentication.py ├── 23. قسمت بیست و سوم - Download File - Static File ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── FastApi.db ├── exceptions.py ├── files │ ├── image1.png │ └── image2.jpg ├── requirements.txt ├── router │ ├── article.py │ ├── file.py │ └── user.py ├── schemas.py ├── main.py └── auth │ └── authentication.py ├── 26. قسمت بیست و ششم - WebSocket - Background Tasks ├── db │ ├── __init__.py │ ├── hash.py │ ├── database.py │ ├── models.py │ ├── db_article.py │ └── db_user.py ├── log.txt ├── FastApi.db ├── exceptions.py ├── requirements.txt ├── note ├── router │ ├── article.py │ ├── file.py │ └── user.py ├── schemas.py ├── client.py └── auth │ └── authentication.py ├── 27. Instagram قسمت اول پروژه ├── requirments ├── note ├── Instagram.db ├── db │ ├── __pycache__ │ │ ├── database.cpython-310.pyc │ │ └── models.cpython-310.pyc │ ├── models.py │ └── database.py └── main.py ├── 28. Instagram قسمت دوم پروژه ├── requirments ├── note ├── Instagram.db ├── main.py ├── db │ ├── hash.py │ ├── db_user.py │ ├── database.py │ └── models.py ├── routers │ └── user.py └── schemas.py ├── 29. Instagram قسمت سوم پروژه ├── requirments ├── Instagram.db ├── db │ ├── hash.py │ ├── db_user.py │ ├── database.py │ ├── db_post.py │ └── models.py ├── routers │ └── user.py ├── main.py └── schemas.py ├── 32. قسمت پایانی ├── Instagram.db ├── requirments ├── .idea │ ├── misc.xml │ ├── inspectionProfiles │ │ ├── profiles_settings.xml │ │ └── Project_Default.xml │ ├── modules.xml │ ├── Files.iml │ ├── dataSources.local.xml │ └── dataSources.xml ├── db │ ├── hash.py │ ├── database.py │ ├── db_user.py │ ├── db_post.py │ ├── db_comment.py │ └── models.py ├── routers │ ├── user.py │ └── comment.py ├── main.py ├── auth │ └── authentication.py └── schemas.py ├── 01.قسمت اول └── main.py ├── 06.قسمت ششم - Router ├── router │ ├── blog_post.py │ └── blog_get.py └── main.py ├── 07.قسمت هفتم - Method Post ├── main.py └── router │ ├── blog_post.py │ └── blog_get.py ├── 08.قسمت هشتم - Query MetaData ├── main.py └── router │ ├── blog_post.py │ └── blog_get.py ├── 09.قسمت نهم - Body Validator ├── main.py └── router │ ├── blog_post.py │ └── blog_get.py ├── 11.قسمت یازدهم - Complex SubTypes ├── main.py └── router │ └── blog_get.py ├── README.md ├── 10.قسمت دهم - integer Validators, Multiple Value ├── main.py └── router │ └── blog_get.py ├── 02.قسمت دوم - Path Parameter └── main.py ├── 03.قسمت سوم - Query Parameter └── main.py └── 04.قسمت چهارم - Status Code └── main.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | **/*.pyc 3 | __pycache__/ -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/test/test.txt: -------------------------------------------------------------------------------- 1 | salam ? 2 | khobi -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/log.txt: -------------------------------------------------------------------------------- 1 | Get All Blogs -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/requirments: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/requirments: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/requirments: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | pydantic>=1.9.0 3 | sqlalchemy -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | pydantic>=1.9.0 3 | sqlalchemy -------------------------------------------------------------------------------- /32. قسمت پایانی/Instagram.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/32. قسمت پایانی/Instagram.db -------------------------------------------------------------------------------- /32. قسمت پایانی/requirments: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy 4 | passlib 5 | bcrypt 6 | python-jose 7 | python-multipart -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/note: -------------------------------------------------------------------------------- 1 | signup login logout 2 | 3 | photo caption 4 | delete post 5 | 6 | view post 7 | comment ( Login ) -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/note: -------------------------------------------------------------------------------- 1 | signup login logout 2 | 3 | photo caption 4 | delete post 5 | 6 | view post 7 | comment ( Login ) -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/13.قسمت سیزدهم - Create User/FastApi.db -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/16.قسمت شانزدهم - Api Article/FastApi.db -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/17.قسمت هفدهم - Error Handler/FastApi.db -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/18.قسمت هجدهم - Custom Response/FastApi.db -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/20. قسمت بیستم - Authentication/FastApi.db -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/Instagram.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/27. Instagram قسمت اول پروژه/Instagram.db -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/Instagram.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/28. Instagram قسمت دوم پروژه/Instagram.db -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/Instagram.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/29. Instagram قسمت سوم پروژه/Instagram.db -------------------------------------------------------------------------------- /01.قسمت اول/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | 3 | app = FastAPI() 4 | 5 | @app.get('/index') 6 | def hello(): 7 | return 'hello world' 8 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/24. قسمت بیست و چهارم - Async - Await/FastApi.db -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/14.قسمت چهاردهم - Read Update Delete User/FastApi.db -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/21. قسمت بیست و یکم - Verify user Token/FastApi.db -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/22. قسمت بیست و دوم - File - UploadFile/FastApi.db -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/12.قسمت دوازدهم - Database - ORM Sqlalchemy/FastApi.db -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/15.قسمت پانزدهم - Relationship - Table Article/FastApi.db -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/19.قسمت نوزدهم - Header - Cookie - Form Data/FastApi.db -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/files/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/22. قسمت بیست و دوم - File - UploadFile/files/image2.jpg -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/test/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/22. قسمت بیست و دوم - File - UploadFile/test/image1.png -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/test/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/22. قسمت بیست و دوم - File - UploadFile/test/image2.jpg -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/files/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/24. قسمت بیست و چهارم - Async - Await/files/image1.png -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/files/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/24. قسمت بیست و چهارم - Async - Await/files/image2.jpg -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/25. قسمت بیست و پنجم - MiddleWare - Error CORS/FastApi.db -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/23. قسمت بیست و سوم - Download File - Static File/FastApi.db -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/FastApi.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/26. قسمت بیست و ششم - WebSocket - Background Tasks/FastApi.db -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailNotValid(Exception): 2 | pass 3 | # def __init__(self, detail): 4 | # self.detail = detail 5 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/files/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/23. قسمت بیست و سوم - Download File - Static File/files/image1.png -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/files/image2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/23. قسمت بیست و سوم - Download File - Static File/files/image2.jpg -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/db/__pycache__/database.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/27. Instagram قسمت اول پروژه/db/__pycache__/database.cpython-310.pyc -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/db/__pycache__/models.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/persianpython/FastApi/HEAD/27. Instagram قسمت اول پروژه/db/__pycache__/models.cpython-310.pyc -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi>=0.75.0 2 | uvicorn 3 | pydantic>=1.9.0 4 | sqlalchemy 5 | passlib 6 | bcrypt 7 | python-multipart 8 | python-jose 9 | websockets -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/note: -------------------------------------------------------------------------------- 1 | app.add_middleware( 2 | CORSMiddleware, 3 | allow_origins=origins, 4 | allow_credentials=True, 5 | allow_methods=["*"], 6 | allow_headers=["*"], 7 | ) -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/note: -------------------------------------------------------------------------------- 1 | app.add_middleware( 2 | CORSMiddleware, 3 | allow_origins=origins, 4 | allow_credentials=True, 5 | allow_methods=["*"], 6 | allow_headers=["*"], 7 | ) -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /06.قسمت ششم - Router/router/blog_post.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | 3 | router = APIRouter(prefix='/blog', tags=['blog']) 4 | 5 | 6 | @router.post('/new') 7 | def create_blog(): 8 | return {"message": 'OK'} 9 | 10 | -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from db.models import Base 3 | from db.database import engine 4 | 5 | app = FastAPI() 6 | 7 | Base.metadata.create_all(engine) 8 | 9 | @app.get("/") 10 | def home(): 11 | return "First Page" 12 | -------------------------------------------------------------------------------- /06.قسمت ششم - Router/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /07.قسمت هفتم - Method Post/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /08.قسمت هشتم - Query MetaData/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /09.قسمت نهم - Body Validator/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class UserBase(BaseModel): 5 | username: str 6 | password: str 7 | email: str 8 | 9 | 10 | class UserDisplay(BaseModel): 11 | username:str 12 | email:str 13 | 14 | class Config: 15 | orm_mode = True -------------------------------------------------------------------------------- /11.قسمت یازدهم - Complex SubTypes/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class UserBase(BaseModel): 5 | username: str 6 | password: str 7 | email: str 8 | 9 | 10 | class UserDisplay(BaseModel): 11 | username:str 12 | email:str 13 | 14 | class Config: 15 | orm_mode = True -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # آموزش FastApi 2 | 3 | فایل های هرقست از آموزش FastApi 4 | 5 | # Persian Python 6 | 7 | لینک پلی لیست آموزش : https://youtube.com/playlist?list=PLVN7DLFGYaP46oDpQtSnOR6vguu_YpUM9 8 | 9 | لینک کانال یوتیوب : https://www.youtube.com/c/PersianPython 10 | 11 | لینک کانال تلگرام : https://t.me/persianpython_official 12 | -------------------------------------------------------------------------------- /10.قسمت دهم - integer Validators, Multiple Value/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | 5 | app = FastAPI() 6 | app.include_router(blog_get.router) 7 | app.include_router(blog_post.router) 8 | 9 | 10 | @app.get('/') 11 | def hello(): 12 | return 'hello world' 13 | -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from db.models import Base 3 | from db.database import engine 4 | from routers import user 5 | 6 | app = FastAPI() 7 | app.include_router(user.router) 8 | 9 | Base.metadata.create_all(engine) 10 | 11 | @app.get("/") 12 | def home(): 13 | return "First Page" 14 | -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String 3 | 4 | 5 | class DbUser(Base): 6 | __tablename__ = 'users' 7 | 8 | id = Column(Integer, index=True, primary_key=True) 9 | username = Column(String) 10 | email = Column(String) 11 | password = Column(String) 12 | -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String 3 | 4 | 5 | class UserBase(Base): 6 | __tablename__ = "user" 7 | 8 | id = Column(Integer, index=True, primary_key=True) 9 | username = Column(String) 10 | password = Column(String) 11 | email = Column(String) 12 | -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String 3 | 4 | 5 | class DbUser(Base): 6 | __tablename__ = 'users' 7 | 8 | id = Column(Integer, index=True, primary_key=True) 9 | username = Column(String) 10 | email = Column(String) 11 | password = Column(String) 12 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String 3 | 4 | 5 | class DbUser(Base): 6 | __tablename__ = 'users' 7 | 8 | id = Column(Integer, index=True, primary_key=True) 9 | username = Column(String) 10 | email = Column(String) 11 | password = Column(String) 12 | -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/Files.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | from db import models 5 | from db.database import engine 6 | 7 | app = FastAPI() 8 | app.include_router(blog_get.router) 9 | app.include_router(blog_post.router) 10 | models.Base.metadata.create_all(engine) 11 | 12 | @app.get('/') 13 | def hello(): 14 | return 'hello world' 15 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/hash.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes='bcrypt', deprecated='auto') 4 | 5 | 6 | class Hash: 7 | 8 | @staticmethod 9 | def bcrypt(password): 10 | return pwd_cxt.hash(password) 11 | 12 | @staticmethod 13 | def verify(hashed_password, plain_password): 14 | return pwd_cxt.verify(plain_password, hashed_password) -------------------------------------------------------------------------------- /32. قسمت پایانی/routers/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from sqlalchemy.orm import Session 3 | 4 | from db.database import get_db 5 | from db import db_user 6 | from schemas import UserDisplay, UserBase 7 | 8 | router = APIRouter(prefix="/user", tags=['user']) 9 | 10 | 11 | @router.post("", response_model=UserDisplay) 12 | def create_user(request: UserBase, db: Session = Depends(get_db)): 13 | return db_user.create_user(request, db) 14 | -------------------------------------------------------------------------------- /07.قسمت هفتم - Method Post/router/blog_post.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | from pydantic import BaseModel 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class BlogModel(BaseModel): 9 | title: str 10 | content: str 11 | nb_comments: int 12 | published: Optional[bool] 13 | 14 | 15 | @router.post('/new') 16 | def create_blog(blog: BlogModel): 17 | return {"message": 'OK', "data": blog} 18 | -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/db/db_user.py: -------------------------------------------------------------------------------- 1 | from db.models import User 2 | from schemas import UserBase 3 | from sqlalchemy.orm import Session 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(request: UserBase, db: Session): 8 | user = User( 9 | username=request.username, 10 | password=Hash.bcrypt(request.password), 11 | email=request.email 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/db/db_user.py: -------------------------------------------------------------------------------- 1 | from db.models import User 2 | from schemas import UserBase 3 | from sqlalchemy.orm import Session 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(request: UserBase, db: Session): 8 | user = User( 9 | username=request.username, 10 | password=Hash.bcrypt(request.password), 11 | email=request.email 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/routers/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from sqlalchemy.orm import Session 3 | 4 | from db.database import get_db 5 | from db import db_user 6 | from schemas import UserDisplay, UserBase 7 | 8 | router = APIRouter(prefix="/user", tags=['user']) 9 | 10 | 11 | @router.post("", response_model=UserDisplay) 12 | def create_user(request: UserBase, db: Session = Depends(get_db)): 13 | return db_user.create_user(request, db) 14 | -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/routers/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from sqlalchemy.orm import Session 3 | 4 | from db.database import get_db 5 | from db import db_user 6 | from schemas import UserDisplay, UserBase 7 | 8 | router = APIRouter(prefix="/user", tags=['user']) 9 | 10 | 11 | @router.post("", response_model=UserDisplay) 12 | def create_user(request: UserBase, db: Session = Depends(get_db)): 13 | return db_user.create_user(request, db) 14 | -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | from router import user 5 | from db import models 6 | from db.database import engine 7 | 8 | app = FastAPI() 9 | app.include_router(blog_get.router) 10 | app.include_router(blog_post.router) 11 | app.include_router(user.router) 12 | models.Base.metadata.create_all(engine) 13 | 14 | @app.get('/') 15 | def hello(): 16 | return 'hello world' 17 | 18 | -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(db:Session, request: UserBase): 8 | user = DbUser( 9 | username=request.username, 10 | email=request.email, 11 | password=Hash.bcrypt(request.password) 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user 17 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | from router import user 5 | from db import models 6 | from db.database import engine 7 | 8 | app = FastAPI() 9 | app.include_router(blog_get.router) 10 | app.include_router(blog_post.router) 11 | app.include_router(user.router) 12 | models.Base.metadata.create_all(engine) 13 | 14 | @app.get('/') 15 | def hello(): 16 | return 'hello world' 17 | 18 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | from router import user 5 | from db import models 6 | from db.database import engine 7 | 8 | app = FastAPI() 9 | app.include_router(blog_get.router) 10 | app.include_router(blog_post.router) 11 | app.include_router(user.router) 12 | models.Base.metadata.create_all(engine) 13 | 14 | @app.get('/') 15 | def hello(): 16 | return 'hello world' 17 | 18 | -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from fastapi.staticfiles import StaticFiles 3 | from db.models import Base 4 | from db.database import engine 5 | from routers import user 6 | from routers import post 7 | 8 | app = FastAPI() 9 | app.include_router(user.router) 10 | app.include_router(post.router) 11 | 12 | 13 | app.mount("/uploaded_files", StaticFiles(directory="uploaded_files"), name="uploaded_files") 14 | 15 | Base.metadata.create_all(engine) 16 | 17 | @app.get("/") 18 | def home(): 19 | return "First Page" 20 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from router import blog_get 3 | from router import blog_post 4 | from router import user 5 | from router import article 6 | from db import models 7 | from db.database import engine 8 | 9 | app = FastAPI() 10 | app.include_router(blog_get.router) 11 | app.include_router(blog_post.router) 12 | app.include_router(user.router) 13 | app.include_router(article.router) 14 | models.Base.metadata.create_all(engine) 15 | 16 | @app.get('/') 17 | def hello(): 18 | return 'hello world' 19 | 20 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | from sqlalchemy import create_engine 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | engine = create_engine("sqlite:///Instagram.db", connect_args={'check_same_thread':False}) 6 | Base = declarative_base() 7 | 8 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 9 | 10 | 11 | def get_db(): 12 | session = sessionlocal() 13 | try: 14 | yield session 15 | finally: 16 | session.close() 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /27. Instagram قسمت اول پروژه/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | from sqlalchemy import create_engine 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | engine = create_engine("sqlite:///Instagram.db", connect_args={'check_same_thread':False}) 6 | Base = declarative_base() 7 | 8 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 9 | 10 | 11 | def get_db(): 12 | session = sessionlocal() 13 | try: 14 | yield session 15 | finally: 16 | session.close() 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | from sqlalchemy import create_engine 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | engine = create_engine("sqlite:///Instagram.db", connect_args={'check_same_thread':False}) 6 | Base = declarative_base() 7 | 8 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 9 | 10 | 11 | def get_db(): 12 | session = sessionlocal() 13 | try: 14 | yield session 15 | finally: 16 | session.close() 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | from sqlalchemy import create_engine 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | engine = create_engine("sqlite:///Instagram.db", connect_args={'check_same_thread':False}) 6 | Base = declarative_base() 7 | 8 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 9 | 10 | 11 | def get_db(): 12 | session = sessionlocal() 13 | try: 14 | yield session 15 | finally: 16 | session.close() 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user:UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read user 18 | 19 | 20 | # update user 21 | 22 | 23 | # delete user -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(engine=engine) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /02.قسمت دوم - Path Parameter/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from enum import Enum 3 | 4 | app = FastAPI() 5 | 6 | @app.get('/') 7 | def hello(): 8 | return 'hello world' 9 | 10 | 11 | class TypeBlogs(str, Enum): 12 | Mesal1 = 'mesal1' 13 | Mesal2 = 'mesal2' 14 | Mesal3 = 'mesal3' 15 | 16 | 17 | @app.get('/blog/type/{type}') 18 | def get_type_blog(type:TypeBlogs): 19 | return {'message': f'blog type is {type}'} 20 | 21 | @app.get('/blog/all') 22 | def get_blogs(): 23 | return {'message':f'all blogs'} 24 | 25 | @app.get('/blog/{id}') 26 | def get_blog(id:int): 27 | return {'message':f'blog {id}'} 28 | 29 | # pydantic -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | 5 | 6 | def create_article(db:Session, request:ArticleBase): 7 | article = DbArticle(title=request.title, 8 | content=request.content, 9 | published=request.published, 10 | user_id=request.creator_id) 11 | db.add(article) 12 | db.commit() 13 | db.refresh(article) 14 | return article 15 | 16 | 17 | def get_article(id, db:Session): 18 | return db.query(DbArticle).filter(DbArticle.id == id).first() 19 | -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/db/db_post.py: -------------------------------------------------------------------------------- 1 | from db.models import Post 2 | from schemas import PostBase 3 | from sqlalchemy.orm import Session 4 | import datetime 5 | 6 | 7 | def create_post(request: PostBase, db: Session): 8 | new_post = Post( 9 | image_url=request.image_url, 10 | image_url_type=request.image_url_type, 11 | caption=request.caption, 12 | timestamp=datetime.datetime.now(), 13 | user_id=request.creator_id 14 | ) 15 | db.add(new_post) 16 | db.commit() 17 | db.refresh(new_post) 18 | return new_post 19 | 20 | 21 | def get_all_posts(db: Session): 22 | return db.query(Post).all() 23 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | engine = create_engine("sqlite:///FastApi.db", connect_args={'check_same_thread':False}) 7 | Base = declarative_base() 8 | 9 | sessionlocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) 10 | 11 | 12 | def get_db(): 13 | session = sessionlocal() 14 | try: 15 | yield session 16 | finally: 17 | session.close() 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /32. قسمت پایانی/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from fastapi.staticfiles import StaticFiles 3 | from db.models import Base 4 | from db.database import engine 5 | from routers import user 6 | from routers import post 7 | from routers import comment 8 | from auth import authentication 9 | 10 | app = FastAPI() 11 | app.include_router(user.router) 12 | app.include_router(post.router) 13 | app.include_router(comment.router) 14 | app.include_router(authentication.router) 15 | 16 | 17 | app.mount("/uploaded_files", StaticFiles(directory="uploaded_files"), name="uploaded_files") 18 | 19 | Base.metadata.create_all(engine) 20 | 21 | @app.get("/") 22 | def home(): 23 | return "First Page" 24 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import oauth2_scheme 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}', response_model=ArticleDisplay) 18 | def get_article(id: int, db=Depends(get_db), token:str=Depends(oauth2_scheme)): 19 | return db_article.get_article(id, db) 20 | 21 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import ArticleBase, ArticleDisplay 5 | from db import db_article 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/article', tags=['article']) 9 | 10 | 11 | # create article 12 | @router.post('/', response_model=ArticleDisplay) 13 | def create_article(article: ArticleBase, db=Depends(get_db)): 14 | return db_article.create_article(db, article) 15 | 16 | 17 | # read article 18 | @router.get('/{id}', response_model=ArticleDisplay) 19 | def get_article(id: int, db=Depends(get_db)): 20 | return db_article.get_article(id, db) 21 | 22 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import ArticleBase, ArticleDisplay 5 | from db import db_article 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/article', tags=['article']) 9 | 10 | 11 | # create article 12 | @router.post('/', response_model=ArticleDisplay) 13 | def create_article(article: ArticleBase, db=Depends(get_db)): 14 | return db_article.create_article(db, article) 15 | 16 | 17 | # read article 18 | @router.get('/{id}', response_model=ArticleDisplay) 19 | def get_article(id: int, db=Depends(get_db)): 20 | return db_article.get_article(id, db) 21 | 22 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import ArticleBase, ArticleDisplay 5 | from db import db_article 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/article', tags=['article']) 9 | 10 | 11 | # create article 12 | @router.post('/', response_model=ArticleDisplay) 13 | def create_article(article: ArticleBase, db=Depends(get_db)): 14 | return db_article.create_article(db, article) 15 | 16 | 17 | # read article 18 | @router.get('/{id}', response_model=ArticleDisplay) 19 | def get_article(id: int, db=Depends(get_db)): 20 | return db_article.get_article(id, db) 21 | 22 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import ArticleBase, ArticleDisplay 5 | from db import db_article 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/article', tags=['article']) 9 | 10 | 11 | # create article 12 | @router.post('/', response_model=ArticleDisplay) 13 | def create_article(article: ArticleBase, db=Depends(get_db)): 14 | return db_article.create_article(db, article) 15 | 16 | 17 | # read article 18 | @router.get('/{id}', response_model=ArticleDisplay) 19 | def get_article(id: int, db=Depends(get_db)): 20 | return db_article.get_article(id, db) 21 | 22 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/router/file.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, File, UploadFile 2 | import shutil 3 | 4 | 5 | router = APIRouter(prefix='/file', tags=['file']) 6 | 7 | 8 | @router.post('/file') 9 | def get_file(file: bytes = File(...)): 10 | content = file.decode('utf-8') 11 | content.split('\n') 12 | return { 13 | 'data': content 14 | } 15 | 16 | 17 | @router.post('/uploadfile') 18 | def upload_file(file: UploadFile= File(...)): 19 | name = file.filename 20 | type = file.content_type 21 | 22 | path = f'files/{name}' 23 | with open(path, 'w+b') as buffer: 24 | shutil.copyfileobj(file.file, buffer) 25 | 26 | return { 27 | 'path': path, 28 | 'type': type 29 | } 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/Note: -------------------------------------------------------------------------------- 1 | from fastapi.security import OAuth2PasswordBearer 2 | from typing import Optional 3 | from datetime import datetime, timedelta 4 | from jose import jwt 5 | 6 | 7 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") 8 | 9 | SECRET_KEY = 'fba012a2a0c9c3d884fdf15843f2aa438bac1b5e8527875ecd7187e3ce494158' 10 | ALGORITHM = 'HS256' 11 | ACCESS_TOKEN_EXPIRE_MINUTES = 30 12 | 13 | def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): 14 | to_encode = data.copy() 15 | if expires_delta: 16 | expire = datetime.utcnow() + expires_delta 17 | else: 18 | expire = datetime.utcnow() + timedelta(minutes=15) 19 | to_encode.update({"exp": expire}) 20 | encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 21 | return encoded_jwt 22 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/auth/oauth2.py: -------------------------------------------------------------------------------- 1 | from fastapi.security import OAuth2PasswordBearer 2 | from typing import Optional 3 | from datetime import datetime, timedelta 4 | from jose import jwt 5 | 6 | 7 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") 8 | 9 | SECRET_KEY = '6c7d438d2ea66cc11ee315566bda6f45336930dc2a40eaa96ec009524c20aa69' 10 | ALGORITHM = 'HS256' 11 | ACCESS_TOKEN_EXPIRE_MINUTES = 30 12 | 13 | def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): 14 | to_encode = data.copy() 15 | if expires_delta: 16 | expire = datetime.utcnow() + expires_delta 17 | else: 18 | expire = datetime.utcnow() + timedelta(minutes=15) 19 | to_encode.update({"exp": expire}) 20 | encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 21 | return encoded_jwt 22 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/router/article.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends 2 | from schemas import ArticleBase, ArticleDisplay, UserBase 3 | from db import db_article 4 | from db.database import get_db 5 | from auth.oauth2 import get_current_user 6 | 7 | router = APIRouter(prefix='/article', tags=['article']) 8 | 9 | 10 | # create article 11 | @router.post('/', response_model=ArticleDisplay) 12 | def create_article(article: ArticleBase, db=Depends(get_db)): 13 | return db_article.create_article(db, article) 14 | 15 | 16 | # read article 17 | @router.get('/{id}') 18 | def get_article(id: int, db=Depends(get_db), current_user : UserBase= Depends(get_current_user)): 19 | return { 20 | "data": db_article.get_article(id, db), 21 | "current_user": current_user 22 | } 23 | 24 | -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, DateTime, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class User(Base): 7 | __tablename__ = "user" 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | password = Column(String) 12 | email = Column(String) 13 | items = relationship("Post", back_pppulates='user') 14 | 15 | 16 | class Post(Base): 17 | __tablename__ = "post" 18 | 19 | image_url = Column(String) 20 | image_url_type = Column(String) 21 | caption = Column(String) 22 | timestamp = Column(DateTime) 23 | user_id = Column(Integer, ForeignKey('user.id')) 24 | user = relationship("Post", back_populates='items') 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /28. Instagram قسمت دوم پروژه/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from datetime import datetime 3 | 4 | 5 | class UserBase(BaseModel): 6 | username: str 7 | email: str 8 | password: str 9 | 10 | 11 | class UserDisplay(BaseModel): 12 | username: str 13 | email: str 14 | 15 | class Config: 16 | orm_mode = True 17 | 18 | 19 | class PostBase(BaseModel): 20 | image_url: str 21 | image_url_type: str 22 | caption: str 23 | creator_id: int 24 | 25 | 26 | class User(BaseModel): 27 | username: str 28 | 29 | class Config: 30 | orm_mode = True 31 | 32 | 33 | class PostDisplay(BaseModel): 34 | id: int 35 | image_url: str 36 | image_url_type: str 37 | caption: str 38 | timestamp: datetime 39 | user: User 40 | 41 | class Config: 42 | orm_mode = True 43 | -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from datetime import datetime 3 | 4 | 5 | class UserBase(BaseModel): 6 | username: str 7 | email: str 8 | password: str 9 | 10 | 11 | class UserDisplay(BaseModel): 12 | username: str 13 | email: str 14 | 15 | class Config: 16 | orm_mode = True 17 | 18 | 19 | class PostBase(BaseModel): 20 | image_url: str 21 | image_url_type: str 22 | caption: str 23 | creator_id: int 24 | 25 | 26 | class User(BaseModel): 27 | username: str 28 | 29 | class Config: 30 | orm_mode = True 31 | 32 | 33 | class PostDisplay(BaseModel): 34 | id: int 35 | image_url: str 36 | image_url_type: str 37 | caption: str 38 | timestamp: datetime 39 | user: User 40 | 41 | class Config: 42 | orm_mode = True 43 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/db_user.py: -------------------------------------------------------------------------------- 1 | from db.models import User 2 | from schemas import UserBase 3 | from sqlalchemy.orm import Session 4 | from db.hash import Hash 5 | from fastapi.exceptions import HTTPException 6 | from fastapi import status 7 | 8 | 9 | def create_user(request: UserBase, db: Session): 10 | user = User( 11 | username=request.username, 12 | password=Hash.bcrypt(request.password), 13 | email=request.email 14 | ) 15 | db.add(user) 16 | db.commit() 17 | db.refresh(user) 18 | return user 19 | 20 | def get_user_by_username(username:str, db:Session): 21 | user = db.query(User).filter(User.username == username).first() 22 | if not user: 23 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 24 | detail="User Not Found !") 25 | 26 | return user 27 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUsers', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, Boolean, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class DbUser(Base): 7 | __tablename__ = 'users' 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | email = Column(String) 12 | password = Column(String) 13 | items = relationship('DbArticle', back_populates='user') 14 | 15 | 16 | class DbArticle(Base): 17 | __tablename__ = 'articles' 18 | id = Column(Integer, index=True, primary_key=True) 19 | title = Column(String) 20 | content = Column(String) 21 | published = Column(Boolean) 22 | 23 | user_id = Column(Integer, ForeignKey('users.id')) 24 | user = relationship('DbUser', back_populates='items') 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | from router import blog_get 5 | from router import blog_post 6 | from router import user 7 | from router import article 8 | from db import models 9 | from db.database import engine 10 | from exceptions import EmailNotValid 11 | 12 | 13 | app = FastAPI() 14 | app.include_router(blog_get.router) 15 | app.include_router(blog_post.router) 16 | app.include_router(user.router) 17 | app.include_router(article.router) 18 | models.Base.metadata.create_all(engine) 19 | 20 | @app.get('/') 21 | def hello(): 22 | return 'hello world' 23 | 24 | 25 | @app.exception_handler(EmailNotValid) 26 | def email_not_valid(request: Request, exc: EmailNotValid): 27 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /29. Instagram قسمت سوم پروژه/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, DateTime, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class User(Base): 7 | __tablename__ = "user" 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | password = Column(String) 12 | email = Column(String) 13 | items = relationship("Post", back_populates='user') 14 | 15 | 16 | class Post(Base): 17 | __tablename__ = "post" 18 | id = Column(Integer, index=True, primary_key=True) 19 | image_url = Column(String) 20 | image_url_type = Column(String) 21 | caption = Column(String) 22 | timestamp = Column(DateTime) 23 | user_id = Column(Integer, ForeignKey('user.id')) 24 | user = relationship("User", back_populates='items') 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 21 | -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/dataSources.local.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | " 7 | 8 | 9 | no-auth 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/db_article.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import ArticleBase 3 | from db.models import DbArticle 4 | from fastapi.exceptions import HTTPException 5 | from fastapi import status 6 | 7 | 8 | def create_article(db:Session, request:ArticleBase): 9 | article = DbArticle(title=request.title, 10 | content=request.content, 11 | published=request.published, 12 | user_id=request.creator_id) 13 | db.add(article) 14 | db.commit() 15 | db.refresh(article) 16 | return article 17 | 18 | 19 | def get_article(id, db:Session): 20 | article = db.query(DbArticle).filter(DbArticle.id == id).first() 21 | if not article: 22 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 23 | detail=f"article with id {id} not Found !") 24 | return article 25 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | from router import blog_get 5 | from router import blog_post 6 | from router import user 7 | from router import article 8 | from router import product 9 | from db import models 10 | from db.database import engine 11 | from exceptions import EmailNotValid 12 | 13 | 14 | app = FastAPI() 15 | app.include_router(blog_get.router) 16 | app.include_router(blog_post.router) 17 | app.include_router(user.router) 18 | app.include_router(article.router) 19 | app.include_router(product.router) 20 | models.Base.metadata.create_all(engine) 21 | 22 | @app.get('/') 23 | def hello(): 24 | return 'hello world' 25 | 26 | 27 | @app.exception_handler(EmailNotValid) 28 | def email_not_valid(request: Request, exc: EmailNotValid): 29 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | 5 | from router import blog_get, blog_post, user,article,product 6 | from auth import authentication 7 | from db import models 8 | from db.database import engine 9 | from exceptions import EmailNotValid 10 | 11 | 12 | app = FastAPI() 13 | app.include_router(blog_get.router) 14 | app.include_router(blog_post.router) 15 | app.include_router(user.router) 16 | app.include_router(article.router) 17 | app.include_router(product.router) 18 | app.include_router(authentication.router) 19 | 20 | 21 | models.Base.metadata.create_all(engine) 22 | 23 | @app.get('/') 24 | def hello(): 25 | return 'hello world' 26 | 27 | 28 | @app.exception_handler(EmailNotValid) 29 | def email_not_valid(request: Request, exc: EmailNotValid): 30 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | from router import blog_get 5 | from router import blog_post 6 | from router import user 7 | from router import article 8 | from router import product 9 | from db import models 10 | from db.database import engine 11 | from exceptions import EmailNotValid 12 | 13 | 14 | app = FastAPI() 15 | app.include_router(blog_get.router) 16 | app.include_router(blog_post.router) 17 | app.include_router(user.router) 18 | app.include_router(article.router) 19 | app.include_router(product.router) 20 | models.Base.metadata.create_all(engine) 21 | 22 | @app.get('/') 23 | def hello(): 24 | return 'hello world' 25 | 26 | 27 | @app.exception_handler(EmailNotValid) 28 | def email_not_valid(request: Request, exc: EmailNotValid): 29 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | 5 | from router import blog_get, blog_post, user,article,product 6 | from auth import authentication 7 | from db import models 8 | from db.database import engine 9 | from exceptions import EmailNotValid 10 | 11 | 12 | app = FastAPI() 13 | app.include_router(blog_get.router) 14 | app.include_router(blog_post.router) 15 | app.include_router(user.router) 16 | app.include_router(article.router) 17 | app.include_router(product.router) 18 | app.include_router(authentication.router) 19 | 20 | 21 | models.Base.metadata.create_all(engine) 22 | 23 | @app.get('/') 24 | def hello(): 25 | return 'hello world' 26 | 27 | 28 | @app.exception_handler(EmailNotValid) 29 | def email_not_valid(request: Request, exc: EmailNotValid): 30 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/router/file.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, File, UploadFile 2 | from fastapi.responses import FileResponse 3 | import shutil 4 | 5 | 6 | 7 | router = APIRouter(prefix='/file', tags=['file']) 8 | 9 | 10 | @router.post('/file') 11 | def get_file(file: bytes = File(...)): 12 | content = file.decode('utf-8') 13 | content.split('\n') 14 | return { 15 | 'data': content 16 | } 17 | 18 | 19 | @router.post('/uploadfile') 20 | def upload_file(file: UploadFile= File(...)): 21 | name = file.filename 22 | type = file.content_type 23 | 24 | path = f'files/{name}' 25 | with open(path, 'w+b') as buffer: 26 | shutil.copyfileobj(file.file, buffer) 27 | 28 | return { 29 | 'path': path, 30 | 'type': type 31 | } 32 | 33 | 34 | @router.post('/download/{name}', response_class=FileResponse) 35 | def download_file(name:str): 36 | path = f'files/{name}' 37 | return path 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/router/file.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, File, UploadFile 2 | from fastapi.responses import FileResponse 3 | import shutil 4 | 5 | 6 | 7 | router = APIRouter(prefix='/file', tags=['file']) 8 | 9 | 10 | @router.post('/file') 11 | def get_file(file: bytes = File(...)): 12 | content = file.decode('utf-8') 13 | content.split('\n') 14 | return { 15 | 'data': content 16 | } 17 | 18 | 19 | @router.post('/uploadfile') 20 | def upload_file(file: UploadFile= File(...)): 21 | name = file.filename 22 | type = file.content_type 23 | 24 | path = f'files/{name}' 25 | with open(path, 'w+b') as buffer: 26 | shutil.copyfileobj(file.file, buffer) 27 | 28 | return { 29 | 'path': path, 30 | 'type': type 31 | } 32 | 33 | 34 | @router.post('/download/{name}', response_class=FileResponse) 35 | def download_file(name:str): 36 | path = f'files/{name}' 37 | return path 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/router/file.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, File, UploadFile 2 | from fastapi.responses import FileResponse 3 | import shutil 4 | 5 | 6 | 7 | router = APIRouter(prefix='/file', tags=['file']) 8 | 9 | 10 | @router.post('/file') 11 | def get_file(file: bytes = File(...)): 12 | content = file.decode('utf-8') 13 | content.split('\n') 14 | return { 15 | 'data': content 16 | } 17 | 18 | 19 | @router.post('/uploadfile') 20 | def upload_file(file: UploadFile= File(...)): 21 | name = file.filename 22 | type = file.content_type 23 | 24 | path = f'files/{name}' 25 | with open(path, 'w+b') as buffer: 26 | shutil.copyfileobj(file.file, buffer) 27 | 28 | return { 29 | 'path': path, 30 | 'type': type 31 | } 32 | 33 | 34 | @router.post('/download/{name}', response_class=FileResponse) 35 | def download_file(name:str): 36 | path = f'files/{name}' 37 | return path 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/router/file.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, File, UploadFile 2 | from fastapi.responses import FileResponse 3 | import shutil 4 | 5 | 6 | 7 | router = APIRouter(prefix='/file', tags=['file']) 8 | 9 | 10 | @router.post('/file') 11 | def get_file(file: bytes = File(...)): 12 | content = file.decode('utf-8') 13 | content.split('\n') 14 | return { 15 | 'data': content 16 | } 17 | 18 | 19 | @router.post('/uploadfile') 20 | def upload_file(file: UploadFile= File(...)): 21 | name = file.filename 22 | type = file.content_type 23 | 24 | path = f'files/{name}' 25 | with open(path, 'w+b') as buffer: 26 | shutil.copyfileobj(file.file, buffer) 27 | 28 | return { 29 | 'path': path, 30 | 'type': type 31 | } 32 | 33 | 34 | @router.post('/download/{name}', response_class=FileResponse) 35 | def download_file(name:str): 36 | path = f'files/{name}' 37 | return path 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | 5 | from router import blog_get, blog_post, user,article,product, file 6 | from auth import authentication 7 | from db import models 8 | from db.database import engine 9 | from exceptions import EmailNotValid 10 | 11 | 12 | app = FastAPI() 13 | app.include_router(blog_get.router) 14 | app.include_router(blog_post.router) 15 | app.include_router(user.router) 16 | app.include_router(article.router) 17 | app.include_router(product.router) 18 | app.include_router(authentication.router) 19 | app.include_router(file.router) 20 | 21 | 22 | models.Base.metadata.create_all(engine) 23 | 24 | @app.get('/') 25 | def hello(): 26 | return 'hello world' 27 | 28 | 29 | @app.exception_handler(EmailNotValid) 30 | def email_not_valid(request: Request, exc: EmailNotValid): 31 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /08.قسمت هشتم - Query MetaData/router/blog_post.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query 2 | from pydantic import BaseModel 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class BlogModel(BaseModel): 9 | title: str 10 | content: str 11 | nb_comments: int 12 | published: Optional[bool] 13 | 14 | 15 | @router.post('/new/{id}') 16 | def create_blog(blog: BlogModel, id: int, version: int = 1): 17 | return {"message": 'OK', "data": blog, "id": id, 'version': version} 18 | 19 | 20 | @router.post('/new/{id}/comment') 21 | def create_comment(id: int, blog: BlogModel, comment_id: int = 22 | Query(None, 23 | title='Title Text !', 24 | description='Description Text !', 25 | alias='CommentID', 26 | deprecated=True 27 | )): 28 | return { 29 | 'blog': blog, 30 | 'id': id, 31 | 'comment_id': comment_id 32 | } 33 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/router/product.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Response 2 | from fastapi.responses import HTMLResponse, PlainTextResponse 3 | 4 | 5 | router = APIRouter(prefix='/product', tags=['product']) 6 | 7 | products = ['watch', 'clock', 'microphone'] 8 | 9 | 10 | @router.get('/') 11 | def get_all(): 12 | data = " ".join(products) 13 | return Response(content=data, media_type="text/plain") 14 | 15 | 16 | @router.get("/{id}", responses={ 17 | 404:{"content":{"text/plain": {'example': "Product Not Found !"}}, 18 | "description": "vaghti mahsol peyda nashode bashe"}, 19 | 200:{"content":{"text/html": {'example': "
data
"}}, 20 | "description": "Html Code Data "} 21 | }) 22 | def get_product(id: int): 23 | if id > len(products): 24 | text = "Product Not Found !" 25 | return PlainTextResponse(status_code=404, content=text, media_type="text/plain") 26 | 27 | data = products[id] 28 | return HTMLResponse(content=f"
{data}
", media_type="text/html") -------------------------------------------------------------------------------- /03.قسمت سوم - Query Parameter/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | app = FastAPI() 6 | 7 | @app.get('/') 8 | def hello(): 9 | return 'hello world' 10 | 11 | 12 | class TypeBlogs(str, Enum): 13 | Mesal1 = 'mesal1' 14 | Mesal2 = 'mesal2' 15 | Mesal3 = 'mesal3' 16 | 17 | @app.get('/blog/{id}/comments/{comment_id}') 18 | def get_comment(id:int, comment_id:int, valid:bool=True, username:Optional[str]=None): 19 | return {"message":f"blog id {id} comment id {comment_id} {valid=} {username=}"} 20 | 21 | 22 | @app.get('/blog/all') 23 | def get_blogs(page:Optional[int]=None, page_size:str=None): 24 | return {"message": f"{page=} -- {page_size=}"} 25 | 26 | 27 | @app.get('/blog/type/{type}') 28 | def get_type_blog(type:TypeBlogs): 29 | return {'message': f'blog type is {type}'} 30 | 31 | # @app.get('/blog/all') 32 | # def get_blogs(): 33 | # return {'message':f'all blogs'} 34 | 35 | @app.get('/blog/{id}') 36 | def get_blog(id:int): 37 | return {'message':f'blog {id}'} 38 | 39 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | creator: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List 3 | 4 | 5 | # article dakhele user disply 6 | class Article(BaseModel): 7 | title: str 8 | content: str 9 | published: bool 10 | 11 | class Config: 12 | orm_mode = True 13 | 14 | 15 | class UserBase(BaseModel): 16 | username: str 17 | password: str 18 | email: str 19 | 20 | 21 | class UserDisplay(BaseModel): 22 | username: str 23 | email: str 24 | items: List[Article] 25 | 26 | class Config: 27 | orm_mode = True 28 | 29 | 30 | # user dakhele article display 31 | class User(BaseModel): 32 | id: int 33 | username: str 34 | 35 | class Config: 36 | orm_mode = True 37 | 38 | 39 | class ArticleBase(BaseModel): 40 | title: str 41 | content: str 42 | published: bool 43 | creator_id: int 44 | 45 | 46 | class ArticleDisplay(BaseModel): 47 | title: str 48 | content: str 49 | published: bool 50 | user: User 51 | 52 | class Config: 53 | orm_mode = True 54 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/db_post.py: -------------------------------------------------------------------------------- 1 | from db.models import Post 2 | from schemas import PostBase 3 | from sqlalchemy.orm import Session 4 | import datetime 5 | from fastapi.exceptions import HTTPException 6 | from fastapi import status 7 | 8 | 9 | def create_post(request: PostBase, db: Session): 10 | new_post = Post( 11 | image_url=request.image_url, 12 | image_url_type=request.image_url_type, 13 | caption=request.caption, 14 | timestamp=datetime.datetime.now(), 15 | user_id=request.creator_id 16 | ) 17 | db.add(new_post) 18 | db.commit() 19 | db.refresh(new_post) 20 | return new_post 21 | 22 | 23 | def get_all_posts(db: Session): 24 | return db.query(Post).all() 25 | 26 | 27 | def delete_post(id: int, user_id: int, db: Session): 28 | post = db.query(Post).filter(Post.id == id).first() 29 | if not post: 30 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) 31 | 32 | if post.user_id != user_id: 33 | raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) 34 | 35 | db.delete(post) 36 | db.commit() 37 | return "OK" 38 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | from fastapi.staticfiles import StaticFiles 5 | 6 | from router import blog_get, blog_post, user,article,product, file 7 | from auth import authentication 8 | from db import models 9 | from db.database import engine 10 | from exceptions import EmailNotValid 11 | 12 | 13 | app = FastAPI() 14 | app.include_router(blog_get.router) 15 | app.include_router(blog_post.router) 16 | app.include_router(user.router) 17 | app.include_router(article.router) 18 | app.include_router(product.router) 19 | app.include_router(authentication.router) 20 | app.include_router(file.router) 21 | 22 | app.mount('/files', StaticFiles(directory='files'), name='files') 23 | 24 | models.Base.metadata.create_all(engine) 25 | 26 | @app.get('/') 27 | def hello(): 28 | return 'hello world' 29 | 30 | 31 | @app.exception_handler(EmailNotValid) 32 | def email_not_valid(request: Request, exc: EmailNotValid): 33 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status 2 | from fastapi.requests import Request 3 | from fastapi.responses import JSONResponse 4 | from fastapi.staticfiles import StaticFiles 5 | 6 | from router import blog_get, blog_post, user,article,product, file 7 | from auth import authentication 8 | from db import models 9 | from db.database import engine 10 | from exceptions import EmailNotValid 11 | 12 | 13 | app = FastAPI() 14 | app.include_router(blog_get.router) 15 | app.include_router(blog_post.router) 16 | app.include_router(user.router) 17 | app.include_router(article.router) 18 | app.include_router(product.router) 19 | app.include_router(authentication.router) 20 | app.include_router(file.router) 21 | 22 | app.mount('/files', StaticFiles(directory='files'), name='files') 23 | 24 | models.Base.metadata.create_all(engine) 25 | 26 | @app.get('/') 27 | def hello(): 28 | return 'hello world' 29 | 30 | 31 | @app.exception_handler(EmailNotValid) 32 | def email_not_valid(request: Request, exc: EmailNotValid): 33 | return JSONResponse(content=str(exc), status_code=status.HTTP_400_BAD_REQUEST) -------------------------------------------------------------------------------- /32. قسمت پایانی/.idea/dataSources.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | sqlite.xerial 6 | true 7 | org.sqlite.JDBC 8 | jdbc:sqlite:D:\Youtube\FastApi\Part_30\Files\Instagram.db 9 | $ProjectFileDir$ 10 | 11 | 12 | file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.38.0/sqlite-jdbc-3.38.0.jar 13 | 14 | 15 | file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.36.0.3/sqlite-jdbc-3.36.0.3.jar 16 | 17 | 18 | file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.34.0/sqlite-jdbc-3.34.0.jar 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(db: Session, request: UserBase): 8 | user = DbUser( 9 | username=request.username, 10 | email=request.email, 11 | password=Hash.bcrypt(request.password) 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user 17 | 18 | 19 | def get_all_users(db:Session): 20 | return db.query(DbUser).all() 21 | 22 | 23 | def get_user(id, db:Session): 24 | return db.query(DbUser).filter(DbUser.id == id).first() 25 | 26 | 27 | def delete_user(id, db:Session): 28 | user = get_user(id, db) 29 | db.delete(user) 30 | db.commit() 31 | return 'ok' 32 | 33 | 34 | def update_user(id, db:Session, request:UserBase): 35 | user = db.query(DbUser).filter(DbUser.id==id) 36 | user.update({ 37 | DbUser.username: request.username, 38 | DbUser.email: request.email, 39 | DbUser.password: Hash.bcrypt(request.password), 40 | }) 41 | db.commit() 42 | return 'ok' -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(db: Session, request: UserBase): 8 | user = DbUser( 9 | username=request.username, 10 | email=request.email, 11 | password=Hash.bcrypt(request.password) 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user 17 | 18 | 19 | def get_all_users(db:Session): 20 | return db.query(DbUser).all() 21 | 22 | 23 | def get_user(id, db:Session): 24 | return db.query(DbUser).filter(DbUser.id == id).first() 25 | 26 | 27 | def delete_user(id, db:Session): 28 | user = get_user(id, db) 29 | db.delete(user) 30 | db.commit() 31 | return 'ok' 32 | 33 | 34 | def update_user(id, db:Session, request:UserBase): 35 | user = db.query(DbUser).filter(DbUser.id==id) 36 | user.update({ 37 | DbUser.username: request.username, 38 | DbUser.email: request.email, 39 | DbUser.password: Hash.bcrypt(request.password), 40 | }) 41 | db.commit() 42 | return 'ok' -------------------------------------------------------------------------------- /32. قسمت پایانی/routers/comment.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status, UploadFile, File 2 | from sqlalchemy.orm import Session 3 | from fastapi.exceptions import HTTPException 4 | from db.database import get_db 5 | from db import db_comment 6 | from typing import List 7 | from schemas import CommentDisplay, CommentBase, UserAuth 8 | from auth import oauth2 9 | 10 | router = APIRouter(prefix="/comment", tags=['comment']) 11 | 12 | 13 | @router.post('/create_comment', response_model=CommentDisplay) 14 | def create_post(request: CommentBase, db: Session = Depends(get_db), 15 | current_user:UserAuth = Depends(oauth2.get_current_user)): 16 | return db_comment.create_comment(request, db) 17 | 18 | 19 | @router.post('/delete/{id}') 20 | def delete_comment(id: int, db: Session = Depends(get_db), 21 | current_user:UserAuth = Depends(oauth2.get_current_user)): 22 | return db_comment.delete_comment(id=id, db=db, user_id=current_user.id) 23 | 24 | 25 | @router.get("/{id}", response_model=List[CommentDisplay]) 26 | def get_comments(id:int, db: Session = Depends(get_db)): 27 | return db_comment.get_comments_by_post_id(id=id, db=db) 28 | 29 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | 6 | 7 | def create_user(db: Session, request: UserBase): 8 | user = DbUser( 9 | username=request.username, 10 | email=request.email, 11 | password=Hash.bcrypt(request.password) 12 | ) 13 | db.add(user) 14 | db.commit() 15 | db.refresh(user) 16 | return user 17 | 18 | 19 | def get_all_users(db:Session): 20 | return db.query(DbUser).all() 21 | 22 | 23 | def get_user(id, db:Session): 24 | return db.query(DbUser).filter(DbUser.id == id).first() 25 | 26 | 27 | def delete_user(id, db:Session): 28 | user = get_user(id, db) 29 | db.delete(user) 30 | db.commit() 31 | return 'ok' 32 | 33 | 34 | def update_user(id, db:Session, request:UserBase): 35 | user = db.query(DbUser).filter(DbUser.id==id) 36 | user.update({ 37 | DbUser.username: request.username, 38 | DbUser.email: request.email, 39 | DbUser.password: Hash.bcrypt(request.password), 40 | }) 41 | db.commit() 42 | return 'ok' -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /32. قسمت پایانی/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | router = APIRouter(tags=['authentication']) 11 | 12 | 13 | @router.post('/token') 14 | def get_token(request: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): 15 | user = db.query(models.User).filter(models.User.username == request.username).first() 16 | if not user: 17 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 18 | 19 | if not Hash.verify(user.password, request.password): 20 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 21 | 22 | access_token = oauth2.create_access_token(data={'sub': request.username}) 23 | 24 | return { 25 | 'access_token': access_token, 26 | 'type_token': 'bearer', 27 | 'userID': user.id, 28 | 'username': user.username 29 | } 30 | -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/router/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body, Path, Depends 2 | from pydantic import BaseModel 3 | from typing import Optional, List, Dict 4 | from schemas import UserBase, UserDisplay 5 | from db import db_user 6 | from db.database import get_db 7 | 8 | router = APIRouter(prefix='/user', tags=['user']) 9 | 10 | 11 | # create user 12 | @router.post('/', response_model=UserDisplay) 13 | def create_user(user: UserBase, db=Depends(get_db)): 14 | return db_user.create_user(db, user) 15 | 16 | 17 | # read All user 18 | @router.get('/', response_model=List[UserDisplay]) 19 | def get_all_users(db=Depends(get_db)): 20 | return db_user.get_all_users(db) 21 | 22 | 23 | # read user 24 | @router.get('/{id}', response_model=UserDisplay) 25 | def get_user(id:int, db=Depends(get_db)): 26 | return db_user.get_user(id, db) 27 | 28 | 29 | # update user 30 | @router.post('/update/{id}') 31 | def update_user(id:int, user: UserBase, db=Depends(get_db)): 32 | return db_user.update_user(id, db, user) 33 | 34 | 35 | # delete user 36 | @router.get('/delete/{id}') 37 | def delete_user(id:int, db=Depends(get_db)): 38 | return db_user.delete_user(id, db) 39 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/db_comment.py: -------------------------------------------------------------------------------- 1 | from db.models import Comment 2 | from schemas import CommentBase 3 | from sqlalchemy.orm import Session 4 | import datetime 5 | from fastapi.exceptions import HTTPException 6 | from fastapi import status 7 | 8 | 9 | def create_comment(request: CommentBase, db: Session): 10 | new_comment = Comment( 11 | text=request.text, 12 | user_id=request.user_id, 13 | post_id=request.post_id, 14 | timestamp=datetime.datetime.now(), 15 | ) 16 | db.add(new_comment) 17 | db.commit() 18 | db.refresh(new_comment) 19 | return new_comment 20 | 21 | 22 | def get_comments_by_post_id(id: int, db: Session): 23 | return db.query(Comment).filter(Comment.post_id == id).all() 24 | 25 | 26 | def delete_comment(id: int, user_id: int, db: Session): 27 | comment = db.query(Comment).filter(Comment.id == id).first() 28 | if not comment: 29 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) 30 | 31 | if comment.user_id == user_id or comment.post.user.id == user_id: 32 | db.delete(comment) 33 | db.commit() 34 | return "OK" 35 | 36 | raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) 37 | 38 | 39 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/client.py: -------------------------------------------------------------------------------- 1 | html = """ 2 | 3 | 4 | 5 | Chat 6 | 7 | 8 |

WebSocket Chat

9 |
10 | 11 | 12 |
13 | 15 | 31 | 32 | 33 | """ -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/auth/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status 2 | from fastapi.exceptions import HTTPException 3 | from fastapi.security.oauth2 import OAuth2PasswordRequestForm 4 | from sqlalchemy.orm.session import Session 5 | from db import models 6 | from db.database import get_db 7 | from db.hash import Hash 8 | from auth import oauth2 9 | 10 | 11 | router = APIRouter(tags=['authentication']) 12 | 13 | 14 | @router.post('/token') 15 | def get_token(request: OAuth2PasswordRequestForm=Depends(), db: Session= Depends(get_db)): 16 | user = db.query(models.DbUser).filter(models.DbUser.username == request.username).first() 17 | if not user: 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid credential') 19 | 20 | if not Hash.verify(user.password, request.password): 21 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='invalid password') 22 | 23 | access_token = oauth2.create_access_token(data={'sub': request.username}) 24 | 25 | return { 26 | 'access_token': access_token, 27 | 'type_token': 'bearer', 28 | 'userID': user.id, 29 | 'username': user.username 30 | } 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | 30 | def delete_user(id, db:Session): 31 | user = get_user(id, db) 32 | db.delete(user) 33 | db.commit() 34 | return 'ok' 35 | 36 | 37 | def update_user(id, db:Session, request:UserBase): 38 | user = db.query(DbUser).filter(DbUser.id==id) 39 | user.update({ 40 | DbUser.username: request.username, 41 | DbUser.email: request.email, 42 | DbUser.password: Hash.bcrypt(request.password), 43 | }) 44 | db.commit() 45 | return 'ok' -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | 30 | def delete_user(id, db:Session): 31 | user = get_user(id, db) 32 | db.delete(user) 33 | db.commit() 34 | return 'ok' 35 | 36 | 37 | def update_user(id, db:Session, request:UserBase): 38 | user = db.query(DbUser).filter(DbUser.id==id) 39 | user.update({ 40 | DbUser.username: request.username, 41 | DbUser.email: request.email, 42 | DbUser.password: Hash.bcrypt(request.password), 43 | }) 44 | db.commit() 45 | return 'ok' -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | 30 | def delete_user(id, db:Session): 31 | user = get_user(id, db) 32 | db.delete(user) 33 | db.commit() 34 | return 'ok' 35 | 36 | 37 | def update_user(id, db:Session, request:UserBase): 38 | user = db.query(DbUser).filter(DbUser.id==id) 39 | user.update({ 40 | DbUser.username: request.username, 41 | DbUser.email: request.email, 42 | DbUser.password: Hash.bcrypt(request.password), 43 | }) 44 | db.commit() 45 | return 'ok' -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | 30 | def delete_user(id, db:Session): 31 | user = get_user(id, db) 32 | db.delete(user) 33 | db.commit() 34 | return 'ok' 35 | 36 | 37 | def update_user(id, db:Session, request:UserBase): 38 | user = db.query(DbUser).filter(DbUser.id==id) 39 | user.update({ 40 | DbUser.username: request.username, 41 | DbUser.email: request.email, 42 | DbUser.password: Hash.bcrypt(request.password), 43 | }) 44 | db.commit() 45 | return 'ok' -------------------------------------------------------------------------------- /04.قسمت چهارم - Status Code/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | app = FastAPI() 6 | 7 | 8 | @app.get('/') 9 | def hello(): 10 | return 'hello world' 11 | 12 | 13 | class TypeBlogs(str, Enum): 14 | Mesal1 = 'mesal1' 15 | Mesal2 = 'mesal2' 16 | Mesal3 = 'mesal3' 17 | 18 | 19 | @app.get('/blog/{id}/comments/{comment_id}') 20 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 21 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 22 | 23 | 24 | @app.get('/blog/all') 25 | def get_blogs(page: Optional[int] = None, page_size: str = None): 26 | return {"message": f"{page=} -- {page_size=}"} 27 | 28 | 29 | @app.get('/blog/type/{type}') 30 | def get_type_blog(type: TypeBlogs): 31 | return {'message': f'blog type is {type}'} 32 | 33 | 34 | # @app.get('/blog/all') 35 | # def get_blogs(): 36 | # return {'message':f'all blogs'} 37 | 38 | @app.get('/blog/{id}', status_code=status.HTTP_200_OK) 39 | def get_blog(id: int, response:Response): 40 | if id > 5: 41 | response.status_code = status.HTTP_404_NOT_FOUND 42 | return {"Error": f"Blog {id} Not Found !"} 43 | return {'message': f'blog {id}'} 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /32. قسمت پایانی/db/models.py: -------------------------------------------------------------------------------- 1 | from db.database import Base 2 | from sqlalchemy import Column, Integer, String, DateTime, ForeignKey 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class User(Base): 7 | __tablename__ = "user" 8 | 9 | id = Column(Integer, index=True, primary_key=True) 10 | username = Column(String) 11 | password = Column(String) 12 | email = Column(String) 13 | items = relationship("Post", back_populates='user') 14 | 15 | 16 | class Post(Base): 17 | __tablename__ = "post" 18 | id = Column(Integer, index=True, primary_key=True) 19 | image_url = Column(String) 20 | image_url_type = Column(String) 21 | caption = Column(String) 22 | timestamp = Column(DateTime) 23 | user_id = Column(Integer, ForeignKey('user.id')) 24 | user = relationship("User", back_populates='items') 25 | comments = relationship("Comment", back_populates='post') 26 | 27 | 28 | class Comment(Base): 29 | __tablename__ = "comment" 30 | id = Column(Integer, index=True, primary_key=True) 31 | text = Column(String) 32 | user_id = Column(Integer, ForeignKey('user.id')) 33 | post_id = Column(Integer, ForeignKey('post.id')) 34 | timestamp = Column(DateTime) 35 | user = relationship("User") 36 | post = relationship("Post", back_populates='comments') 37 | -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /23. قسمت بیست و سوم - Download File - Static File/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /26. قسمت بیست و ششم - WebSocket - Background Tasks/db/db_user.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm.session import Session 2 | from schemas import UserBase 3 | from db.models import DbUser 4 | from db.hash import Hash 5 | from exceptions import EmailNotValid 6 | 7 | 8 | def create_user(db: Session, request: UserBase): 9 | if "@" not in request.email: 10 | raise EmailNotValid('Email Not Valid !') 11 | user = DbUser( 12 | username=request.username, 13 | email=request.email, 14 | password=Hash.bcrypt(request.password) 15 | ) 16 | db.add(user) 17 | db.commit() 18 | db.refresh(user) 19 | return user 20 | 21 | 22 | def get_all_users(db:Session): 23 | return db.query(DbUser).all() 24 | 25 | 26 | def get_user(id, db:Session): 27 | return db.query(DbUser).filter(DbUser.id == id).first() 28 | 29 | def get_user_by_username(username, db:Session): 30 | return db.query(DbUser).filter(DbUser.username == username).first() 31 | 32 | def delete_user(id, db:Session): 33 | user = get_user(id, db) 34 | db.delete(user) 35 | db.commit() 36 | return 'ok' 37 | 38 | 39 | def update_user(id, db:Session, request:UserBase): 40 | user = db.query(DbUser).filter(DbUser.id==id) 41 | user.update({ 42 | DbUser.username: request.username, 43 | DbUser.email: request.email, 44 | DbUser.password: Hash.bcrypt(request.password), 45 | }) 46 | db.commit() 47 | return 'ok' -------------------------------------------------------------------------------- /32. قسمت پایانی/schemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from datetime import datetime 3 | 4 | from db.models import Post 5 | 6 | 7 | class UserBase(BaseModel): 8 | username: str 9 | email: str 10 | password: str 11 | 12 | 13 | class UserDisplay(BaseModel): 14 | username: str 15 | email: str 16 | 17 | class Config: 18 | from_attributes = True 19 | 20 | 21 | class User(BaseModel): 22 | username: str 23 | 24 | class Config: 25 | from_attributes = True 26 | 27 | 28 | class CommentBase(BaseModel): 29 | text: str 30 | timestamp: datetime 31 | user_id: int 32 | post_id: int 33 | 34 | 35 | class CommentDisplay(BaseModel): 36 | id: int 37 | user: User 38 | post_id: int 39 | timestamp: datetime 40 | text: str 41 | 42 | class Config: 43 | from_attributes = True 44 | 45 | 46 | class PostBase(BaseModel): 47 | image_url: str 48 | image_url_type: str 49 | caption: str 50 | creator_id: int 51 | 52 | 53 | class PostDisplay(BaseModel): 54 | id: int 55 | image_url: str 56 | image_url_type: str 57 | caption: str 58 | timestamp: datetime 59 | user: User 60 | comments: list[CommentDisplay] 61 | 62 | class Config: 63 | from_attributes = True 64 | 65 | 66 | class UserAuth(BaseModel): 67 | id: int 68 | username: str 69 | email: str 70 | 71 | class Config: 72 | from_attributes = True 73 | -------------------------------------------------------------------------------- /09.قسمت نهم - Body Validator/router/blog_post.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Query, Body 2 | from pydantic import BaseModel 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class BlogModel(BaseModel): 9 | title: str 10 | content: str 11 | nb_comments: int 12 | published: Optional[bool] 13 | 14 | 15 | @router.post('/new/{id}') 16 | def create_blog(blog: BlogModel, id: int, version: int = 1): 17 | return {"message": 'OK', "data": blog, "id": id, 'version': version} 18 | 19 | 20 | @router.post('/new/{id}/comment') 21 | def create_comment(id: int, blog: BlogModel, 22 | comment_id: int = Query(None, 23 | title='Title Text !', 24 | description='Description Text !', 25 | alias='CommentID', 26 | deprecated=True 27 | ), 28 | content: str = Body(..., 29 | min_length=10, 30 | max_length=20, 31 | regex='^[A-Z].*', 32 | ) 33 | ): 34 | return { 35 | 'blog': blog, 36 | 'id': id, 37 | 'comment_id': comment_id, 38 | 'content': content 39 | } 40 | -------------------------------------------------------------------------------- /06.قسمت ششم - Router/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /07.قسمت هفتم - Method Post/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /08.قسمت هشتم - Query MetaData/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /09.قسمت نهم - Body Validator/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /13.قسمت سیزدهم - Create User/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /16.قسمت شانزدهم - Api Article/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /17.قسمت هفدهم - Error Handler/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /18.قسمت هجدهم - Custom Response/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /20. قسمت بیستم - Authentication/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /11.قسمت یازدهم - Complex SubTypes/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /14.قسمت چهاردهم - Read Update Delete User/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /21. قسمت بیست و یکم - Verify user Token/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /22. قسمت بیست و دوم - File - UploadFile/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /24. قسمت بیست و چهارم - Async - Await/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /12.قسمت دوازدهم - Database - ORM Sqlalchemy/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /15.قسمت پانزدهم - Relationship - Table Article/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /19.قسمت نوزدهم - Header - Cookie - Form Data/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /25. قسمت بیست و پنجم - MiddleWare - Error CORS/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} -------------------------------------------------------------------------------- /10.قسمت دهم - integer Validators, Multiple Value/router/blog_get.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, status, Response 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | router = APIRouter(prefix='/blog', tags=['blog']) 6 | 7 | 8 | class TypeBlogs(str, Enum): 9 | Mesal1 = 'mesal1' 10 | Mesal2 = 'mesal2' 11 | Mesal3 = 'mesal3' 12 | 13 | 14 | @router.get('/{id}/comments/{comment_id}', tags=['comment']) 15 | def get_comment(id: int, comment_id: int, valid: bool = True, username: Optional[str] = None): 16 | return {"message": f"blog id {id} comment id {comment_id} {valid=} {username=}"} 17 | 18 | 19 | @router.get('/all') 20 | def get_blogs(page: Optional[int] = None, page_size: str = None): 21 | return {"message": f"{page=} -- {page_size=}"} 22 | 23 | 24 | @router.get('/type/{type}') 25 | def get_type_blog(type: TypeBlogs): 26 | return {'message': f'blog type is {type}'} 27 | 28 | 29 | # @app.get('/blog/all') 30 | # def get_blogs(): 31 | # return {'message':f'all blogs'} 32 | 33 | @router.get('/{id}', status_code=status.HTTP_200_OK, summary='daryaft blog !', response_description='id blog darkhasti !') 34 | def get_blog(id: int, response:Response): 35 | 36 | """ 37 | in api baraye daryaft blog hastesh ! 38 | 39 | - **id** baraye daryaft id blog 40 | 41 | """ 42 | 43 | if id > 5: 44 | response.status_code = status.HTTP_404_NOT_FOUND 45 | return {"Error": f"Blog {id} Not Found !"} 46 | return {'message': f'blog {id}'} --------------------------------------------------------------------------------