routes.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from flask import flash, request, redirect, url_for
  2. import requests
  3. from time import sleep
  4. from backstage.utils import translate
  5. from collections import defaultdict
  6. from os import path
  7. TYPE_URL_FOR = {'collection': 'collections.collection_list',
  8. 'blog': 'blogs.blog_list'}
  9. def create_content(data, image_data):
  10. new_response = requests.post('http://127.0.0.1:5000/api/new_content', json=data)
  11. if new_response.status_code == 200:
  12. requests.post(
  13. 'http://127.0.0.1:5000/api/upload/static/img?type={}&filename={}'.format(
  14. data.get('type'), image_data.filename), files={'image': image_data})
  15. sleep(1) # sleep for waiting for new_content API generating content successfully.
  16. return redirect(url_for('editor.editor', url='/{}/{}'.format(
  17. data.get('type'), get_trans_title_url_name(data.get('name')))))
  18. else:
  19. flash('新增文章失敗', 'danger')
  20. return redirect(url_for(TYPE_URL_FOR.get(data.get('type'))))
  21. def remove_content():
  22. url = request.args.get('url', type=str)
  23. response = requests.delete('http://127.0.0.1:5000/api/contents?url={}'.format(url))
  24. if response.status_code == 200:
  25. flash('刪除文章成功', 'success')
  26. else:
  27. flash('刪除文章失敗', 'danger')
  28. def get_trans_title_url_name(title):
  29. return translate(title).replace(' ', '_')
  30. def update_manage_table(forms, req_args, files, img_type):
  31. def allow_file(filename):
  32. return '.' in filename and \
  33. filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  34. ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
  35. update_data = defaultdict(list)
  36. for key, value in forms.items():
  37. element_type = key.split('-')[0]
  38. if element_type == 'img':
  39. value = eval(value)
  40. else:
  41. value = str(value)
  42. update_data[element_type].append(value)
  43. for f_key, f_value in files.items():
  44. if not f_value or f_value.filename == '':
  45. continue
  46. if not allow_file(f_value.filename):
  47. flash('上傳圖片失敗,副檔名必須為:{}'.format(ALLOWED_EXTENSIONS), 'danger')
  48. continue
  49. requests.post(
  50. 'http://127.0.0.1:5000/api/upload/static/img?type={}&filename={}'.format(
  51. img_type, f_value.filename), files={'image': f_value})
  52. img_index = int(f_key.split('-')[-1])-1
  53. update_data['img'][img_index]['src'] = path.join(
  54. path.split(update_data['img'][img_index]['src'])[0], f_value.filename)
  55. response = requests.post(
  56. 'http://127.0.0.1:5000/api/manages/data?page={}&section={}'.format(
  57. req_args.get('page'), req_args.get('section_class')), json=update_data)
  58. if response.status_code == 200:
  59. flash('修改成功', 'success')
  60. else:
  61. flash('修改失敗', 'danger')