No Description

articles.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. from flask import (Blueprint, current_app, flash, jsonify, redirect, request,
  3. send_from_directory, url_for)
  4. from flask_cors import CORS, cross_origin
  5. from werkzeug.utils import secure_filename
  6. articles_api_bp = Blueprint(
  7. "articles", __name__, template_folder="templates")
  8. cors = CORS(articles_api_bp, resources={
  9. r"/articles": {"origins": "http://localhost:5500"}})
  10. @articles_api_bp.route("/<path:article>")
  11. @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
  12. def send_text_file(article):
  13. return send_from_directory(directory="articles_files", path=article)
  14. @articles_api_bp.route('/')
  15. @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
  16. def index():
  17. # List files in articles directory
  18. files = list()
  19. for filename in os.listdir(os.path.join(
  20. current_app.root_path, "articles_files")):
  21. path = os.path.join(os.path.join(
  22. current_app.root_path, "articles_files"), filename)
  23. if os.path.isfile(path):
  24. files.append(filename)
  25. return jsonify(files)
  26. @articles_api_bp.route("/upload", methods=("POST",))
  27. @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
  28. def upload_file():
  29. if request.method == "POST":
  30. if "file" not in request.files:
  31. flash("No file part")
  32. return redirect(request.url)
  33. file = request.files["file"]
  34. if file.filename == '':
  35. flash("No selected file")
  36. return redirect(request.url)
  37. if file and allowed_file(file.filename):
  38. filename = secure_filename(file.filename)
  39. file.save(os.path.join(
  40. current_app.config["UPLOAD_FOLDER"], filename))
  41. return redirect(url_for("articles.send_text_file",
  42. article=filename))
  43. def allowed_file(filename):
  44. return '.' in filename and \
  45. filename.rsplit('.', 1)[1].lower(
  46. ) in current_app.config["ALLOWED_EXTENSIONS"]