ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Bottle] 3. Routing 3 - 정적파일 라우트, 에러 페이지, 리다이렉트
    Python/Bottle 2019. 9. 2. 23:45
    반응형

    [Python web framework: Bottle] 3. Routing 3 ROUTING STATIC FILES

    CSS나 이미지 파일 등을 정적파일이라고 부릅니다.

    root='./static' 으로 설정하고 작업 디렉토리 아래에 '/static' 디렉토리를 만들면 됩니다. 

    작업 디렉토리(./)와 프로젝트 디렉토리가 항상 동일한 것은 아니기 때문에 주의해야 합니다. 

    from bottle import route, static_file, run
    
    
    @route('/static/<filename>')
    def server_static(filename):
        return static_file(filename, root='/path/to/your/static/files')  # 1
        # return static_file(filename, root='./static')
    
    
    run(host='localhost', port=8080, debug=True)
    

    static_file 함수는 <filename>이 직접적으로 정해진 디렉토리에만 접근할 수 있도록 제한함으로 안전하고 편리하게 파일들을 제공(serve)하도록 도와줍니다. 

     

    만약 그 서브디렉토리의 파일까지 제공(serve)하려면 와일드카드에 path 필터를 걸어주면 됩니다. 

    @route('/static/<filepath:path>')
    def server_static(filepath):
        return static_file(filepath, root='/path/to/your/static/files')

    강제 다운로드도 가능합니다. 

    @route('/download/<filename:path>')
    def download(filename):
        return static_file(filename, root='/path/to/static/files', download=filename)

    download=True 로 하면 원 파일명으로 다운로드 됩니다. 

    ERROR PAGES

    from bottle import error
    @error(404)
    def error404(error):
        return 'Nothing here, sorry

    설명할 것이 별로 없어보입니다. 

    from bottle import route, abort
    @route('/restricted')
    def restricted():
        abort(401, "Sorry, access denied.")

    REDIRECTS

    from bottle import redirect
    @route('/wrong/url')
    def wrong():
        redirect("/right/url")
    반응형
Designed by Tistory.