source

플라스크와 함께 Create-React-App으로 만든 프런트 엔드를 제공합니다.

nicesource 2023. 2. 10. 22:04
반응형

플라스크와 함께 Create-React-App으로 만든 프런트 엔드를 제공합니다.

Create-React-app을 사용하여 만든 React 단일 페이지 응용 프로그램에서 액세스하는 API 루트가 포함된 플라스크 백엔드가 있습니다.create-react-app dev server를 사용할 때는 플라스크 백엔드가 작동합니다.

.npm run build스태틱 리액션 앱React 앱을 구축하면 다음과 같은 디렉터리 구조가 생성됩니다.

- build
  - static
    - css
        - style.[crypto].css
        - style.[crypto].css.map
    - js
        - main.[crypto].js
        - main.[crypto].js.map
  - index.html
  - service-worker.js
  - [more meta files]

★★★★★★★★★★★★★★★★의[crypto]빌드 시에 랜덤으로 생성된 스트링을 말합니다.

「 」를 .index.html그러면 브라우저는 다음 요청을 합니다.

- GET /static/css/main.[crypto].css
- GET /static/css/main.[crypto].css
- GET /service-worker.js

이 파일들은 어떻게 전달해야 하나요?내가 생각해낸 건 이거야

from flask import Blueprint, send_from_directory

static = Blueprint('static', __name__)

@static.route('/')
def serve_static_index():
    return send_from_directory('../client/build/', 'index.html')

@static.route('/static/<path:path>') # serve whatever the client requested in the static folder
def serve_static(path):
    return send_from_directory('../client/build/static/', path)

@static.route('/service-worker.js')
def serve_worker():
    return send_from_directory('../client/build/', 'service-worker.js')

이렇게 하면 정적 자산이 정상적으로 처리됩니다.

한편, 플라스크에 내장된 정적 유틸리티에 통합할 수도 있습니다.단, 이 설정 방법을 이해할 수 없습니다.

솔루션이 충분히 견고합니까?내장 플라스크 기능을 사용하여 이러한 자산을 제공할 수 있는 방법이 있습니까?create-react-app을 사용하는 더 좋은 방법이 있나요?

import os
from flask import Flask, send_from_directory

app = Flask(__name__, static_folder='react_app/build')

# Serve React App
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists(app.static_folder + '/' + path):
        return send_from_directory(app.static_folder, path)
    else:
        return send_from_directory(app.static_folder, 'index.html')


if __name__ == '__main__':
    app.run(use_reloader=True, port=5000, threaded=True)

그것이 내가 결국 하게 된 것이다.따라서 기본적으로 모든 경로를 캐치하고 경로가 파일 = > send file = > send index.delays 인지를 테스트합니다.이렇게 하면 원하는 경로에서 리액트 앱을 새로고침할 수 있으며 고장도 나지 않습니다.

은 을 해야 합니다.npm run build한 바와 스태틱 .

from flask import Flask, render_template

app = Flask(__name__, static_folder="build/static", template_folder="build")

@app.route("/")
def hello():
    return render_template('index.html')

print('Starting Flask!')

app.debug=True
app.run(host='0.0.0.0')

아쉽게도 개발 핫 새로고침으로는 작업을 할 수 없을 것 같습니다.

여기에서는 유효한 해결책입니다.두가 따로 해 본 적 요?static ★★★★★★★★★★★★★★★★★」templates장판판 분리 ?? ????,, 둘, 둘, 둘, 둘, 둘, 둘, 둘, 둘, 둘, but, but, but, but, but, but, but, but, but, but, but, but, but, but, but for, for, for, for, for, for, for, for, for, , , for, for,static ★★★★★★★★★★★★★★★★★」templates파일 형식과 모든 종속성이 이와 같이 연결되어 있습니다.

build는 둘 다라고 .static ★★★★★★★★★★★★★★★★★」templates.

이런 걸 쓰세요.

from flask import Flask, render_template

app = Flask(__name__, static_url_path='',
                  static_folder='build',
                  template_folder='build')

@app.route("/")
def hello():
    return render_template("index.html")

당신의 플라스크 앱은 잘 작동될 것입니다.

받아들여진 답변은 나에게 효과가 없다.사용한 적이 있다

import os

from flask import Flask, send_from_directory, jsonify, render_template, request

from server.landing import landing as landing_bp
from server.api import api as api_bp

app = Flask(__name__, static_folder="../client/build")
app.register_blueprint(landing_bp, url_prefix="/landing")
app.register_blueprint(api_bp, url_prefix="/api/v1")


@app.route("/")
def serve():
    """serves React App"""
    return send_from_directory(app.static_folder, "index.html")


@app.route("/<path:path>")
def static_proxy(path):
    """static folder serve"""
    file_name = path.split("/")[-1]
    dir_name = os.path.join(app.static_folder, "/".join(path.split("/")[:-1]))
    return send_from_directory(dir_name, file_name)


@app.errorhandler(404)
def handle_404(e):
    if request.path.startswith("/api/"):
        return jsonify(message="Resource not found"), 404
    return send_from_directory(app.static_folder, "index.html")


@app.errorhandler(405)
def handle_405(e):
    if request.path.startswith("/api/"):
        return jsonify(message="Mehtod not allowed"), 405
    return e


CRA(Create react app) 빌드폴더에서 index.html 파일을 읽는 루트 /가 1개뿐인 플라스크 서버를 사용했습니다.

from flask import Flask
app = Flask(__name__)
app.static_folder =  '../build'

@app.route('/')
def index():
    fref = open(r'../build/index.html')
    html_text = fref.read()
    fref.close()
    return html_text

app.run()

이렇게 설정하면 경로 불일치로 인해 정적 파일이 제대로 처리되지 않기 때문에 사용한 솔루션은 다음과 같습니다.

  1. 홈페이지 속성을 패키지에 추가합니다.CRA의 json을 "/static"으로 설정합니다.

{ "name" ""App-name", "version":", "dependencies":{} "홈페이지":/static",....[기타 키]}

 Add **homepage** key parallel to the **dependencies** key in the package.json file
  1. 홈페이지 속성은 CRA 빌드 프로세스 중에 사용되며 index.html의 %PUBLIC_URL% 대신 사용되며 다른 정적 자산의 URL 경로에 추가됩니다(빌드 프로세스 후에 index.html 코드를 표시하여 확인할 수 있습니다).

  2. 빌드 프로세스 후 플라스크 서버를 실행하면 /와 함께 제공되는 GET 요청을 확인할 수 있으며, index.html이 처리되고 이어서 HTML 파일의 기타 정적 자산에 대한 요청 /static/js/[filename]이 처리되어 모든 것이 정상적으로 동작합니다.

언급URL : https://stackoverflow.com/questions/44209978/serving-a-front-end-created-with-create-react-app-with-flask

반응형