Skip to content

Instantly share code, notes, and snippets.

@mysteriousHerb
Last active June 10, 2019 05:51
Show Gist options
  • Save mysteriousHerb/bb10372e90c41e648a422663a3b210e9 to your computer and use it in GitHub Desktop.
Save mysteriousHerb/bb10372e90c41e648a422663a3b210e9 to your computer and use it in GitHub Desktop.
backend/app.py
from flask import Flask, render_template, jsonify, request, send_from_directory
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api
from flask_cors import CORS
# https://flask-marshmallow.readthedocs.io/en/latest/
from flask_marshmallow import Marshmallow
from werkzeug.utils import secure_filename
import os
class FileEntry(db.Model):
id = db.Column("file_id", db.Integer, primary_key=True)
user_name = db.Column(db.String)
filepath = db.Column(db.String)
class FileEntrySchema(ma.ModelSchema):
class Meta:
model = FileEntry
# if the database does not exist, use db.create_all()
def initialize_database():
try:
Todo.query.get(1)
except:
db.create_all()
# put some place holder data
todo0 = Todo(content="buy food", done=False)
file_entry_0 = FileEntry(user_name="Tian", filepath='C:')
# add and then commit to apply changes
db.session.add(todo0)
db.session.add(file_entry_0)
db.session.commit()
# delete use: db.session.delete(me)
ALLOWED_EXTENSIONS = ["txt", "pdf", "png", "jpg", "jpeg", "gif"]
def allowed_file(filename):
# string.rsplit(separator, max) Specifies how many splits to do.
if "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS:
return True
else:
return False
class upload_file(Resource):
def get(self):
file_entries = FileEntry.query.all()
file_entries_schema = FileEntrySchema(many=True)
output = file_entries_schema.dump(file_entries)
return output
def post(self):
file = request.files.get('file')
if file:
if file.filename == "":
return {"message": "No file found", "status": "error"}
elif allowed_file(file.filename) is True:
# https://werkzeug.palletsprojects.com/en/0.15.x/utils/#werkzeug.utils.secure_filename
filename = secure_filename(file.filename)
filename_no_extension = filename.rsplit(".", 1)[0]
existed_entry = FileEntry.query.filter_by(user_name=filename_no_extension).first()
if existed_entry is None:
file_entry = FileEntry(user_name=filename_no_extension, filepath=os.path.join(app.config["UPLOAD_FOLDER"], filename))
db.session.add(file_entry)
else:
# if the user_name already exist, remove the existing file and update the db entry
os.remove(existed_entry.filepath)
existed_entry.filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
db.session.commit()
file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
return {
"filename": filename,
"message": "file uploaded",
"status": "success",
}
# same api can accept other arguments for file system modification, using json to communicate
file_upload_args = request.get_json()
print(file_upload_args)
if "cancel_upload" in file_upload_args:
filename = file_upload_args["cancel_file"]
filename = secure_filename(file.filename)
filename_no_extension = filename.rsplit(".", 1)[0]
existed_entry = FileEntry.query.filter_by(user_name=filename_no_extension).first()
db.session.delete(existed_entry)
db.session.commit()
try:
os.remove(os.path.join(app.config["UPLOAD_FOLDER"], filename))
except FileNotFoundError:
print('file is already deleted')
class download_file(Resource):
# http://flask.pocoo.org/docs/1.0/patterns/fileuploads/
def get(self):
return send_from_directory(app.config["UPLOAD_FOLDER"], "alex.jpg", as_attachment=True)
api.add_resource(todo_database_access, "/todo_db")
api.add_resource(upload_file, "/upload_file")
api.add_resource(download_file, "/download_file")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment