routes.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. TYPE_URL_FOR = {'collection': 'collections.collection_list',
  7. 'blog': 'blogs.blog_list'}
  8. def create_content(data, image_data):
  9. new_response = requests.post('http://127.0.0.1:5000/api/new_content', json=data)
  10. if new_response.status_code == 200:
  11. requests.post(
  12. 'http://127.0.0.1:5000/api/upload/static/img?type={}&filename={}'.format(
  13. data.get('type'), image_data.filename), files={'image': image_data})
  14. sleep(1) # sleep for waiting for new_content API generating content successfully.
  15. return redirect(url_for('editor.editor', url='/{}/{}'.format(
  16. data.get('type'), get_trans_title_url_name(data.get('name')))))
  17. else:
  18. flash('新增文章失敗', 'danger')
  19. return redirect(url_for(TYPE_URL_FOR.get(data.get('type'))))
  20. def remove_content():
  21. url = request.args.get('url', type=str)
  22. response = requests.delete('http://127.0.0.1:5000/api/contents?url={}'.format(url))
  23. if response.status_code == 200:
  24. flash('刪除文章成功', 'success')
  25. else:
  26. flash('刪除文章失敗', 'danger')
  27. def get_trans_title_url_name(title):
  28. return translate(title).replace(' ', '_')
  29. def update_manage_table(forms, req_args):
  30. update_data = defaultdict(list)
  31. for key, value in forms.items():
  32. element_type = key.split('-')[0]
  33. if element_type == 'img':
  34. value = eval(value)
  35. else:
  36. value = str(value)
  37. update_data[element_type].append(value)
  38. response = requests.post(
  39. 'http://127.0.0.1:5000/api/manages/data?page={}&section={}'.format(
  40. req_args.get('page'), req_args.get('section_class')), json=update_data)
  41. if response.status_code == 200:
  42. flash('修改成功', 'success')
  43. else:
  44. flash('修改失敗', 'danger')