Hello 
I'm new to flask and i am trying to upload files i have as attributes 
filename data and type(meaning extension of the file) this is my app.py 
code :  
 import base64
from fileinput import filename
from io import BytesIO
from optparse import Values
import string
from typing import Any
from flask_cors import CORS, cross_origin
from flask import Flask , render_template, request , send_file, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource, reqparse 
from werkzeug.utils import secure_filename
import os

app= Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONs'] = False

db = SQLAlchemy(app)
api = Api(app)

app.secret_key = "caircocoders-ednalan"

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 
'docx', 'pptx' , 'xlsx'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in 
ALLOWED_EXTENSIONS

class Upload(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(50))
    data = db.Column(db.LargeBinary)
    ext = db.Column(db.String(50))

    def __init__(self, filename, data, ext):
        self.filename = filename
        self.ext = ext
    
    def json(self): 
        return {"id":self.id , "filename":self.filename , "ext":self.ext }


class ProductsView(Resource):
    def get(self):
        files = Upload.query.all()
        return {f'Files':list(x.json() for x in files)}

api.add_resource(ProductsView, '/files')

@app.route('/views', methods=['GET'])
def views():
    """files = Upload.query.all()
    return render_template('view.html', values=Upload.query.all())"""
    files = Upload.query.all()
    return jsonify({'Files': 
list(dict(id=x.id,data=str(x.data),filename=x.filename, ext=x.ext) for x in 
files )})

@app.route('/' , methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file= request.files['file']
        ext = os.path.splitext(file.filename)
        file.ext = ext[1]
        upload = Upload(filename=file.filename, data=file.read(), 
ext=file.ext) 
        db.session.add(upload)
        db.session.commit()
        return f'Uploaded: {file.filename}' 
    return render_template('index.html')

@app.route('/upload' , methods=['POST'])
def upload_file():
    # check if the post request has the file part
    if 'files[]' not in request.files:
        resp = jsonify({'message' : 'No file part in the request'})
        resp.status_code = 400
        return resp

    files = request.files.getlist('files[]')

    errors = {}
    success = False

    for file in files:      
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            ext = os.path.splitext(filename)
            file.ext = ext[1]
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            success = True
            upload = Upload(filename=file.filename, ext=file.ext, 
data=base64.b64encode(file.read())) 
            db.session.add(upload)
            db.session.commit()
            return f'Uploaded: {file.ext}'
        else:
            errors[file.filename] = 'File type is not allowed'

    if success and errors:
        errors['message'] = 'File(s) successfully uploaded'
        resp = jsonify(errors)
        resp.status_code = 500
        return resp
    if success:
        upload = Upload(filename=file.filename, ext=file.ext, 
data=base64.b64encode(file.read())) 
        db.session.add(upload)
        db.session.commit()
        """return f'Uploaded: {file.filename}'"""
        resp = jsonify({'message' : 'Files successfully uploaded'})
        resp.status_code = 201
        return resp
    else:
        resp = jsonify(errors)
        resp.status_code = 500
        return resp




@app.route('/file/<upload_id>')
def get(upload_id):
    product = Upload.query.filter_by(id=upload_id).first()
    if product:
        return product.json()
    return {'message':'Product id not found'},404


@app.route('/download/<upload_id>')
def download(upload_id):
    upload = Upload.query.filter_by(id=upload_id).first()
    return send_file(BytesIO(upload.data), 
attachment_filename=upload.filename , as_attachment=True)

@app.route('/delete/<upload_id>')
def delete(upload_id):
    f = Upload.query.filter_by(id=upload_id).first()
    if f: 
        db.session.delete(f)
        db.session.commit()
        return {'message':'Deleted'}
    else:
        return {'message':'File not found'},404

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sqlalchemy/b811cc6d-fceb-45de-ab36-d5428cee0366n%40googlegroups.com.

Reply via email to