python

Flask & React 연결 (w/ s3)

jaeha_lee 2024. 1. 23. 00:15

프론트엔드 (React)

  1. React 앱 생성:
  2. npx create-react-app s3-image-app cd s3-image-app
  3. 필요한 라이브러리 설치:
  4. npm install axios

물론, 디자인을 별도의 CSS 파일로 분리하는 방법도 있습니다. 아래는 styled-components 대신에 외부 CSS 파일을 사용하는 방법입니다.

프론트엔드 (React) - CSS 파일 추가

  1. src/components/ImageGrid.js 컴포넌트 수정:
// src/components/ImageGrid.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './ImageGrid.css';

const ImageGrid = ({ imagePaths }) => {
  const [images, setImages] = useState([]);

  useEffect(() => {
    axios.post('http://localhost:5000/images', { imagePaths })
      .then(response => {
        setImages(response.data);
      })
      .catch(error => {
        console.error('Error fetching images:', error);
      });
  }, [imagePaths]);

  return (
    <div className="image-grid">
      {images.map((image, index) => (
        <div key={index} className="frame">
          <img src={`data:image/png;base64,${image.data}`} alt={`Image ${index}`} />
        </div>
      ))}
    </div>
  );
};

export default ImageGrid;
  1. src/components/ImageGrid.css 파일 생성:
/* src/components/ImageGrid.css */
.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.frame {
  border: 2px solid #ddd;
  padding: 8px;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s ease-in-out;
}

.frame:hover {
  transform: scale(1.05);
}

.frame img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}
  1. src/App.js에서 ImageGrid 컴포넌트 사용:
// src/App.js
import React from 'react';
import ImageGrid from './components/ImageGrid';
import './App.css';

const App = () => {
  const imagePaths = [
    's3://your_bucket/image1.png',
    's3://your_bucket/image2.png',
    's3://your_bucket/image3.png',
    // Add more image paths as needed
  ];

  return (
    <div className="App">
      <ImageGrid imagePaths={imagePaths} />
    </div>
  );
};

export default App;
  1. src/App.css 파일 생성 (프로젝트 전체 스타일을 관리하는 파일):
/* src/App.css */
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #f8f9fa;
}

.App {
  text-align: center;
}

/* Add more global styles as needed */

이렇게 하면 ImageGrid 컴포넌트의 스타일이 ImageGrid.css 파일에서 분리되어 관리됩니다. 필요한 경우, 추가적인 CSS 파일을 생성하여 스타일을 분리할 수 있습니다.

백엔드 (Flask 및 Smart Open 사용)

  1. Flask 애플리케이션 작성 (app.py):
  2. # app.py from flask import Flask, request, jsonify from smart_open import open from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/images', methods=['POST']) def get_images(): image_paths = request.json.get('imagePaths', []) image_data = read_images_from_s3(image_paths) return jsonify(image_data) def read_images_from_s3(image_paths): image_data = [] for path in image_paths: try: with open(path, 'rb') as file: data = file.read() image_data.append({'url': path, 'data': data}) except Exception as e: print(f"Error reading image from {path}: {str(e)}") return image_data if __name__ == '__main__': app.run(debug=True)

위 코드는 기본적인 구조를 제공하며, 프로젝트의 실제 요구 사항에 따라 수정이 필요할 수 있습니다. 또한, 보안 및 예외 처리 부분은 실제 프로덕션 환경에서는 더 신경 써야 하는 부분입니다. 코드를 변경하면서 발생하는 문제에 대비하여 적절한 에러 핸들링과 보안 검토를 수행하십시오.

 

---

Smart open 사용 시 아래 참고

import pandas as pd
from smart_open import smart_open

aws_key = 'AKIAxxxxx'
aws_secret = 'VNdBVtxxxxx'

bucket_name = 'victor-seoul'
file_name = 'million_song/YearPredictionMSD.txt'

path = 's3://{}:{}@{}/{}'.format(aws_key, aws_secret, bucket_name, file_name)

df = pd.read_csv(smart_open(path), header=None)

 

https://kimjingo.tistory.com/87

 

[Python] boto3를 이용한 Flask-S3 연동 (파일 업로드 및 다운로드)

boto3 설치 pip install boto3 s3 config file 정의 # m_config.py AWS_ACCESS_KEY = "SDKNFLWKEFNWEFKEFJA" AWS_SECRET_ACCESS_KEY = "fWEKLFWKLENWK" AWS_S3_BUCKET_REGION = "ap-northeast-2" AWS_S3_BUCKET_NAME = "file-storage" s3 connect 함수 및 파일 업

kimjingo.tistory.com

 

https://www.geeksforgeeks.org/read-file-without-saving-in-flask/

 

Read File Without Saving in Flask - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

https://github.com/getcrest/smart-open