ADD : .env

This commit is contained in:
2022-08-15 10:53:27 +07:00
parent 8dd498fe8d
commit d21fdea082
7 changed files with 643 additions and 131 deletions

View File

@@ -27,4 +27,7 @@ python-multipart==0.0.5
aiofiles==0.8.0 aiofiles==0.8.0
jinja2==3.1.0 jinja2==3.1.0
requests==2.28.1 requests==2.28.1
pytz==2019.3 pytz==2019.3
fastapi-pagination == 0.9.3
python_dotenv==0.20.0
pathlib==1.0.1

View File

@@ -114,3 +114,25 @@ class HistoryByUserModel(BaseModel):
# "key_find": "datetime" # "key_find": "datetime"
# } # }
# } # }
class StatisticalSpecialistModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
name: Union[str, None] = None
id: str = None
count: int = 0
class Config:
orm_mode = True
case_sensitive = True
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"name": "",
"id": "",
"count": 0,
}
}

View File

@@ -35,27 +35,28 @@ class DataPost(BaseModel):
class DataSmallPost(BaseModel): class DataSmallPost(BaseModel):
name: str name: str
level: str level: List[str]
class Point(BaseModel): class Point(BaseModel):
less10: Optional[int] = None less10: Optional[int] = 0
form10to20: Optional[int] = None form10to20: Optional[int] = 0
form20to30: Optional[int] = None form20to30: Optional[int] = 0
form30to40: Optional[int] = None form30to40: Optional[int] = 0
form40to50: Optional[int] = None form40to50: Optional[int] = 0
form50to60: Optional[int] = None form50to60: Optional[int] = 0
bigger60: Optional[int] = None bigger60: Optional[int] = 0
total: Optional[int] = None total: Optional[int] = 0
class PostModel(BaseModel): class PostModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id") id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
original_post: Union[str, None] = None original_post: Union[str, None] = None
translation_post: Union[str, None] = None translation_post: Union[str, None] = None
tag: List[str] = None
link: Union[str, None] = None link: Union[str, None] = None
is_active: bool is_active: bool
created_at: Optional[datetime] = None created_at: Optional[datetime] = datetime.now(tz=tz)
updated_at: Optional[datetime] = None updated_at: Optional[datetime] = None
specialist: str specialist: str
summary: str = None summary: str = None
@@ -73,6 +74,7 @@ class PostModel(BaseModel):
"original_post": "Joh111", "original_post": "Joh111",
"translation_post": "Doe11111", "translation_post": "Doe11111",
"link": "simple mortal111", "link": "simple mortal111",
"tag": "",
"is_active": False, "is_active": False,
"created_at": "07/20/22 02: 26: 54", "created_at": "07/20/22 02: 26: 54",
"specialist": "", "specialist": "",
@@ -117,10 +119,11 @@ class UpdatePostModel(BaseModel):
original_post: Union[str, None] = None original_post: Union[str, None] = None
translation_post: Union[str, None] = None translation_post: Union[str, None] = None
link: Union[str, None] = None link: Union[str, None] = None
tag: List[str] = None
is_active: bool is_active: bool
created_at: Optional[datetime] = datetime.now(tz=tz) created_at: Optional[datetime] = datetime.now(tz=tz)
updated_at: Optional[datetime] = None updated_at: Optional[datetime] = datetime.now(tz=tz)
specialist: str specialist: str = None
summary: str = None summary: str = None
data: List[DataPost] data: List[DataPost]
point: Point = None point: Point = None
@@ -133,6 +136,7 @@ class UpdatePostModel(BaseModel):
"original_post": "Joh111", "original_post": "Joh111",
"translation_post": "Doe11111", "translation_post": "Doe11111",
"link": "simple mortal111", "link": "simple mortal111",
"tag": "",
"is_active": False, "is_active": False,
"specialist": "", "specialist": "",
"summary": "", "summary": "",
@@ -178,7 +182,7 @@ class ShowPostModel(BaseModel):
translation_post: Optional[str] translation_post: Optional[str]
link: Optional[str] link: Optional[str]
is_active: Optional[str] is_active: Optional[str]
specialist: Optional[str] specialist: Optional[str] = None
summary: Optional[str] = None summary: Optional[str] = None
data: List[DataSmallPost] data: List[DataSmallPost]
point: Point = None point: Point = None

