4. MongoDB + Gunicorn
1. Mission
2. MongoDB
1) MongoDB 설정
2) MongoDB 재시작 및 상태 확인
sudo service mongod restart
sudo service mongod status
Could not create server TCP listening socket 127.0.0.1:27017: bind: Address already in use
와 같은 메시지가 로그에 찍힌다면 다음과 같이 해결한다.
mongodb 5402 0.3 0.0 1547284 120260 ? Sl Nov02 5:12 /usr/bin/mongod --config /etc/mongod.conf
sudo service mongod restart
sudo service mongod status
3) classifier.py
수정
- 기존의
classifier.py
를 다음과 같이 수정한다.
from flask import Flask, request
from pymongo import MongoClient
from bson.objectid import ObjectId
import requests
import json
import os
app = Flask(__name__)
class Classifier:
def __init__(self):
self.project_dir = os.path.dirname(os.path.abspath(__file__))
self.json_name = "access_token.json"
self.json_path = os.path.join(self.project_dir, self.json_name)
self.PID = os.getpid()
print(f"PID: {self.PID} / Loaded Classifier!")
if not os.path.isfile(self.json_path):
print(f"PID: {self.PID} / {self.json_path} does not exist!")
self.load()
def load(self):
with open(self.json_path, "r") as json_file:
self.json_data = json.load(json_file)
print(f"PID: {self.PID} / JSON file loaded from {self.json_path}")
def request_text(URL: str, body: dict):
response = requests.post(URL, data=json.dumps(body)).json()
return response
classifier = Classifier()
access_tokens = classifier.json_data.values()
client = MongoClient("localhost", 27017)
@app.route("/", methods=["POST"])
def main():
URL = "http://127.0.0.1:9999/predictions/test"
DB_NAME, COL_NAME = "test_db", "test_col"
headers = request.headers
body = request.get_json(force=True)
db = client[DB_NAME]
collection = db[COL_NAME]
if headers["Authorization"] in access_tokens:
src_lang = body["src_lang"]
src_text = body["src_text"]
tgt_lang = body["tgt_lang"]
translated = request_text(URL, body)
data_dict = {
"src_lang": src_lang,
"src_text": src_text,
"tgt_lang": tgt_lang,
"tgt_text": translated
}
collection.insert_one(data_dict)
print(f"\nPID: {classifier.PID} \ URL: {URL}\nSrc_Lang: {src_lang} \ Src_text: {src_text}\nTgt_Lang: {tgt_lang} \ Translated: {translated['translated']}\nSet to DB")
return translated
else:
return "Access Token Error!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port="80", debug=True)
4) Gunicorn 실행