Skip to content

Commit e7d4266

Browse files
committed
SQLModel added
1 parent 5847cd6 commit e7d4266

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+2086
-4
lines changed

FastAPIMongoEngineGraphQL/setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from setuptools import setup
22

33
setup(
4-
name='FastAPIMongoEngine',
4+
name='FastAPIMongoEngineGraphQL',
55
version='0.0.1',
66
author='scionoftech',
7-
description='FastAPIMongoEngine is a simple Python API Application',
7+
description='FastAPIMongoEngineGraphQL is a simple Python API Application',
88
platforms='any',
99
install_requires=[
1010
'fastapi',

FastAPISQLAlchamyGraphQL/setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from setuptools import setup
22

33
setup(
4-
name='FastAPISQLAlchemy',
4+
name='FastAPISQLAlchemyGraphQL',
55
version='0.0.1',
66
author='scionoftech',
7-
description='FastAPISQLAlchemy is a simple Python API Application',
7+
description='FastAPISQLAlchemyGraphQL is a simple Python API Application',
88
platforms='any',
99
install_requires=[
1010
'fastapi',

FastAPISQLModel/Dockerfile

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
2+
3+
COPY app /app
4+
5+
RUN ls -l
6+
7+
# RUN apt-get install python3-psycopg2
8+
9+
RUN pip install -r ./requirements.txt

FastAPISQLModel/Jenkinsfile

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
pipeline {
2+
agent any
3+
stages {
4+
stage('Clone Repository') {
5+
/* Cloning the repository to our workspace */
6+
steps {
7+
checkout scm
8+
}
9+
}
10+
stage('Build Image') {
11+
steps {
12+
sh 'sudo docker-compose build'
13+
}
14+
}
15+
stage('Run Container') {
16+
steps {
17+
sh 'sudo docker-compose up -d'
18+
}
19+
}
20+
}
21+
}

FastAPISQLModel/README.md

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# FastAPI-SQLModel
2+
3+
FastAPI-SQLModel is a Python API Application with FastAPI, JWT Authentication,
4+
Postgresql, SQLModel, Docker and Jenkins Pipeline
5+
6+
## Features
7+
8+
* Full **Docker** integration (Docker based).
9+
* **Production ready** Python web server using Uvicorn and Gunicorn.
10+
* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend:
11+
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
12+
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
13+
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
14+
* **Short**: Minimize code duplication. Multiple features from each parameter declaration.
15+
* **Robust**: Get production-ready code. With automatic interactive documentation.
16+
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
17+
* <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Many other features**</a> including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
18+
* **Secure password** hashing by default.
19+
* **JWT token** authentication.
20+
* **SQLModel** new SQL ORM.
21+
* Basic starting models for users (modify and remove as you need).
22+
* **CORS** (Cross Origin Resource Sharing).
23+
* Load balancing between frontend and backend with **Nginx**, so you can have both under the same domain, separated by path, but served by different containers.
24+
* Let's Encrypt **HTTPS** certificates automatic generation.
25+
26+
27+
## How to use it
28+
29+
**psycopg2**
30+
31+
psycopg2 is postgresql adapter for sqlalchamy this can't be installed directly
32+
in linux using pip, use below command to install
33+
34+
```bash
35+
sudo apt-get install python3-psycopg2
36+
sudo apt-get install libpq-dev python3-dev
37+
```
38+
39+
## JWT token authentication
40+
41+
JWT-Signature using RSA256 algorithm.
42+
43+
You can generate a 2048-bit RSA key pair with the following commands:
44+
45+
```bash
46+
openssl genpkey -algorithm RSA -out rsa_private.pem -pkeyopt rsa_keygen_bits:2048
47+
openssl rsa -in rsa_private.pem -pubout -out rsa_public.pem
48+
```
49+
50+
## Create SSL Certificates using Certbot
51+
52+
Generate SSL cerificates from trusted thirdparty or openssl
53+
54+
For Open SSL use Certbot (Let'sencrypt)
55+
```bash
56+
sudo apt-get update
57+
sudo apt-get install software-properties-common
58+
sudo add-apt-repository universe
59+
sudo add-apt-repository ppa:certbot/certbot
60+
sudo apt-get install certbot python3-certbot-nginx
61+
62+
sudo certbot -d example.com certonly
63+
```
64+
certificates will be found in "/etc/letsencrypt/live/example.com/"
65+
66+
Generate a set of 4096-bit diffie-hellman parameters to improve security for some types of ciphers.
67+
```bash
68+
sudo mkdir -p /etc/nginx/ssl
69+
sudo openssl dhparam -out /etc/nginx/ssl/dhp-4096.pem 4096
70+
```
71+
72+
## Deployment
73+
74+
FastAPI Backend can be deployed using docker. Use below docker image for deployment.
75+
76+
tiangolo/uvicorn-gunicorn-fastapi-docker - [Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker)
77+
78+
79+
#### References
80+
81+
The fundamental repositories:
82+
- FastAPI - [FastAPI framework, high performance, easy to learn, fast to code, ready for production](https://fastapi.tiangolo.com/)
83+
- full-stack-fastapi-postgresql - [Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.](https://github.com/tiangolo/full-stack-fastapi-postgresql)
84+
- blog-posts - [Build a web API from scratch with FastAPI - the workshop](https://github.com/tiangolo/blog-posts/tree/master/pyconby-web-api-from-scratch-with-fastapi)
85+
- uvicorn - [The lightning-fast ASGI server.](https://www.uvicorn.org/deployment/)
86+
- tiangolo/uvicorn-gunicorn-fastapi-docker - [Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker)
87+
- sqlmodel - [SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust.](https://sqlmodel.tiangolo.com/)
88+
-

FastAPISQLModel/app/__init__.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from . import auth
2+
from . import conf
3+
from . import controller
4+
from . import crud
5+
from . import db
6+
from . import logs
7+
from . import routes
8+
from . import util
Binary file not shown.
Binary file not shown.

FastAPISQLModel/app/auth/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .token import access_token
2+
Binary file not shown.
Binary file not shown.

FastAPISQLModel/app/auth/token.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from datetime import timedelta, datetime
2+
import os
3+
from jwt import (
4+
JWT,
5+
jwk_from_pem,
6+
)
7+
from typing import Dict
8+
from pathlib import Path
9+
from jwt.utils import get_int_from_datetime
10+
from app.conf import EmailSettings
11+
12+
13+
def get_root() -> str:
14+
return str(Path(__file__).parent.parent) + os.sep
15+
16+
17+
class AccessToken:
18+
""" Access Token Util Class"""
19+
20+
def __init__(self):
21+
22+
self.__instance = JWT()
23+
self.__algorithm = "RS256"
24+
with open(get_root() + 'auth' + os.sep + 'jwtRS256_private.pem',
25+
'rb') as fh:
26+
self.__signing_key = jwk_from_pem(fh.read())
27+
with open(get_root() + 'auth' + os.sep + 'jwtRS256_public.pem',
28+
'rb') as fh:
29+
self.__verifying_key = jwk_from_pem(fh.read())
30+
31+
def create_access_token(self, *, data: dict,
32+
expires_delta: timedelta = None) -> str:
33+
"""Create Access Token Using JWT with RSA256 Encryption"""
34+
to_encode = data.copy()
35+
if expires_delta:
36+
expire = datetime.utcnow() + expires_delta
37+
else:
38+
expire = datetime.utcnow() + timedelta(minutes=15)
39+
to_encode.update({"ist": get_int_from_datetime(datetime.utcnow())})
40+
to_encode.update({"exp": get_int_from_datetime(expire)})
41+
encoded_jwt = self.__instance.encode(to_encode, self.__signing_key,
42+
self.__algorithm)
43+
return encoded_jwt
44+
45+
def decode_access_token(self, *, token: str) -> Dict:
46+
""" Decode Access Token """
47+
return self.__instance.decode(token, self.__verifying_key,
48+
do_time_check=False)
49+
50+
def generate_password_reset_token(self, email: str) -> str:
51+
""" Generate Access Token for password Reset email"""
52+
delta = timedelta(hours=EmailSettings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
53+
now = datetime.utcnow()
54+
expires = now + delta
55+
encoded_jwt = self.__instance.encode(
56+
{"exp": get_int_from_datetime(expires),
57+
"ist": get_int_from_datetime(now), "sub": email},
58+
self.__signing_key,
59+
alg=self.__algorithm,
60+
)
61+
return encoded_jwt
62+
63+
def verify_password_reset_token(self, token: str) -> Dict:
64+
""" Decode Access Token """
65+
return self.__instance.decode(token, self.__verifying_key,
66+
do_time_check=False)
67+
68+
69+
access_token = AccessToken()

FastAPISQLModel/app/conf/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .config import ProjectSettings
2+
from .config import DBSettings
3+
from .config import EmailSettings
Binary file not shown.
Binary file not shown.

FastAPISQLModel/app/conf/conf.json

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"PROJECT_CONF": {
3+
"PROJECT_NAME": "FastAPISQLModel",
4+
"PROJECT_DESCRIPTION": "A Simple Application to demonstrate SQLModel with FastAPI",
5+
"API_VERSION": "1.0.0",
6+
"API_VERSION_PATH": "/api/v1",
7+
"ACCESS_TOKEN_EXPIRE_MINUTES": 300,
8+
"SESSION_TOKEN_EXPIRE_SECONDS": 43200,
9+
"SERVER_NAME": "SampleBackEndPROD",
10+
"SERVER_HOST": "https://localhost:8088/api/v1/",
11+
"BACKEND_CORS_ORIGINS": [
12+
"*"
13+
]
14+
},
15+
"EMAIL_CONF": {
16+
"EMAIL_RESET_TOKEN_EXPIRE_HOURS": 15,
17+
"EMAIL_ID": "",
18+
"EMAIL_PASSWORD": "",
19+
"SMTP_SERVER": "",
20+
"SMTP_PORT": 465
21+
},
22+
"DATABASE_CONF": {
23+
"DATABASE": "postgresql",
24+
"POSTGRES_SERVER": "localhost",
25+
"POSTGRES_PORT": "5432",
26+
"POSTGRES_USER": "",
27+
"POSTGRES_PASSWORD": "",
28+
"POSTGRES_DB": "postgres",
29+
"POSTGRES_ADAPTER": "psycopg2"
30+
}
31+
}

FastAPISQLModel/app/conf/config.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import json
2+
import os
3+
from pathlib import Path
4+
from typing import Dict
5+
6+
7+
def get_config() -> Dict:
8+
""" Get Config Json"""
9+
with open(str(Path(
10+
__file__).parent.parent) + os.sep + "conf" + os.sep + "conf.json",
11+
'r') as fp:
12+
return json.load(fp)
13+
14+
15+
class EmailSettings:
16+
""" Email Settings"""
17+
__DATA = get_config()['EMAIL_CONF']
18+
EMAIL_RESET_TOKEN_EXPIRE_HOURS = __DATA["EMAIL_RESET_TOKEN_EXPIRE_HOURS"]
19+
EMAIL_ID = __DATA["EMAIL_ID"]
20+
EMAIL_PASSWORD = __DATA["EMAIL_PASSWORD"]
21+
SMTP_SERVER = __DATA["SMTP_SERVER"]
22+
SMTP_PORT = __DATA["SMTP_PORT"]
23+
24+
25+
class DBSettings:
26+
""" Database Configuration"""
27+
__DATA = get_config()['DATABASE_CONF']
28+
# 'postgres+psycopg2://USER:PASSWORD@localhost:5432/DATABASE'
29+
SQLALCHEMY_DATABASE_URL = __DATA["DATABASE"] + '+' + __DATA[
30+
"POSTGRES_ADAPTER"] + '://' + \
31+
__DATA["POSTGRES_USER"] + ':' + __DATA[
32+
"POSTGRES_PASSWORD"] + '@' + __DATA[
33+
"POSTGRES_SERVER"] + ':' + \
34+
__DATA["POSTGRES_PORT"] + '/' + __DATA[
35+
"POSTGRES_DB"]
36+
37+
38+
class ProjectSettings:
39+
""" Project Configuration"""
40+
__DATA = get_config()['PROJECT_CONF']
41+
PROJECT_NAME = __DATA["PROJECT_NAME"]
42+
PROJECT_DESCRIPTION = __DATA["PROJECT_DESCRIPTION"]
43+
API_VERSION = __DATA["API_VERSION"]
44+
API_VERSION_PATH = __DATA["API_VERSION_PATH"]
45+
SERVER_NAME = __DATA["SERVER_NAME"]
46+
SERVER_HOST = __DATA["SERVER_HOST"]
47+
BACKEND_CORS_ORIGINS = __DATA["BACKEND_CORS_ORIGINS"]
48+
ACCESS_TOKEN_EXPIRE_MINUTES = __DATA["ACCESS_TOKEN_EXPIRE_MINUTES"]
49+
SESSION_TOKEN_EXPIRE_SECONDS = __DATA["SESSION_TOKEN_EXPIRE_SECONDS"]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Binary file not shown.

FastAPISQLModel/app/crud/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .crud_base import (get_user, get_active_user,get_user_password)
2+
from .crud_users import crud_users
3+
from .crud_login import crud_login
4+
from .crud_articles import crud_articles
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)