routes.py 2.9 KB

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