View File

@@ -4,7 +4,8 @@ from fastapi import (
status, status,
HTTPException HTTPException
) )
from bson import ObjectId from ..settings import *
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordRequestForm from fastapi.security import OAuth2PasswordRequestForm
@@ -29,6 +30,7 @@ from ..dependecies import (
create_access_token, create_access_token,
get_password_hash get_password_hash
) )
from bson.objectid import ObjectId
import re import re
import pytz import pytz
import datetime import datetime
@@ -125,17 +127,79 @@ async def get_key_find_view_by_username(token: str = None):
return all_user return all_user
@history.delete("/delete_user_history/", response_description="Delete history by user") @history.delete("/delete_user_history/{id}", response_description="Delete history by user")
async def delete_user(data: HistoryByUserModel, async def delete_user(id: str,
# current_user: UserModel = Depends(get_current_user) # current_user: UserModel = Depends(get_current_user)
token: str, token: str,
): ):
data_token = await get_current_user(token) data_token = await get_current_user(token)
user_name = data_token.get("user_name", None) user_name = data_token.get("user_name", None)
user_type = data_token.get("user_type", None) user_type = data_token.get("user_type", None)
print(ObjectId(id))
if user_name == None: if user_name == None:
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"}) return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
delete_result = await db["history"].delete_one({"_id": data.id}) delete_result = await db["history"].delete_one({"_id": ObjectId(id)})
delete = await db["history"].delete_one({"_id": id})
print(delete.deleted_count)
if delete_result.deleted_count == 1: if delete_result.deleted_count == 1:
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT, content={"message": "Delete successfull"}) return JSONResponse(status_code=status.HTTP_204_NO_CONTENT, content={"message": "Delete successfull"})
elif delete.deleted_count == 1:
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT, content={"message": "Delete successfull"})
raise HTTPException(status_code=404, detail=f"History not found") raise HTTPException(status_code=404, detail=f"History not found")
@history.get("/statistics_key_find", response_description="Get list history key find", response_model=List[HistoryByUserModel])
async def statistics_view_by_username():
history_find = await db["history"].find({"status": "Tìm kiếm bài viết theo từ khóa"}).sort("count", -1).to_list(1000)
all_user = []
out_data = []
i = 0
if history_find == []:
return history_find
all_user.append(history_find[0])
out_data.append(history_find[0]["data"])
for dt in history_find:
if not dt["data"] in out_data:
all_user.append(dt)
out_data.append(dt["data"])
i = i+1
if i == 99:
break
return all_user
@history.post("/create_khoa", response_description="history", response_model=StatisticalSpecialistModel)
async def create_history(token: str, ss: StatisticalSpecialistModel = None):
ss = jsonable_encoder(ss)
print(ss)
StatisticalSpecialist_new = await db["StatisticalSpecialist"].insert_one(ss)
create_ss = await db["StatisticalSpecialist"].find_one({"_id": StatisticalSpecialist_new.inserted_id})
create_ss = jsonable_encoder(create_ss)
# return JSONResponse(status_code=status.HTTP_201_CREATED, content=create_history)
return create_ss
@history.post("/auto_create_khoa", response_description="history", response_model=List[StatisticalSpecialistModel])
async def create_history():
data = []
for i in KHOA:
print(i)
StatisticalSpecialist_new = await db["StatisticalSpecialist"].insert_one(i)
create_ss = await db["StatisticalSpecialist"].find_one({"_id": StatisticalSpecialist_new.inserted_id})
data.append(create_ss)
return JSONResponse(status_code=status.HTTP_201_CREATED, content=data)
@history.get(
"/statistical_specialist", response_description="Statistical Specialist", response_model=List[StatisticalSpecialistModel]
)
async def list_post():
StatisticalSpecialist = await db["StatisticalSpecialist"].find().to_list(1000)
return StatisticalSpecialist
@history.delete("/statistical_specialist111"
)
async def delete():
StatisticalSpecialist = await db["StatisticalSpecialist"].delete_many({})
return StatisticalSpecialist.deleted_count

View File

@@ -1,3 +1,10 @@
import datetime
import pytz
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import codecs
from pathlib import Path
import re
from email.policy import default from email.policy import default
import imp import imp
from fastapi import APIRouter, Depends, status, HTTPException, UploadFile, File, Header, Request from fastapi import APIRouter, Depends, status, HTTPException, UploadFile, File, Header, Request
@@ -12,7 +19,6 @@ from ..dependecies import (
create_access_token, create_access_token,
get_password_hash get_password_hash
) )
from src.settings import db, ACCESS_TOKEN_EXPIRE_MINUTES
from ..models.post import ( from ..models.post import (
PostModel, PostModel,
UpdatePostModel, UpdatePostModel,
@@ -35,14 +41,7 @@ from ..settings import *
from ..models.history_find import * from ..models.history_find import *
from ..routers.routers import * from ..routers.routers import *
from typing import List from typing import List
import os
import re
from pathlib import Path
import codecs
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import pytz
import datetime
tz = pytz.timezone('Asia/Ho_Chi_Minh') tz = pytz.timezone('Asia/Ho_Chi_Minh')
post = APIRouter() post = APIRouter()
@@ -64,13 +63,13 @@ async def create_post(post: PostModel,
): ):
try: try:
# print(post) # print(post)
# data_token = await get_current_user(token) # data_token = await get_current_user(Nonetoken)
# data = data_token.get("user_name", None) # data = data_token.get("user_name", None)
# user_type = data_token.get("user_type", None) # user_type = data_token.get("user_type", None)
# if data == None: # if data == None:
# return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"}) # return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
post.created_at = datetime.datetime.now(tz=tz) # post.created_at = datetime.datetime.now(tz=tz)
post = jsonable_encoder(post) post = jsonable_encoder(post)
if(post.get("point", None) == None): if(post.get("point", None) == None):
post["point"] = { post["point"] = {
@@ -121,10 +120,16 @@ async def create_post(post: PostModel,
"/list_post", response_description="List all posts" "/list_post", response_description="List all posts"
) )
async def list_post( async def list_post(
token: TokenModel = None token: TokenModel = None,
page: int = 0,
limit: int = 10,
): ):
posts = await db["posts"].find().sort("created_at", -1).to_list(1000) posts = await db["posts"].find().sort("created_at", -1).sort("point.total", -1).skip(page*limit).to_list(limit)
count_total = await db["posts"].count_documents({})
# print(count)
output = [] output = []
if token.token != None: if token.token != None:
posts = jsonable_encoder(posts) posts = jsonable_encoder(posts)
for post in posts: for post in posts:
@@ -152,15 +157,21 @@ async def list_post(
else: else:
post["post_save"] = False post["post_save"] = False
output.append(post) output.append(post)
return output return {
"total": count_total,
"data": output,
}
else: else:
return posts return {
"total": count_total,
"data": posts,
}
@post.post( @post.post(
"/find_list_post", response_description="search list posts" "/find_list_post", response_description="search list posts"
) )
async def find_list_post(key_find: str, token: str = None, history: HistoryFindModel = None): async def find_list_post(page: int = 0, limit: int = 10, key_find: str = None, token: str = None, history: HistoryFindModel = None):
# point_data = ["point.less10", # point_data = ["point.less10",
# "point.form10to20", # "point.form10to20",
# "point.form20to30", # "point.form20to30",
@@ -187,6 +198,111 @@ async def find_list_post(key_find: str, token: str = None, history: HistoryFindM
{"data.content": {"$regex": key_find, "$options": 'i'}}, {"data.content": {"$regex": key_find, "$options": 'i'}},
{"original_post": {"$regex": key_find, "$options": 'i'}}, {"original_post": {"$regex": key_find, "$options": 'i'}},
{"summary": {"$regex": key_find, "$options": 'i'}}, {"summary": {"$regex": key_find, "$options": 'i'}},
{"tag": {"$regex": key_find, "$options": 'xi'}},
]
}).sort("point.total", -1).skip(page*limit).to_list(limit)
count_total = await db["posts"].count_documents({
"$or": [
{"translation_post": {"$regex": key_find, "$options": 'i'}},
{"data.content": {"$regex": key_find, "$options": 'i'}},
{"original_post": {"$regex": key_find, "$options": 'i'}},
{"summary": {"$regex": key_find, "$options": 'i'}},
{"tag": {"$regex": key_find, "$options": 'xi'}},
]
})
output = []
# history.created_at = datetime.datetime.now(tz=tz)
if token != None:
data_token = await get_current_user(token)
data = data_token.get("user_name", None)
user_type = data_token.get("user_type", None)
history = jsonable_encoder(history)
history_user = history
history_user["user_name"] = data
history_user["status"] = "Tìm kiếm bài viết theo từ khóa"
history_user["note"] = ""
history_user["data"] = key_find
check_data = await db["history"].find({"data": key_find, "status": "Tìm kiếm bài viết theo từ khóa"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
del history_user["_id"]
del history_user["token"]
del history_user["sick"]
del history_user["authorities"]
print(history_user)
history_new = await db["history"].insert_one(history_user)
for post in posts:
if data == None:
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
post = jsonable_encoder(post)
count = await db["post_save"].count_documents({"post_id": post["_id"], "username": data})
if count != 0:
post["post_save"] = True
else:
post["post_save"] = False
output.append(post)
return {
"total": count_total,
"data": output,
}
else:
history = jsonable_encoder(history)
history_user = history
history_user["user_name"] = "anonymous"
history_user["status"] = "Tìm kiếm bài viết theo từ khóa"
history_user["note"] = ""
history_user["data"] = key_find
check_data = await db["history"].find({"data": key_find, "status": "Tìm kiếm bài viết theo từ khóa"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
del history_user["_id"]
del history_user["token"]
del history_user["sick"]
del history_user["authorities"]
print(history_user)
history_new = await db["history"].insert_one(history_user)
return {
"total": count_total,
"data": posts,
}
@post.post(
"/find_list_post1111", response_description="search list posts"
)
async def find_list_post(key_find: str, token: str = None, history: HistoryFindModel = None):
# point_data = ["point.less10",
# "point.form10to20",
# "point.form20to30",
# "point.form30to40",
# "point.form40to50",
# "point.form50to60",
# ]
age_sort = "point.total"
# history = jsonable_encoder(history)
# if history.get("age", None) != None:
# if history.get("age") > 59:
# age_sort = "point.bigger60"
# else:
# age_sort = point_data[history.get("age")//10]
# posts = await db["posts"].find("$or": [
# {"translation_post": {"$regex": key_find}},
# {"translation_post": {"$regex": key_find}},
# ]).sort(age_sort, -1).to_list(100)
posts = await db["posts"].find({
"$or": [
{"translation_post": {"$regex": key_find, "$options": 'xi'}},
{"data.content": {"$regex": key_find, "$options": 'xi'}},
{"original_post": {"$regex": key_find, "$options": 'xi'}},
{"summary": {"$regex": key_find, "$options": 'xi'}},
{"tag": {"$regex": key_find, "$options": 'xi'}},
] ]
}).sort(age_sort, -1).to_list(100) }).sort(age_sort, -1).to_list(100)
output = [] output = []
@@ -251,7 +367,7 @@ async def find_list_post(key_find: str, token: str = None, history: HistoryFindM
) )
async def get_post_by_name(history: HistoryFindModel): async def get_post_by_name(history: HistoryFindModel):
try: try:
history.created_at = datetime.datetime.now(tz=tz) # history.created_at = datetime.datetime.now(tz=tz)
history = jsonable_encoder(history) history = jsonable_encoder(history)
token = history.get("token", None) token = history.get("token", None)
if token == '': if token == '':
@@ -262,13 +378,18 @@ async def get_post_by_name(history: HistoryFindModel):
post["data"].remove(dt) post["data"].remove(dt)
history_find = jsonable_encoder(history) history_find = jsonable_encoder(history)
history = jsonable_encoder(history) history = jsonable_encoder(history)
count = await db["post_save"].count_documents({"post_id": post["_id"], "username": data}) check_data = await db["history"].find({"post_id": post["_id"], "username": data, "status": "xem bài viết"}).sort("created_at", -1).to_list(1)
if count != 0: if check_data != []:
post["post_save"] = True history_user["count"] = int(check_data[0]["count"]) + 1
else: else:
post["post_save"] = False history_user["count"] = 1
new_his = await db["history_find"].insert_one(history_find) # count = await db["post_save"].count_documents({"post_id": post["_id"], "username": data})
created = await db["history_find"].find_one({"_id": new_his.inserted_id}) # if count != 0:
# post["post_save"] = True
# else:
# post["post_save"] = False
# new_his = await db["history_find"].insert_one(history_find)
# created = await db["history_find"].find_one({"_id": new_his.inserted_id})
history_user = history_find history_user = history_find
history_user["user_name"] = "anonymous" history_user["user_name"] = "anonymous"
history_user["status"] = "xem bài viết" history_user["status"] = "xem bài viết"
@@ -315,6 +436,11 @@ async def get_post_by_name(history: HistoryFindModel):
del history_user["token"] del history_user["token"]
del history_user["sick"] del history_user["sick"]
del history_user["authorities"] del history_user["authorities"]
check_data = await db["history"].find({"post_id": post["_id"], "username": data, "status": "xem bài viết"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
history_new = await db["history"].insert_one(history_user) history_new = await db["history"].insert_one(history_user)
create_history = await db["history"].find_one({"_id": history_new.inserted_id}) create_history = await db["history"].find_one({"_id": history_new.inserted_id})
if post is not None: if post is not None:
@@ -336,7 +462,7 @@ async def get_post_by_name(history: HistoryFindModel):
) )
async def get_post_edit(history: HistoryFindModel): async def get_post_edit(history: HistoryFindModel):
try: try:
history.created_at = datetime.datetime.now(tz=tz) # history.created_at = datetime.datetime.now(tz=tz)
history = jsonable_encoder(history) history = jsonable_encoder(history)
post = await db["posts"].find_one({"_id": history["post_id"]}) post = await db["posts"].find_one({"_id": history["post_id"]})
new_his = await db["history_find"].insert_one(history) new_his = await db["history_find"].insert_one(history)
@@ -388,48 +514,14 @@ async def score_all_post(
# current_user: UserModel = Depends(get_current_user) # current_user: UserModel = Depends(get_current_user)
): ):
posts = await db["posts"].find().to_list(1000) posts = await db["posts"].find().to_list(1000)
print(post)
for dt_post in posts: for dt_post in posts:
data_old = dt_post data_old = dt_post
dt_post["point"]["less10"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 0, '$lte': 9
}})
dt_post["point"]["form10to20"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 10, '$lte': 19
}})
dt_post["point"]["form20to30"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 20, '$lte': 29
}})
dt_post["point"]["form30to40"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 30, '$lte': 39
}})
dt_post["point"]["form40to50"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 40, '$lte': 49
}})
dt_post["point"]["form50to60"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 50, '$lte': 59
}})
dt_post["point"]["bigger60"] = await db["history_find"].count_documents({"post_id": dt_post["_id"],
"age": {
'$gte': 60
}})
dt_post["point"]["total"] = await db["history_find"].count_documents({"post_id": dt_post["_id"]}) dt_post["point"]["total"] = await db["history_find"].count_documents({"post_id": dt_post["_id"]})
# await db["posts"].update_one(data_old, dt_post) # await db["posts"].update_one(data_old, dt_post)
await db["posts"].update_one({"_id": dt_post["_id"]}, {"$set": { await db["posts"].update_one({"_id": dt_post["_id"]}, {"$set": {
"point": { "point": {
"less10": dt_post["point"]["less10"],
"form10to20": dt_post["point"]["form10to20"],
"form20to30": dt_post["point"]["form20to30"],
"form30to40": dt_post["point"]["form30to40"],
"form40to50": dt_post["point"]["form40to50"],
"form50to60": dt_post["point"]["form50to60"],
"bigger60": dt_post["point"]["bigger60"],
"total": dt_post["point"]["total"] "total": dt_post["point"]["total"]
} }
}}) }})
@@ -474,6 +566,7 @@ async def create_upload_post(
# now = datetime.datetime.now(tz=tz) # now = datetime.datetime.now(tz=tz)
# current_time = now.strftime("%H_%M_%S_%d-%m-%Y_") # current_time = now.strftime("%H_%M_%S_%d-%m-%Y_")
folder_save = f"./post/" folder_save = f"./post/"
# Path(folder_save).mkdir(parents=True) # Path(folder_save).mkdir(parents=True)
# for file in post: # for file in post:
# file_save = folder_save + "/" + file.filename # file_save = folder_save + "/" + file.filename
@@ -482,11 +575,12 @@ async def create_upload_post(
# with open(file_save, "wb+") as file_object: # with open(file_save, "wb+") as file_object:
# file_object.write(file.file.read()) # file_object.write(file.file.read())
folder_save = folder_save + "/images" # folder_save = folder_save + "/images"
Path(folder_save).mkdir(parents=True, exist_ok=True) Path(folder_save).mkdir(parents=True, exist_ok=True)
for file in image: for file in image:
file_save = folder_save + "/" + file.filename file_save = f"./post/images" + "/" + file.filename
file_name.append(file_save) file_return = URL_SERVER+"post/images/" + file.filename
file_name.append(file_return)
with open(file_save, "wb+") as file_object: with open(file_save, "wb+") as file_object:
file_object.write(file.file.read()) file_object.write(file.file.read())
return {"filenames": file_name} return {"filenames": file_name}
@@ -544,7 +638,7 @@ async def create_upload_post(
@post.post("/edit_post/{id}", response_description="score all post") @post.post("/edit_post/{id}", response_description="score all post")
async def edit_post(id: str, post: UpdatePostModel, token: str): async def edit_post(id: str, post: UpdatePostModel, token: str):
try: try:
post.updated_at = datetime.datetime.now(tz=tz) # post.updated_at = datetime.datetime.now(tz=tz)
post = jsonable_encoder(post) post = jsonable_encoder(post)
created_post = await db["posts"].find_one({"_id": id}) created_post = await db["posts"].find_one({"_id": id})
post["created_at"] = created_post["created_at"] post["created_at"] = created_post["created_at"]
@@ -584,3 +678,93 @@ async def edit_post(id: str, post: UpdatePostModel, token: str):
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
content={'message': str(e)} content={'message': str(e)}
) )
@post.post(
"/fillter", response_description="filtter posts"
)
async def find_list_post(status: str = None, specialist: str = None, key_find: str = None, token: str = None, history: HistoryFindModel = None):
# point_data = ["point.less10",
# "point.form10to20",
# "point.form20to30",
# "point.form30to40",
# "point.form40to50",
# "point.form50to60",
# ]
age_sort = "point.total"
# history = jsonable_encoder(history)
# if history.get("age", None) != None:
# if history.get("age") > 59:
# age_sort = "point.bigger60"
# else:
# age_sort = point_data[history.get("age")//10]
# posts = await db["posts"].find("$or": [
# {"translation_post": {"$regex": key_find}},
# {"translation_post": {"$regex": key_find}},
# ]).sort(age_sort, -1).to_list(100)
posts = await db["posts"].find({
"$and": [
{"specialist": specialist},
{"status": status},
{"translation_post": {"$regex": key_find, "$options": 'i'}},
{"data.content": {"$regex": key_find, "$options": 'i'}},
{"original_post": {"$regex": key_find, "$options": 'i'}},
{"summary": {"$regex": key_find, "$options": 'i'}},
{"tag": {"$regex": key_find, "$options": 'xi'}},
]
}).sort(age_sort, -1).to_list(100)
output = []
# history.created_at = datetime.datetime.now(tz=tz)
if token != None:
data_token = await get_current_user(token)
data = data_token.get("user_name", None)
user_type = data_token.get("user_type", None)
history = jsonable_encoder(history)
history_user = history
history_user["user_name"] = data
history_user["status"] = "Tìm kiếm bài viết theo từ khóa"
history_user["note"] = ""
history_user["data"] = key_find
check_data = await db["history"].find({"data": key_find, "status": "Tìm kiếm bài viết theo từ khóa"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
del history_user["_id"]
del history_user["token"]
del history_user["sick"]
del history_user["authorities"]
print(history_user)
history_new = await db["history"].insert_one(history_user)
for post in posts:
if data == None:
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "UNAUTHORIZED"})
post = jsonable_encoder(post)
count = await db["post_save"].count_documents({"post_id": post["_id"], "username": data})
if count != 0:
post["post_save"] = True
else:
post["post_save"] = False
output.append(post)
return output
else:
history = jsonable_encoder(history)
history_user = history
history_user["user_name"] = "anonymous"
history_user["status"] = "Tìm kiếm bài viết theo từ khóa"
history_user["note"] = ""
history_user["data"] = key_find
check_data = await db["history"].find({"data": key_find, "status": "Tìm kiếm bài viết theo từ khóa"}).sort("created_at", -1).to_list(1)
if check_data != []:
history_user["count"] = int(check_data[0]["count"]) + 1
else:
history_user["count"] = 1
del history_user["_id"]
del history_user["token"]
del history_user["sick"]
del history_user["authorities"]
history_new = await db["history"].insert_one(history_user)
return posts

View File

@@ -5,6 +5,11 @@ import datetime
from json import JSONEncoder from json import JSONEncoder
import os import os
import motor.motor_asyncio import motor.motor_asyncio
from dotenv import load_dotenv
from pathlib import Path
dotenv_path = Path('../../.env')
load_dotenv(dotenv_path=dotenv_path)
# ================= Creating necessary variables ======================== # ================= Creating necessary variables ========================
# ------------------ Token, authentication variables --------------------- # ------------------ Token, authentication variables ---------------------
@@ -13,13 +18,14 @@ ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30 ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
URL_SERVER = os.getenv('URL_SERVER')
class DateTimeEncoder(JSONEncoder): class DateTimeEncoder(JSONEncoder):
# Override the default method # Override the default method
def default(self, obj): def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)): if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat() return obj.isofort()
oauth2_scheme = OAuth2PasswordBearer( oauth2_scheme = OAuth2PasswordBearer(
@@ -76,54 +82,280 @@ ROLE_ORG = [
} }
] ]
KHOA = [{ KHOA = [
"name": "KHOA_NOI", {
"comment": "Khoa Nội", "name": 'Khoa Khám bệnh',
}, "count": 0,
{ "id": 'K01',
"name": "KHOA_NGOAI", },
"comment": "Khoa Ngoại", {
}, "name": 'Khoa Hồi sức cấp cứu',
{ "count": 0,
"name": "KHOA_PHU_SAN", "id": 'K02',
"comment": "Khoa Phụ sản", },
}, {
{ "name": 'Khoa Nội tổng hợp',
"name": "KHOA_NHI", "count": 0,
"comment": "Khoa Nhi", "id": 'K03',
}, },
{ {
"name": "KHOA_TRUYEN_NHIEM", "name": 'Khoa Nội tim mạch',
"comment": "Khoa Truyền nhiễm", "count": 0,
}, "id": 'K04',
{ },
"name": "KHOA_CAP_CUU",
"comment": "Khoa Cấp cứu", {
}, "name": 'Khoa Nội tiêu hoá',
{ "count": 0,
"name": "KHOA_HOI_SUC", "id": 'K05',
"comment": "Khoa Hồi sức tích cực và chống độc", },
}, {
{ "name": 'Khoa Nội cơ - xương - khớp',
"name": "KHOA_Y_HOC_CO_TRUYEN", "count": 0,
"comment": "Khoa Y học cổ truyền", "id": 'K06',
},
{ },
"name": "KHOA_U_BUOU", {
"comment": "Khoa Ung bướu", "name": 'Khoa Nội thận - tiết niệu',
}, "count": 0,
{ "id": 'K07',
"name": "KHOA_Y_HOC_HAT_NHAN", },
"comment": "Khoa Y học Hạt nhân", {
}, "name": 'Khoa Nội tiết',
{ "count": 0,
"name": "KHOA_PHAU_THUA", "id": 'K08',
"comment": "Khoa Phẫu thuật - gây mê hồi sức",
}, },
{
"name": "KHOA_CHAN_DOAN_HINH_ANH", {
"comment": "Khoa Chẩn đoán hình ảnh", "name": 'Khoa Dị ứng',
}] "count": 0,
"id": 'K09',
},
{
"name": 'Khoa Huyết học lâm sàng',
"count": 0,
"id": 'K10',
},
{
"name": 'Khoa Nội thận - tiết niệu',
"count": 0,
"id": 'K11',
},
{
"name": 'Khoa Truyền nhiễm',
"count": 0,
"id": 'K12',
},
{
"name": 'Khoa Lao',
"count": 0,
"id": 'K13',
},
{
"name": 'Khoa Da liễu',
"count": 0,
"id": 'K14',
},
{
"name": 'Khoa Thần kinh',
"count": 0,
"id": 'K15',
},
{
"name": 'Khoa Tâm thần',
"count": 0,
"id": 'K16',
},
{
"name": 'Khoa Y học cổ truyền',
"count": 0,
"id": 'K17',
},
{
"name": 'Khoa Lão học',
"count": 0,
"id": 'K18',
},
{
"name": 'Khoa Nhi',
"count": 0,
"id": 'K19',
},
{
"name": 'Khoa Ngoại tổng hợp',
"count": 0,
"id": 'K20',
},
{
"name": 'Khoa Ngoại thần kinh',
"count": 0,
"id": 'K21',
},
{
"name": 'Khoa Ngoại lồng ngực',
"count": 0,
"id": 'K22',
},
{
"name": 'Khoa Ngoại tiêu hoá',
"count": 0,
"id": 'K23',
},
{
"name": 'Khoa Ngoại thận - tiết niệu',
"count": 0,
"id": 'K24',
},
{
"name": 'Khoa Chấn thương chỉnh hình',
"count": 0,
"id": 'K25',
},
{
"name": 'Khoa Bỏng',
"count": 0,
"id": 'K26',
},
{
"name": 'Khoa Phụ sản',
"count": 0,
"id": 'K27',
},
{
"name": 'Khoa Tai - Mũi - Họng',
"count": 0,
"id": 'K28',
},
{
"name": 'Khoa Răng - Hàm - Mặt',
"count": 0,
"id": 'K29',
},
{
"name": 'Khoa Mắt',
"count": 0,
"id": 'K30',
},
{
"name": 'Khoa Vật lý trị liệu - Phục hồi chức năng',
"count": 0,
"id": 'K31',
},
{
"name": 'Khoa Y học hạt nhân',
"count": 0,
"id": 'K32',
},
{
"name": 'Khoa Ung bướu (điều trị tia xạ)',
"count": 0,
"id": 'K33',
},
{
"name": 'Khoa Truyền máu',
"count": 0,
"id": 'K34',
},
{
"name": 'Khoa Lọc máu nhân tạo',
"count": 0,
"id": 'K35',
},
{
"name": 'Khoa Huyết học',
"count": 0,
"id": 'K36',
},
{
"name": 'Khoa Sinh hoá',
"count": 0,
"id": 'K37',
},
{
"name": 'Khoa Vi sinh',
"count": 0,
"id": 'K38',
},
{
"name": 'Khoa Chẩn đoán hình ảnh',
"count": 0,
"id": 'K39',
},
{
"name": 'Khoa Thăm dò chức năng',
"count": 0,
"id": 'K40',
},
{
"name": 'Khoa Nội soi',
"count": 0,
"id": 'K41',
},
{
"name": 'Khoa Giải phẫu bệnh',
"count": 0,
"id": 'K42',
},
{
"name": 'Khoa Chống nhiễm khuẩn',
"count": 0,
"id": 'K43',
},
{
"name": 'Khoa Dược',
"count": 0,
"id": 'K44',
},
{
"name": 'Khoa Dinh dưỡng',
"count": 0,
"id": 'K45',
},
{
"name": 'Khoa Sinh học phân tử',
"count": 0,
"id": 'K46',
},
{
"name": 'Khoa Xét nghiệm',
"count": 0,
"id": 'K47',
},
{
"name": 'Khoa hồi sức tích cực',
"count": 0,
"id": 'K48',
},
{
"name": 'Khoa Chống độc',
"count": 0,
"id": 'K49',
},
{
"name": 'Khoa Nội hô hấp',
"count": 0,
"id": 'K50',
},
]
# ----------------- Database variables (MongoDB) -------------------------- # ----------------- Database variables (MongoDB) --------------------------
client = motor.motor_asyncio.AsyncIOMotorClient(os.environ["DB_URL"]) client = motor.motor_asyncio.AsyncIOMotorClient(os.environ["DB_URL"])
db = client.myTestDB db = client.myTestDB

View File

@@ -2,6 +2,7 @@ version: "3.8"
services: services:
api: api:
image: medihome-dictionary-be:v1
build: ./app build: ./app
ports: ports:
- 80:80 - 80:80
@@ -10,6 +11,8 @@ services:
volumes: volumes:
- ./app:/app - ./app:/app
restart: always restart: always
env_file:
- .env
db: db:
image: mongo image: mongo