简体   繁体   中英

Sending static files in Flask

After reading this question and the documentation here I've written a function that should return a static resource(html, css and javascript files):

server.py

import json
import random
import string
import re

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from app import app
from flask import Flask, jsonify, request, render_template
from database_helpers import query_db, insert_db
from werkzeug.security import generate_password_hash, check_password_hash

# set the project root directory as the static folder, you can set others.
# cwd = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, static_url_path='')
# url_for('static', filename='style.css')

@app.route('/')
def index():
    # This works
    # return "Test test test."
    # This doesn't 
    return app.send_static_file('welcome.html')

The project layout directory is:

项目布局

Does the static path have to be absolute or relative to the current working directory? I'm working on windows. Does this imply that slashes backward slashes should be added to all paths present in server.py ?

Each request receives a 404 response.

Commenting out the line that defines the static URL path fixed the issue:

server.py

import json
import random
import string
import re

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from app import app
from flask import Flask, jsonify, request, render_template
from database_helpers import query_db, insert_db
from werkzeug.security import generate_password_hash, check_password_hash

@app.route('/')
def index():
    # This works
    # return "Test test test."
    # This doesn't 
    return app.send_static_file('welcome.html')

However, the styles and images are not sent.

In order to send the static content required by an html file, it must be referenced relatively to the root path. For example, if index.html has an image:

<img src="favicon.ico"/>

then its source must be changed so as to point in the static directory where favicon.ico is located:

<img src="static/favicon.ico"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM