Добавил класс с конфигом, поправил вызов классов

This commit is contained in:
Lulzette 2021-09-17 15:29:50 +03:00
parent ee18b5535c
commit 28b98a9127

59
main.py
View File

@ -2,12 +2,24 @@
from bottle import abort, route, run, request
import pymongo
mongoclient = pymongo.MongoClient('localhost', 27017)
database = mongoclient['pycms']
posts = database['posts']
class Config:
"""
posts - public, posts table from MongoClient
config: private, config for DB
config.db.host
config.db.port
config.db.dbname
"""
def __init__(self):
"""
Init init
"""
mongoclient = pymongo.MongoClient('localhost', 27017)
database = mongoclient['pycms']
posts = database['posts']
self.posts = posts
class Init:
def readConfig():
"""
Read config file, if not exists - call Init.createConfig()
@ -20,30 +32,30 @@ class Init:
"""
pass
def setupConnect():
"""
Setup MongoDB connection
"""
pass
class Back:
class Back():
"""
All actions that will be triggered by http
"""
def getRootPost():
def getRootPost(self):
try:
return posts.find_one({'name': '_root_'})['text']
except TypeError:
return abort(404, 'No such page')
def getPost(name):
def getPost(self, name):
try:
return posts.find_one({'name': name})['text']
except TypeError:
return abort(404, 'No such page')
def updatePost(name, body):
def getAllPosts(self):
dict_posts = list()
for i in posts.find():
dict_posts.append(i)
return str(dict_posts)
def updatePost(self, name, body):
# If post exists, update it
if posts.find_one({'name': name}):
newPost = {'$set': {'text': body}}
@ -53,7 +65,7 @@ class Back:
newPost = {'name': name, 'text': body}
return str(posts.insert_one(newPost).inserted_id)
def deletePost(name):
def deletePost(self, name):
return posts.delete_one({'name': name})
@ -62,7 +74,7 @@ def post(name):
'''
Get post
'''
return Back.getPost(name)
return str(back.getPost(name))
@route('/post/<name>', method='POST')
@ -71,7 +83,7 @@ def postUpd(name):
Insert/Update post
'''
body = request.forms.get('body')
return Back.updatePost(name=name, body=body)
return back.updatePost(name=name, body=body)
@route('/post/<name>', method='DELETE')
@ -80,7 +92,7 @@ def postDel(name):
Delete post by name
'''
# return str(posts.delete_one({'name':name}))
return str(Back.deletePost(name))
return str(back.deletePost(name))
@route('/post')
@ -88,17 +100,16 @@ def all_posts():
'''
Returns all posts
'''
dict_posts = list()
for i in posts.find():
dict_posts.append(i)
return str(dict_posts)
return back.getAllPosts()
@route('/')
def index():
return Back.getRootPost()
return back.getRootPost()
if __name__ == '__main__':
cfg = Config()
back = Back()
posts = cfg.posts
run(host='0.0.0.0', port=8081, reloader=True, debug=True)