No Description

files_api.py 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import os
  2. from flask import Flask, send_from_directory, jsonify, current_app
  3. from flask_cors import CORS, cross_origin
  4. from werkzeug.utils import secure_filename
  5. app = Flask(__name__, static_url_path='')
  6. app.config["SECRET_KEY"] = "f82abccd93a28b6cdda4525c9afa7a30"
  7. app.config["CORS_HEADERS"] = "Content-Type"
  8. app.config['UPLOAD_FOLDER'] = './articles'
  9. cors = CORS(app, resources={r"/articles": {"origins": "http://localhost:5500"}})
  10. @app.route("/articles/<path:article>")
  11. @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
  12. def send_text_file(article):
  13. return send_from_directory(directory="articles", path=article)
  14. @app.route("/articles")
  15. @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
  16. def list_files():
  17. files = list()
  18. for filename in os.listdir(os.path.join(current_app.root_path, "articles")):
  19. path = os.path.join(current_app.root_path, "articles", filename)
  20. if os.path.isfile(path):
  21. files.append(filename)
  22. return jsonify(files)
  23. @app.route("/" ,methods = ['POST'])
  24. def upload_file():
  25. if requested.method == 'POST':
  26. file=request.files['file']
  27. if file:
  28. filename = secure_filename(file.filename)
  29. file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
  30. return list_files()
  31. if __name__ == "__main__":
  32. app.run()