Compare commits

..

No commits in common. "ee18b5535c633c167b9925c212d9e465c0f9d18f" and "7c67f2f5bdfa80bdb545d5ea6c2c239d83838f81" have entirely different histories.

2 changed files with 36 additions and 77 deletions

View File

@ -20,19 +20,3 @@ Index page:
} }
``` ```
# Routes:
GET /post — список статей.
GET /post/name — отдельная статья.
POST /admin/posts — создать статью.
PUT /admin/posts — обновить статью.
DELETE /admin/posts/:id — удалить статью.
Все маршруты, которые начинаются с «/admin» требуют аутентификацию пользователя. Для stateless-сервиса очень удобно использовать Basic-аутентификацию, т.к. каждый запрос содержит логин и пароль пользователя.
# TODO:
* Переписать маршруты под админку
* Добавить авторизацию
* Добавить конфигурацию

95
main.py
View File

@ -1,5 +1,5 @@
#!/usr/bin/python3 #!/usr/bin/python3
from bottle import abort, route, run, request from bottle import abort, route, run, template, debug, request
import pymongo import pymongo
mongoclient = pymongo.MongoClient('localhost', 27017) mongoclient = pymongo.MongoClient('localhost', 27017)
@ -7,83 +7,41 @@ database = mongoclient['pycms']
posts = database['posts'] posts = database['posts']
class Init:
def readConfig():
"""
Read config file, if not exists - call Init.createConfig()
"""
pass
def createConfig():
"""
Create config file
"""
pass
def setupConnect():
"""
Setup MongoDB connection
"""
pass
class Back:
"""
All actions that will be triggered by http
"""
def getRootPost():
try:
return posts.find_one({'name': '_root_'})['text']
except TypeError:
return abort(404, 'No such page')
def getPost(name):
try:
return posts.find_one({'name': name})['text']
except TypeError:
return abort(404, 'No such page')
def updatePost(name, body):
# If post exists, update it
if posts.find_one({'name': name}):
newPost = {'$set': {'text': body}}
return str(posts.update_one({'name': name}, newPost))
# Else - create new
else:
newPost = {'name': name, 'text': body}
return str(posts.insert_one(newPost).inserted_id)
def deletePost(name):
return posts.delete_one({'name': name})
@route('/post/<name>') @route('/post/<name>')
def post(name): def post(name):
''' '''
Get post Get post
''' '''
return Back.getPost(name) try:
return posts.find_one({'name':name})['text']
except TypeError:
return abort(404, 'No such page')
@route('/post/<name>', method='POST') @route('/post/<name>', method='POST')
def postUpd(name): def post(name):
''' '''
Insert/Update post Insert/Update post
''' '''
body = request.forms.get('body') body = request.forms.get('body')
return Back.updatePost(name=name, body=body) # If post exists, update it
if posts.find_one({'name': name}):
newPost = {'$set': {'text': body}}
return str(posts.update_one({'name': name}, newPost))
# Else - create new
else:
newPost = {'name': name, 'text': body}
return str(posts.insert_one(newPost).inserted_id)
@route('/post/<name>', method='DELETE') @route('/post/<name>', method='DELETE')
def postDel(name): def post(name):
''' '''
Delete post by name Delete post by name
''' '''
# return str(posts.delete_one({'name':name})) return str(posts.delete_one({'name':name}))
return str(Back.deletePost(name))
@route('/posts')
@route('/post')
def all_posts(): def all_posts():
''' '''
Returns all posts Returns all posts
@ -97,8 +55,25 @@ def all_posts():
@route('/') @route('/')
def index(): def index():
return Back.getRootPost() try:
return posts.find_one({'name':'/'})['text']
except TypeError:
return abort(404, 'No such page')
@route('/', method='POST')
def post():
'''
Insert/Update post
'''
body = request.forms.get('body')
# If post exists, update it
if posts.find_one({'name': '/'}):
newPost = {'$set': {'text': body}}
return str(posts.update_one({'name': '/'}, newPost))
# Else - create new
else:
newPost = {'name': '/', 'text': body}
return str(posts.insert_one(newPost).inserted_id)
if __name__ == '__main__': if __name__ == '__main__':
run(host='0.0.0.0', port=8081, reloader=True, debug=True) run(host='0.0.0.0', port=8081, reloader=True, debug=True)