pycms/main.py

183 lines
4.4 KiB
Python
Raw Normal View History

#!/usr/bin/python3
2021-09-17 14:29:32 +03:00
from bottle import abort, route, run, request
2021-09-07 04:54:24 +03:00
import pymongo
import time
2021-09-20 02:18:03 +03:00
# TODO: auth to /admin
# TODO: timestamps to posts
# TODO: author to posts and multiple users
# TODO: add bottle's params to config
2021-09-20 02:18:03 +03:00
class Config:
"""
2021-09-20 02:18:03 +03:00
posts - table with posts
config structure:
DB:
- host
- port
- dbname
2021-11-01 05:25:57 +03:00
App:
- host
- port
- debug
"""
def __init__(self):
"""
2021-09-20 02:18:03 +03:00
Init config
"""
self.readConfig()
mongoclient = pymongo.MongoClient(self.host, self.port)
if self.dbname not in mongoclient.list_database_names():
print('DB not found, creating')
database = mongoclient[self.dbname]
if 'posts' not in database.list_collection_names():
2021-11-01 05:25:57 +03:00
print('Table not found, creating')
posts = database['posts']
self.posts = posts
def readConfig(self):
2021-09-17 14:29:32 +03:00
"""
2021-09-20 02:18:03 +03:00
Read config file, if not exists - call self.createConfig()
2021-09-17 14:29:32 +03:00
"""
import configparser
config = configparser.ConfigParser()
if not config.read('config.ini'):
self.createConfig(config)
db = config['DB']
self.host = db['host']
self.port = int(db['port'])
self.dbname = db['name']
2021-09-17 14:29:32 +03:00
app = config['App']
self.apphost = app['host']
self.appport = int(app['port'])
self.appdebug = bool(app['debug'])
def createConfig(self, config):
2021-09-17 14:29:32 +03:00
"""
Create config file
"""
config['DB'] = {}
db = config['DB']
db['host'] = 'localhost'
db['port'] = '27017'
db['name'] = 'pycms'
config['App'] = {}
app = config['App']
app['port'] = '8080'
app['debug'] = 'True'
app['host'] = '0.0.0.0'
with open('config.ini', 'w') as cfgfile:
config.write(cfgfile)
2021-09-17 14:29:32 +03:00
class Back():
2021-09-17 14:29:32 +03:00
"""
All actions that will be triggered by http
"""
def getRootPost(self):
2021-09-17 14:29:32 +03:00
try:
return posts.find_one({'name': '_root_'})['text']
except TypeError:
return abort(404, 'No such page')
def getPost(self, name):
2021-09-17 14:29:32 +03:00
try:
return posts.find_one({'name': name})['text']
except TypeError:
return abort(404, 'No such page')
def getAllPosts(self):
2021-09-20 02:18:03 +03:00
# TODO: clear up output, remove '_id' and 'body',
# now there should be only
dict_posts = list()
for i in posts.find():
dict_posts.append(i)
return str(dict_posts)
def updatePost(self, name, body):
2021-09-17 14:29:32 +03:00
# If post exists, update it
if posts.find_one({'name': name}):
newPostJson = {'$set': {'text': body}}
newPost = posts.update_one({'name': name}, newPostJson)
result = dict(
status=200, state='updated', count=newPost.matched_count
)
2021-09-17 14:29:32 +03:00
# Else - create new
else:
newPostJson = {'name': name, 'text': body,
'create_timestamp': str(time.time())}
newPost = posts.insert_one(newPost).inserted_id
result = dict(status=200, state='new')
return str(result)
2021-09-17 14:29:32 +03:00
def deletePost(self, name):
2021-11-01 05:54:36 +03:00
delete = posts.delete_one({'name': name}).deleted_count
if not delete:
result = dict(status=500, count=delete)
else:
result = dict(status=200, count=delete)
return str(result)
2021-09-17 14:29:32 +03:00
2021-11-01 04:46:07 +03:00
class Metrics:
def alive():
return str("alive 1")
@route('/metrics')
def metrics():
return Metrics.alive()
@route('/post/<name>')
def post(name):
'''
Get post
'''
return str(back.getPost(name))
2021-09-18 04:48:04 +03:00
@route('/admin/post/<name>', method='POST')
2021-09-17 14:29:32 +03:00
def postUpd(name):
'''
Insert/Update post
'''
body = request.forms.get('body')
return back.updatePost(name=name, body=body)
2021-09-18 04:48:04 +03:00
@route('/admin/post/<name>', method='DELETE')
2021-09-17 14:29:32 +03:00
def postDel(name):
'''
Delete post by name
'''
return str(back.deletePost(name))
2021-09-17 14:29:32 +03:00
2021-09-17 14:29:32 +03:00
@route('/post')
def all_posts():
'''
Returns all posts
'''
return back.getAllPosts()
@route('/')
def index():
return back.getRootPost()
2021-09-07 06:35:22 +03:00
if __name__ == '__main__':
2021-10-18 18:16:02 +03:00
print("Init")
cfg = Config()
2021-10-18 18:16:02 +03:00
print("Configured")
back = Back()
posts = cfg.posts
run(host=cfg.apphost, port=cfg.appport, reloader=cfg.appdebug, debug=cfg.appdebug)