Просмотр исходного кода

handle upload img action for yodate_manage_table and add files, img_type input to home, room_planner update route

weichen 4 лет назад
Родитель
Сommit
e963273085
3 измененных файлов с 20 добавлено и 3 удалено
  1. 1 1
      backstage/home/routes.py
  2. 1 1
      backstage/room_planner/routes.py
  3. 18 1
      backstage/utils/routes.py

+ 1 - 1
backstage/home/routes.py

@@ -18,5 +18,5 @@ def home():
 
 @home_app.route('/backstage/home/update', methods=['POST'])
 def update():
-    update_manage_table(request.form, request.args)
+    update_manage_table(request.form, request.args, request.files, 'home2')
     return redirect(url_for('home.home'))

+ 1 - 1
backstage/room_planner/routes.py

@@ -17,5 +17,5 @@ def main():
 
 @room_planner_app.route('/backstage/room_planner/update', methods=['POST'])
 def update():
-    update_manage_table(request.form, request.args)
+    update_manage_table(request.form, request.args, request.files, 'room_planner2')
     return redirect(url_for('room_planner.main'))

+ 18 - 1
backstage/utils/routes.py

@@ -3,6 +3,7 @@ import requests
 from time import sleep
 from backstage.utils import translate
 from collections import defaultdict
+from os import path
 
 TYPE_URL_FOR = {'collection': 'collections.collection_list',
                 'blog': 'blogs.blog_list'}
@@ -35,7 +36,11 @@ def get_trans_title_url_name(title):
     return translate(title).replace(' ', '_')
 
 
-def update_manage_table(forms, req_args):
+def update_manage_table(forms, 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 key, value in forms.items():
         element_type = key.split('-')[0]
@@ -44,6 +49,18 @@ def update_manage_table(forms, req_args):
         else:
             value = str(value)
         update_data[element_type].append(value)
+    for f_key, f_value in files.items():
+        if not f_value or f_value.filename == '':
+            continue
+        if not allow_file(f_value.filename):
+            flash('上傳圖片失敗,副檔名必須為:{}'.format(ALLOWED_EXTENSIONS), 'danger')
+            continue
+        requests.post(
+            'http://127.0.0.1:5000/api/upload/static/img?type={}&filename={}'.format(
+                img_type, f_value.filename), files={'image': f_value})
+        img_index = int(f_key.split('-')[-1])-1
+        update_data['img'][img_index]['src'] = path.join(
+            path.split(update_data['img'][img_index]['src'])[0], f_value.filename)
     response = requests.post(
         'http://127.0.0.1:5000/api/manages/data?page={}&section={}'.format(
             req_args.get('page'), req_args.get('section_class')), json=update_data)