programing

url_for를 사용하여 Flask 정적 파일에 링크

topblog 2023. 8. 16. 21:53
반응형

url_for를 사용하여 Flask 정적 파일에 링크

사용 방법url_for폴더의 파일을 참조하기 위해 플라스크에서?예를 들어, 몇 가지 정적 파일이 있습니다.static폴더, 그 중 일부는 다음과 같은 하위 폴더에 있을 수 있습니다.static/bootstrap.

다음에서 파일을 제공하려고 할 때static/bootstrap오류가 발생했습니다.

 <link rel=stylesheet type=text/css href="{{ url_for('static/bootstrap', filename='bootstrap.min.css') }}">

이것으로 하위 폴더에 없는 파일을 참조할 수 있습니다.

 <link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">

정적 파일을 참조하는 올바른 방법은 무엇입니까?url_for사용 방법url_for어떤 수준의 정적 파일에 대한 URL을 생성할 수 있습니까?

기본적으로 정적 파일의 끝점이 있습니다.또한 응용 프로그램에는 다음과 같은 인수가 있습니다.

static_url_path웹의 정적 파일에 대해 다른 경로를 지정하는 데 사용할 수 있습니다.의 이름으로 기본 설정됩니다.static_folder폴더를 누릅니다.

static_folder제공되어야 하는 정적 파일이 있는 폴더static_url_path응용 프로그램의 루트 경로에 있는 'static' 폴더로 기본 설정됩니다.

그것은 의미는filename인수는 파일에 대한 상대 경로를 사용합니다.static_folder그리고 그것을 결합된 상대 경로로 변환합니다.static_url_default:

url_for('static', filename='path/to/file')

에서 파일 경로를 변환합니다.static_folder/path/to/fileURL 경로로static_url_default/path/to/file.

그래서 만약 당신이 파일을 얻고 싶다면.static/bootstrap이 코드를 사용하는 폴더:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

(기본 설정 사용)으로 변환할 대상:

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

설명서도 참조하십시오.

저의 경우 nginx 구성 파일에 대한 특별 지침이 있었습니다.

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

nginx는 플라스크에 대해 알려진 것이 없기 때문에 모든 고객은 '404'를 받았습니다.

기본 구성 파일은 다음과 같습니다./etc/nginx/nginx.conf리눅스에서.Windows에서도 유사할 수 있습니다.

언급URL : https://stackoverflow.com/questions/16351826/link-to-flask-static-files-with-url-for

반응형