# 7.1 静态文件访问原理

## 1.默认访问方法

Flask访问静态文件非常简单，只需要在项目根目录建立static文件夹。将静态资源文件放入static下即可。访问的时候访问`http://ip:port/static/fileName`即可。

需要注意的是，这里的根目录并不是项目的根目录fisher，而是app目录。这是因为，我们在实例化Flask核心对象的时候，传入了\_\_name\_\_参数，这个 \_\_name\_\_指向的就是当前文件所在目录。

![image.png](https://upload-images.jianshu.io/upload_images/7220971-8f6488aafcc6c931.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240)

## 2.修改默认存储路径

修改默认存储路径，只需要在实例化Flask核心对象的时候，传入static\_folder这个关键字参数即可，但是这个时候，访问的路径应该变成`http://ip:port/static_folder的最后一级/fileName`，如果想自定义url访问路径，传入关键字参数static\_url\_path即可

```python
app = Flask(__name__, static_folder="statics", static_url_path="/static")
```

## 3.核心原理

在Flask的app.py的Flask类的构造函数的地556行，是注册静态资源视图函数的源码，可以看到实际上就是通过我们之前所讲到的add\_url\_rule注册了一个视图函数。其中的访问url路径，就是获取了static\_url\_path

```python
        if self.has_static_folder:
            assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'
            self.add_url_rule(
                self.static_url_path + '/<path:filename>',
                endpoint='static',
                host=static_host,
                view_func=self.send_static_file
            )
```

下面是static\_url\_path的定义，可以看到他是调用了\_get\_static\_url\_path方法。 这个方法首先获取static\_url\_path关键字参数，如果有，则直接将其作为url访问路径，否则获取static\_folder关键字参数，如果有，则取他的基本路径拼拼接上"/"作为url访问路径

```python
    def _get_static_url_path(self):
        if self._static_url_path is not None:
            return self._static_url_path

        if self.static_folder is not None:
            return '/' + os.path.basename(self.static_folder)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://flask-yushu.gitbook.io/yushu/7.-jing-tai-wen-jian-mo-ban-xiao-xi-shan-xian-yu-jinja2/7.1-jing-tai-wen-jian-fang-wen-yuan-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
