Example #1
0
 def get_item(self, _id=None, postId=None):
     try:
         coll = db[self.collection]
         query = {"_id": ObjectId(_id)}
         if request.args.get("embedded", None) is not None:
             return Utils.embedded_comments(_id)
         if postId is not None:
             query = {"_id": ObjectId(_id), "postId": ObjectId(postId)}
         if coll.find(query) is not None:
             return Utils.return_jsonify(list(coll.find(query)))
         else:
             return make_error(status=400, description="Not found")
     except Exception as e:
         return make_error(status=400, description=str(e))
Example #2
0
    def get_list(self, postId=None):
        coll = db[self.collection]
        item = None

        where = request.args.get("where")
        if where:
            where = json.loads(where)
        else:
            where = {}

        max_result = int(request.args.get("max_result", "3"))
        page_id = int(request.args.get("page", "1"))

        skip = max_result * (page_id - 1)
        documents = list(coll.find(where).skip(skip).limit(max_result))
        if postId is not None:
            documents = list(
                coll.find({
                    "postId": ObjectId(postId)
                }).skip(skip).limit(max_result))

        # logger.warn('Doc %r', json.loads(json.dumps(documents)))

        item = json.loads(json.dumps(documents, default=json_util.default))

        page = {
            "_item": item,
            "_meta": {
                "max_result": max_result,
                "page": page_id,
                "total": coll.find({}).count(),
            }
        }
        return Utils.return_jsonify(page)
Example #3
0
    def get_list(cls):
        coll = db[cls.collection]
        item = None

        where = request.args.get("where")
        if where:
            where = json.loads(where)

        max_result = int(request.args.get("max_result", "3"))
        page_id = int(request.args.get("page", "1"))

        skip = max_result * (page_id - 1)
        documents = list(coll.find(where).skip(skip).limit(max_result))

        if (len(documents) > 0):
            last_id = documents[0]["_id"]
        else:
            item = []

        # logger.warn('Doc %r', json.loads(json.dumps(documents)))

        item = json.loads(json.dumps(documents, default=json_util.default))

        page = {
            "_item": item,
            "_meta": {
                "max_result": max_result,
                "page": page_id,
                "total": coll.find({}).count(),
                # "last_id": last_id
            }
        }
        return Utils.return_jsonify(page)
Example #4
0
 def create(cls, postId=None):
     request_data = return_request_data()
     coll = db[cls.collection]
     v = Validator(cls.schema)
     if not v.validate(request_data):
         return make_error(status=400, description=v.errors)
     else:
         if cls.__name__ == "User":
             if users.find_one({"username":
                                request_data.get('username')}) is not None:
                 return make_error(
                     400,
                     description="Username is exist, please choose another."
                 )
             request_data["birthday"] = datetime.strptime(
                 request_data.get("birthday"), format_str)
         elif cls.__name__ == "Post":
             request_data["user"] = session.get("username")
             request_data["_create"] = datetime.now()
         elif cls.__name__ == "Comment":
             request_data["postId"] = ObjectId(postId)
             request_data["userId"] = session.get("username")
         result = coll.insert_one(request_data)
         post = coll.find_one({'_id': result.inserted_id})
         logger.warn('Update %r', post)
         return Utils.return_jsonify(post)
Example #5
0
def login():
    session.clear()
    request_data = return_request_data()
    if not request_data.get("username", None):
        return make_error(400, description="[username] is required.")

    if not request_data.get("password", None):
        return make_error(400, description="[password] is required.")

    if users.find_one({"username": request_data.get('username')}) is None:
        return make_error(
            400, description="Username is not exist, please choose another.")

    if users.find_one({"password": request_data.get('password')}) is None:
        return make_error(400, description="password is wrong")

    data_user = users.find_one({"username": request_data.get("username")})
    payload = {
        "username":
        request_data.get("username"),
        "exp":
        datetime.utcnow() + timedelta(seconds=JWTConfig.JWT_EXP_DELTA_SECONDS)
    }
    jwt_token = jwt.encode(payload, JWTConfig.JWT_SECRET,
                           JWTConfig.JWT_ALGORITHM)
    return Utils.return_jsonify({'token': jwt_token.decode('utf-8')})
Example #6
0
 def get_item(cls, postId=None):
     check = request.args.get("comments", "")
     if check != "":
         return Utils.embedded_comments(postId)
     else:
         query = {}
         try:
             coll = db[cls.collection]
             if cls.__name__ == "Post":
                 query = {"_id": ObjectId(postId)}
             elif cls.__name__ == "Comment":
                 query = {"postId": ObjectId(postId)}
             if coll.find(query) is not None:
                 return Utils.return_jsonify(list(coll.find(query)))
             else:
                 return make_error(status=400, description="Not found")
         except Exception as e:
             return make_error(status=400, description=str(e))
Example #7
0
 def update(self, _id=None, postId=None):
     request_data = return_request_data()
     query = {"_id": ObjectId(_id)}
     coll = db[self.collection]
     if coll.find_one(query) is None:
         return make_error(status=400, description="it's not yours")
     request_data["_updated"] = datetime.now()
     result = coll.find_one_and_update(query, {'$set': request_data})
     result = coll.find_one(query)
     return Utils.return_jsonify(result)
Example #8
0
 def update(cls, _id=None):
     request_data = return_request_data()
     if request_data.get("birthday", None) is not None:
         request_data["birthday"] = datetime.strptime(
             request_data.get("birthday"), format_str)
     query = {"username": session.get("username")}
     coll = db[cls.collection]
     if coll.find_one(query) is None:
         return make_error(status=400, description="it's not yours")
     result = coll.find_one_and_update(query, {'$set': request_data})
     return Utils.return_jsonify(result)
Example #9
0
 def create(self, postId=None):
     request_data = return_request_data()
     coll = db[self.collection]
     v = Validator(self.schema)
     if not v.validate(request_data):
         return make_error(status=400, description=v.errors)
     else:
         if postId is not None:
             request_data["postId"] = ObjectId(postId)
         request_data["_create"] = datetime.now()
         request_data["_updated"] = datetime.now()
         result = coll.insert_one(request_data)
         post = coll.find_one({'_id': result.inserted_id})
         logger.warn('Update %r', post)
         return Utils.return_jsonify(post)
Example #10
0
 def update(cls, _id=None):
     request_data = return_request_data()
     query = {}
     if cls.__name__ == "Post":
         request_data["_updated"] = datetime.now()
         try:
             query = {"_id": ObjectId(_id), "user": session.get("username")}
         except Exception as e:
             return make_error(status=400, description=str(e))
     elif cls.__name__ == "User":
         if request_data.get("birthday", None) is not None:
             request_data["birthday"] = datetime.strptime(
                 request_data.get("birthday"), format_str)
         query = {"username": session.get("username")}
     coll = db[cls.collection]
     if coll.find_one(query) is None:
         return make_error(status=400, description="it's not yours")
     result = coll.find_one_and_update(query, {'$set': request_data})
     return Utils.return_jsonify(result)