routes.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. from flask import request, Blueprint
  2. from flask.wrappers import Response
  3. from flask_restful import Resource, Api
  4. from os import path, remove, walk, mkdir
  5. import logging
  6. import re
  7. from models.config import CONTENT_DIR, STATIC_DIR
  8. import shutil
  9. contents_app = Blueprint('contents', __name__)
  10. api = Api(contents_app)
  11. logger = logging.getLogger(__name__)
  12. DATA_FIELD = ['title:', 'url:','tags:','image:','description:']
  13. def _get_data(file_dir):
  14. def load_data():
  15. if 'title: ' in line:
  16. data_field.remove('title:')
  17. s = line.split('"')
  18. result['title'] = s[1]
  19. elif 'date: ' in line:
  20. # data_field.remove('date: ')
  21. s = line.replace('date: ', '').strip()
  22. result['date'] = s
  23. elif 'draft: ' in line:
  24. # data_field.remove('draft: ')
  25. s = line.replace('draft: ', '').strip()
  26. result['draft'] = s
  27. elif 'url: ' in line:
  28. data_field.remove('url:')
  29. s = line.split('"')
  30. result['url'] = s[1]
  31. elif 'tags: ' in line:
  32. data_field.remove('tags:')
  33. s = line.replace('tags: ', '').strip()
  34. """ if s != "":
  35. s = s + ","
  36. s = s + "全部屋型,全部坪數,全部預算,全部格局" """
  37. result['tags'] = s
  38. elif 'image: ' in line:
  39. s = line.replace('image: ', '').strip()
  40. s = s.replace('"', '').strip()
  41. result['image'] = s
  42. elif 'description: ' in line:
  43. s = line.replace('description: ', '').strip()
  44. s = s.replace('"', '').strip()
  45. result['description'] = s
  46. data_field = list(DATA_FIELD)
  47. result = {}
  48. with open(file_dir, 'r', encoding="utf-8") as md:
  49. result['content'] = md.read()
  50. md.seek(0)
  51. md_line_data = md.readlines()
  52. for line in md_line_data:
  53. load_data()
  54. if not data_field:
  55. return result
  56. if not 'tags' in result:
  57. result['tags'] = "全部類型,全部坪數,全部預算,全部格局"
  58. else:
  59. if result['tags'] != "":
  60. result['tags'] = result['tags'] + ","
  61. result['tags'] = result['tags'].replace('"', '') + "全部類型,全部坪數,全部預算,全部格局"
  62. return result
  63. def _gen_content_files():
  64. for root, dirs, files in walk(CONTENT_DIR):
  65. for f in files:
  66. if '.md' not in f:
  67. continue
  68. yield path.join(root, f)
  69. def _search_dir(url):
  70. def _get_file_front_matter_url():
  71. with open(file_dir, 'r', encoding="utf-8") as md:
  72. md_line_data = md.readlines()
  73. for line in md_line_data:
  74. if 'url:' in line:
  75. return list(filter(None, re.split('"|\n', line)))[-1]
  76. for file_dir in _gen_content_files():
  77. if url == _get_file_front_matter_url():
  78. return path.dirname(file_dir)
  79. def _search_content_dir(type_, categories=None):
  80. target = categories or type_
  81. def _get_file_front_matter_type():
  82. with open(file_dir, 'r', encoding="utf-8") as md:
  83. md_line_data = md.readlines()
  84. for line in md_line_data:
  85. if categories:
  86. if 'categories' in line:
  87. return list(filter(None, re.split('"|\n|]', line)))[-1]
  88. else:
  89. if 'type:' in line:
  90. return list(filter(None, re.split('"|\n', line)))[-1]
  91. for file_dir in _gen_content_files():
  92. if target == _get_file_front_matter_type():
  93. return path.dirname(file_dir)
  94. class Content(Resource):
  95. DATA_FIELD = ['title:', 'url:']
  96. @property
  97. def url(self):
  98. return request.args.get('url', type=str)
  99. def _search_content(self):
  100. result = {}
  101. for file_dir in _gen_content_files():
  102. data = _get_data(file_dir)
  103. if self.url in data.get('url', ''):
  104. result = data
  105. result['path'] = file_dir
  106. #print(result['path'])
  107. yield result
  108. def _get_contents(self):
  109. for file_dir in _gen_content_files():
  110. yield _get_data(file_dir)
  111. def get(self):
  112. if self.url:
  113. sortedData = sorted(list(self._search_content()), key=lambda x:x['date'], reverse=True)
  114. return sortedData
  115. else:
  116. sortedData = sorted(list(self._get_contents()), key=lambda x:x['date'], reverse=True)
  117. return sortedData
  118. def post(self):
  119. try:
  120. file_dir = path.join(
  121. _search_dir(request.args.get('url', type=str)), 'index.md')
  122. md_content = request.json.get('content')
  123. with open(file_dir, 'w', encoding="utf-8") as md:
  124. md.write(md_content)
  125. return md_content
  126. except TypeError as err:
  127. logger.error(
  128. 'Content post failed with file_dir param contain None. error: {}'.format(err))
  129. except OSError as err:
  130. logger.error(
  131. 'Content post failed with: {} is not exist{}'.format(file_dir, err))
  132. except AttributeError as err:
  133. logger.error('Content post failed with AttributeError: {}'.format(err))
  134. except Exception as err:
  135. logger.error('Content post failed with: {}'.format(err))
  136. def delete(self):
  137. content_data = list(self._search_content())
  138. file_dir = content_data[0].get('path')
  139. if path.exists(file_dir):
  140. # remove(file_dir)
  141. shutil.rmtree(file_dir[0:file_dir.replace('\\', '/').rfind('/')+1])
  142. # print(file_dir[0:file_dir.replace('\\','/').rfind('/')+1])
  143. logger.info('delete dir: {}'.format(
  144. file_dir[0:file_dir.replace('\\', '/').rfind('/')+1]))
  145. else:
  146. logger.warning('delete fail with {} not exist'.format(file_dir))
  147. @contents_app.route('/api/upload/img', methods=['POST'])
  148. def upload_img():
  149. img_data = request.files['image']
  150. file_dir = _search_dir(request.args.get('url', type=str))
  151. img_dir = path.join(file_dir, 'img/{}'.format(img_data.filename))
  152. img_data.save(img_dir)
  153. return {'filename': img_data.filename}
  154. @contents_app.route('/api/delete/img', methods=['DELETE'])
  155. def delete_img():
  156. try:
  157. file_dir = _search_dir(request.args.get('url', type=str))
  158. img_dir = path.join(file_dir, 'img/{}'.format(request.args.get('filename', type=str)))
  159. remove(img_dir)
  160. logger.info('delete img: {}'.format(img_dir))
  161. return {'filename': request.args.get('filename', type=str)}
  162. except TypeError as err:
  163. logger.error('delete img: {} failed with file_dir is None. error: {}'.format(
  164. request.args.get('filename', type=str), err))
  165. return {'filename': request.args.get('filename', type=str)}
  166. except OSError as err:
  167. logger.error('delete img: {} failed with img_dir is not exist. error: {}'.format(
  168. request.args.get('filename', type=str), err))
  169. return {'filename': request.args.get('filename', type=str)}
  170. except Exception as err:
  171. logger.error('delete img: {} failed with {}'.format(
  172. request.args.get('filename', type=str), err))
  173. return {'filename': request.args.get('filename', type=str)}
  174. @contents_app.route('/api/upload/static/img', methods=['POST'])
  175. def upload_static_img():
  176. img_data = request.files['image']
  177. img_dir = path.join(STATIC_DIR, 'img',
  178. request.args.get('type', type=str),
  179. request.args.get('filename', type=str))
  180. img_data.save(img_dir)
  181. return {'filename': request.args.get('filename', type=str)}
  182. @contents_app.route('/api/new_content', methods=['POST'])
  183. def gen_content():
  184. front_matter = request.json.get('frontMatter', '---\n---')
  185. name = request.json.get('name', 'Undefind')
  186. if request.json.get('type') == "blog":
  187. dir_ = CONTENT_DIR + "/"+request.json.get('type') + "/" + name
  188. if not path.exists(dir_):
  189. mkdir(dir_)
  190. if not path.exists(path.join(dir_, 'img')):
  191. mkdir(path.join(dir_, 'img'))
  192. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  193. md.write(front_matter)
  194. # print(front_matter)
  195. else:
  196. dir_ = path.join(_search_content_dir(
  197. request.json.get('type'), request.json.get('categories')), name)
  198. if dir_:
  199. if not path.exists(dir_):
  200. mkdir(dir_)
  201. else:
  202. return Response({}, status=201)
  203. if not path.exists(path.join(dir_, 'img')):
  204. mkdir(path.join(dir_, 'img'))
  205. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  206. md.write(front_matter)
  207. return {'new_content': name}
  208. @contents_app.route('/api/get_cats', methods=['POST', 'GET'])
  209. def get_cats():
  210. """ front_matter = request.json.get('frontMatter', '---\n---')
  211. name = request.json.get('name', 'Undefind')
  212. dir_ = path.join(_search_content_dir(
  213. request.json.get('type'), request.json.get('categories')), name) """
  214. #print(_search_content_dir('blog', 'home_inspection_knowledge'))
  215. return {}
  216. @contents_app.route('/api/new_cat', methods=['POST'])
  217. def gen_cat():
  218. front_matter = request.json.get('frontMatter', '---\n---')
  219. name = request.json.get('name', 'Undefind')
  220. dir_ = path.join(_search_content_dir(
  221. request.json.get('type'), request.json.get('categories')), name)
  222. #print(request.json.get('type') + ',' + request.json.get('categories'))
  223. if dir_:
  224. if not path.exists(dir_):
  225. mkdir(dir_)
  226. else:
  227. return Response({}, status=201)
  228. if not path.exists(path.join(dir_, 'img')):
  229. mkdir(path.join(dir_, 'img'))
  230. with open(path.join(dir_, 'index.md'), 'w', encoding="utf-8") as md:
  231. md.write(front_matter)
  232. return {'new_content': name}
  233. api.add_resource(Content, '/api/contents')