Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pgsql 을 sqlite로 교체 #26

Merged
merged 2 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ __pycache__/
# C extensions
*.so


*.sqlite

# Distribution / packaging
.Python
build/
Expand Down
148 changes: 69 additions & 79 deletions core/sql_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import typing

import psycopg2
import sqlite3

from oauth.dto.user_dto import UserDto

Expand All @@ -12,51 +12,36 @@ def env(key):
return os.environ.get(key)


_HOST = env("AIT_DB_HOST")
_PORT = env("AIT_DB_PORT")
_USER = env("AIT_DB_USER")
_PW = env("AIT_DB_PW")
_DATABASE = env("AIT_DB_NAME")
_DIR = "./database.sqlite"
_IS_TEST = env("IS_TEST")

_IS_TEST = os.environ.get("IS_TEST")

if not _IS_TEST:
if _USER is None:
raise Exception("DB 접속 유저 이름이 설정되지 않았습니다")
if _PW is None:
raise Exception("DB 접속 암호가 설정되지 않았습니다")
if _DATABASE is None:
raise Exception("접속할 DB 이름을 설정하지 않았습니다")

_conn = psycopg2.connect(
host=_HOST,
dbname=_DATABASE,
user=_USER,
password=_PW,
port=_PORT,
) if not _IS_TEST else None
_conn = sqlite3.connect(_DIR) if not _IS_TEST else None


def check_and_create_table():
print("Checking Table...")
table = "account"
with _conn.cursor() as cmd:
cmd.execute(
"""
CREATE TABLE IF NOT EXISTS {} (
id SERIAL PRIMARY KEY,
"userId" character varying(20) NOT NULL UNIQUE,
password character varying(256) NOT NULL,
"jwtKey" character varying(128) NOT NULL,
"validState" character varying(20) NOT NULL,
state character varying(20) NOT NULL,
"registerTimestamp" timestamp without time zone NOT NULL,
"validTimestamp" timestamp without time zone,
email character varying(30)
)
""".format(table)
cmd = _conn.cursor()
cmd.execute(
"""
CREATE TABLE IF NOT EXISTS {} (
id SERIAL PRIMARY KEY,
"userId" character varying(20) NOT NULL UNIQUE,
password character varying(256) NOT NULL,
"jwtKey" character varying(128) NOT NULL,
"validState" character varying(20) NOT NULL,
state character varying(20) NOT NULL,
"registerTimestamp" timestamp without time zone NOT NULL,
"validTimestamp" timestamp without time zone,
email character varying(30)
)
_conn.commit()
""".format(
table
)
)
_conn.commit()
cmd.close()


def create_user(_id: str, encoded_pw: str) -> typing.Union[UserDto, None]:
Expand All @@ -65,55 +50,60 @@ def create_user(_id: str, encoded_pw: str) -> typing.Union[UserDto, None]:
valid_state = "NOT_VALID"
state = "ACTIVATE"
register_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with _conn.cursor() as cmd:
try:
cmd.execute(
"INSERT INTO {} ({}) VALUES ({})".format(
table,
'"userId", password, "jwtKey", "validState", state, "registerTimestamp"',
"'{}', '{}', '{}', '{}', '{}', '{}'".format(
_id,
encoded_pw,
jwt_key,
valid_state,
state,
register_timestamp,
),
)
cmd = _conn.cursor()
try:
cmd.execute(
"INSERT INTO {} ({}) VALUES ({})".format(
table,
'"userId", password, "jwtKey", "validState", state, "registerTimestamp"',
"'{}', '{}', '{}', '{}', '{}', '{}'".format(
_id,
encoded_pw,
jwt_key,
valid_state,
state,
register_timestamp,
),
)
user = find_user(_id)
_conn.commit()
return user
except:
return None
)
user = find_user(_id)
_conn.commit()
return user
except:
return None
finally:
cmd.close()


def find_user(_id: str) -> typing.Union[UserDto, None]:
table = "account"
with _conn.cursor() as cmd:
cmd.execute(
"SELECT * FROM {} WHERE \"userId\"='{}' limit 1".format(
table,
_id,
)
cmd = _conn.cursor()
cmd.execute(
"SELECT * FROM {} WHERE \"userId\"='{}' limit 1".format(
table,
_id,
)
rec = cmd.fetchone()
if rec is not None:
return UserDto(*rec)
return None
)
rec = cmd.fetchone()
cmd.close()
if rec is not None:
return UserDto(*rec)
return None


def delete_user(_id: str) -> bool:
table = "account"
with _conn.cursor() as cmd:
try:
cmd.execute(
'DELETE FROM {} WHERE "userId"={}'.format(
table,
_id,
)
cmd = _conn.cursor()
try:
cmd.execute(
'DELETE FROM {} WHERE "userId"={}'.format(
table,
_id,
)
_conn.commit()
return True
except:
return False
)
_conn.commit()
return True
except:
return False
finally:
cmd.close()
8 changes: 1 addition & 7 deletions environment_setup_full.bat
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ setlocal enabledelayedexpansion

echo "¸ðµç º¯¼ö¸¦ ¼³Á¤ÇÏ´Â ÇÁ·Î±×·¥ ÀÔ´Ï´Ù"
echo "°ü¸®ÀÚ¸¸ ¼öÇàÇÏ¸é µÇ´Â ÀÛ¾÷ÀÔ´Ï´Ù"
set /p user=AIT_DB_USER:
set /p pw=AIT_DB_PW:
set /p db=AIT_DB_NAME:
set /p salt=AIT_PW_SALT:
set /p pepper=AIT_PW_PEPPER:
set /p deepl_key=DEEPL_API_KEY:
Expand All @@ -31,10 +28,7 @@ set /p ipinfo_key=IPINFO_TOKEN:
set /p subway_key=SUBWAY_API_KEY:

echo setting environments...
:: »ç¿ëÀÚ ÀÔ·ÂÀ» ȯ°æ º¯¼ö¿¡ ÀúÀå
setx AIT_DB_USER %user%
setx AIT_DB_PW %pw%
setx AIT_DB_NAME %db%
:: »ç¿ëÀÚ ÀÔ·ÂÀ» ȯ°æ º¯¼ö¿¡ ÀúÀåsetx AIT_DB_USER %user%
setx AIT_PW_SALT %salt%
setx AIT_PW_PEPPER %pepper%
setx DEEPL_API_KEY %deepl_key%
Expand Down
1 change: 0 additions & 1 deletion requirements-deploy.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
fastapi
uvicorn
python-multipart
psycopg2
PyJWT
requests
beautifulsoup4
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ fastapi
uvicorn
pytest
python-multipart
psycopg2
python-dotenv
PyJWT
requests
Expand Down
Loading