Skip to content

Instantly share code, notes, and snippets.

@Sanix-Darker
Last active February 1, 2020 14:19
Show Gist options
  • Save Sanix-Darker/68a52083269bc75f193dd59af18f3a91 to your computer and use it in GitHub Desktop.
Save Sanix-Darker/68a52083269bc75f193dd59af18f3a91 to your computer and use it in GitHub Desktop.
Models-Python
[config]
DATABASE_HOST = 127....
DATABASE_NAME = test
from pymongo import MongoClient
from settings import *
class DATABASE:
def __init__(self, database_name):
# creation of MongoClient
client = MongoClient()
# Connect with the portnumber and host
client = MongoClient(DATABASE_HOST)
# Access database
self.database_name = database_name
self.db = client[self.database_name]
def get_db():
DB = DATABASE(DATABASE_NAME)
return DB.db
from . import Database
from jsonschema import validate, ValidationError
class Model:
def __init__(self, json=None):
if json is None:
json = {"_id": "test"}
self.json = json
self.database = Database
self.collection = self.database.get_db()["model_example"]
self.schema = {}
def save(self):
if self.validate_input(self.json)[0]:
self.collection.insert(self.json)
else:
print("[+] JSON not valid for save()")
def update(self, param, json):
if self.validate_input(json)[0]:
self.collection.update_one(param, {"$set": json}, upsert=True)
else:
print("[+] JSON not valid for update()")
def delete(self, param):
self.collection.delete_many(param)
def count(self, param):
return self.collection.find(param).count()
def find_by(self, param):
return self.collection.find(param)
def find_all(self):
return self.collection.find()
def close(self):
self.collection.close()
def validate_input(self, data):
try:
validate(data, self.schema)
return True, ""
except ValidationError as e:
return False, str(e)
pymongo
configparser
jsonschema
import configparser as ConfigParser
# Configs parameters
configParser = ConfigParser.RawConfigParser()
configFilePath = r'config.txt'
configParser.read(configFilePath)
# Filling parameters
DATABASE_HOST = configParser.get('config', 'DATABASE_HOST')
DATABASE_NAME = configParser.get('config', 'DATABASE_NAME')
from . import Model
class Sms(Model.Model):
def __init__(self, json=None):
super().__init__(json)
if json is None:
json = {"_id": "test"}
self.json = json
self.collection = self.database.get_db()["sms"]
self.schema = {
"type": "object",
"required": ["s_number", "date", "encoding", "from_number", "message", "command"],
"properties": {
"s_number": {"type": "string"},
"date": {"type": "string"},
"encoding": {"type": "string"},
"from_number": {"type": "string"},
"message": {"type": "string"},
"command": {"type": "object"}
}
}
# Save process
# sms_fetch = list(Sms().findBy({
# "from_number": json_sms["from_number"],
# "message": json_sms["message"],
# "date": json_sms["date"]
# }))
# if len(sms_fetch) == 0:
# print("{+} Saving json_sms: ", json_sms)
# new_sms = Sms(json_sms)
# new_sms.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment