s3_4.py 884 B

123456789101112131415161718192021222324252627
  1. def upload_file(file, chalid):
  2. access_key_id = utils.get_app_config('ACCESS_KEY_ID')
  3. secret_access_key = utils.get_app_config('SECRET_ACCESS_KEY')
  4. if access_key_id and secret_access_key:
  5. s3 = boto3.client(
  6. 's3',
  7. aws_access_key_id=access_key_id,
  8. aws_secret_access_key=secret_access_key
  9. )
  10. bucket = utils.get_app_config('BUCKET')
  11. else:
  12. s3 = boto3.client('s3')
  13. bucket = utils.get_app_config('BUCKET')
  14. filename = filter(clean_filename, secure_filename(file.filename).replace(' ', '_'))
  15. if len(filename) <= 0:
  16. return False
  17. md5hash = hashlib.md5(os.urandom(64)).hexdigest()
  18. key = md5hash + '/' + filename
  19. s3.upload_fileobj(file, bucket, key)
  20. db_f = Files(chalid, key)
  21. db.session.add(db_f)
  22. db.session.commit()
  23. return db_f.id, (md5hash + '/' + filename)