123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- from flask import flash, request, redirect, url_for
- import requests
- from time import sleep
- from backstage.utils import translate
- from collections import defaultdict
- from os import path
- from backstage.config import PORTAL_SERVER
- TYPE_URL_FOR = {'collection': 'collections.collection_list',
- 'blog': 'blogs.blog_list'}
- def create_content(data, image_data):
- new_response = requests.post('{}new_content'.format(PORTAL_SERVER), json=data)
- if new_response.status_code == 200:
- requests.post(
- '{}upload/static/img?type={}&filename={}'.format(
- PORTAL_SERVER, data.get('type'), image_data.filename), files={'image': image_data})
- sleep(1) # sleep for waiting for new_content API generating content successfully.
- return redirect(url_for('editor.editor', url='/{}/{}'.format(
- data.get('type'), get_trans_title_url_name(data.get('name')))))
- else:
- flash('新增文章失敗', 'danger')
- return redirect(url_for(TYPE_URL_FOR.get(data.get('type'))))
- def remove_content():
- url = request.args.get('url', type=str)
- response = requests.delete('{}contents?url={}'.format(PORTAL_SERVER, url))
- if response.status_code == 200:
- flash('刪除文章成功', 'success')
- else:
- flash('刪除文章失敗', 'danger')
- def get_trans_title_url_name(title):
- return translate(title).replace(' ', '_')
- def update_manage_table(data, elements, req_args, files, img_type):
- def allow_file(filename):
- return '.' in filename and \
- filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
- update_data = defaultdict(list)
- for element, value in zip(elements, data):
- if element == 'img':
- value = eval(value)
- elif element == 'yt_video':
- value = {'videoid': str(value)}
- else:
- value = str(value)
- update_data[element].append(value)
- for idx, f_value in enumerate(files):
- if not f_value or f_value.filename == '':
- continue
- if not allow_file(f_value.filename):
- flash('上傳圖片失敗,副檔名必須為:{}'.format(ALLOWED_EXTENSIONS), 'danger')
- continue
- requests.post(
- '{}upload/static/img?type={}&filename={}'.format(
- PORTAL_SERVER, img_type, f_value.filename), files={'image': f_value})
- update_data['img'][idx]['src'] = path.join(
- path.split(update_data['img'][idx]['src'])[0], f_value.filename)
- response = requests.post(
- '{}manages/data?page={}§ion={}'.format(
- PORTAL_SERVER, req_args.get('page'), req_args.get('section_class')), json=update_data)
- if response.status_code == 200:
- sleep(1) # waiting for API upload image successfully.
- flash('修改成功', 'success')
- else:
- flash('修改失敗', 'danger')
|