myblog_3_文件查詢_視圖查詢接口實現(xiàn)
一. 文件管理方法實現(xiàn)
- 在blog_model目錄下新建file_models.py
- 因為不使用django的orm模型也就不用它的models文件了
1.獲取文件分級目錄(作為欄目分類)
import os
from blog_manages.settings import BASE_DIR
file_path = os.path.join(BASE_DIR, 'data_box')
# 使用遞歸方法列出目錄下的所有文件子目錄及子目錄的文件
def get_path(path):
results = []
paths = os.listdir(path)
# print(paths)
for a in paths:
a_path = os.path.join(path, a)
if os.path.isdir(a_path):
data = get_path(a_path)
results.append({'count': len(data), a: data})
else:
results += [a]
return results
if __name__ == '__main__':
print(get_path(file_path))
# 執(zhí)行結(jié)果
'''
[{'count': 0, '網(wǎng)絡工程': []},
{'count': 9, 'linux': ['linux_python_讓python代碼像系統(tǒng)命令一樣運行_高仿系統(tǒng)日歷.md',
'linux_防火墻_contos.md',
'排序算法_選擇_冒泡_歸并.md',
'Ubuntu踩坑記錄.md', 'Linux命令.md',
'Git版本控制.md',
'linux_vim_操作命令和技巧.md',
'python_pip_使用技巧.md',
'2019-04-28.md']},
{'count': 7, 'Python': [{'count': 3, 'Python_進階':
['Python多進程.md',
'對象的setattr_getattr(對象的騷操作).md', 'Python裝飾器_上下文語法_中間件.md']},
'資料_Python-_常見數(shù)據(jù)類型的內(nèi)建函數(shù)_持續(xù)更新.md', '資料_控制臺格式化輸出-%.md',
'資料_markdown快速入門.md',
'資料_ASCII碼表.md'
......
'''
2.獲取文件的詳細路徑
def get_file_path(path):
results = []
paths = os.listdir(path)
# print(paths)
for a in paths:
# print(a)
a_path = os.path.join(path, a)
if os.path.isdir(a_path):
data = get_file_path(a_path)
results += data
else:
results += [a_path.split(file_path)[1]]
return results
if __name__ == '__main__':
for i in get_file_path(file_path):
print(i)
# 執(zhí)行結(jié)果
'''
/前端_html5/html_element_響應式樣式布局.md
/前端_html5/html_vue_響應式數(shù)據(jù)更新.md
/數(shù)據(jù)庫/rides命令.md
/數(shù)據(jù)庫/mysql安裝.md
/數(shù)據(jù)庫/mariadb安裝.md
/數(shù)據(jù)庫/python_pymysql操作.md
/數(shù)據(jù)庫/MongoDB.md
/數(shù)據(jù)庫/mysql命令總結(jié)( 不帶select:查找數(shù)據(jù)).md
/note_學習筆記/Python_基礎_homework/python_day13_homework.md
/note_學習筆記/Python_基礎_homework/python_day14_homework.md
/note_學習筆記/Python_基礎_homework/python_day4_homework.md
/note_學習筆記/Python_基礎_homework/python_day11_homework.md
......
'''
3.獲取文件的內(nèi)容
def get_file(path):
with open(file_path + path, 'r')as f:
data = f.read()
return {
'path': path,
'title': path.split('/')[-1][:-3],
'content': data
}
if __name__ == '__main__':
print(get_file('/linux/排序算法_選擇_冒泡_歸并.md'))
# 執(zhí)行結(jié)果
'''
{'path': '/linux/排序算法_選擇_冒泡_歸并.md', 'title': '排序算法_選擇_冒泡_歸并', 'content': '###歸并排序\n```\n"""歸并排序"""\n\n\ndef merger_sort(items, le=lambda x, y: x <= y):\n """歸并"""\n if len(items) <= 1:\n return items\n mid = len(items) // 2\n items1 = merger_sort(items[:mid], le)\n items2 = merger_sort(items[mid:], le)\n return merger(items1, items2, le)\n\n\ndef merger(items1: list, items2: list, le=lambda x, y: x <= y )
......
'''
二. 實現(xiàn)內(nèi)存緩存
原計劃二階段實現(xiàn)的, 但是發(fā)現(xiàn)我所有的文檔(107個)不到900k
先用一個簡單的字典實現(xiàn)文件目錄的緩存
import os
from blog_manages.settings import BASE_DIR
file_path = os.path.join(BASE_DIR, 'data_box')
ram_cache_list = {}
def ram_cache(func):
def inner(path):
if path not in ram_cache_list.keys():
data = func(path)
ram_cache_list[path] = data
return data
return ram_cache_list[path]
return inner
@ram_cache
def get_file(path):
print('查看程序執(zhí)行次數(shù)')
with open(file_path + path, 'r')as f:
data = f.read()
return {
'path': path,
'title': path.split('/')[-1][:-3],
'content': data
}
if __name__ == '__main__':
print(get_file('/linux/排序算法_選擇_冒泡_歸并.md'))
print(ram_cache_list)
print(get_file('/linux/排序算法_選擇_冒泡_歸并.md'))
'''
查看程序執(zhí)行次數(shù)
{'path': '/linux/排序算法_選擇_冒泡_歸并.md', 'title': '排序算法_
{'/linux/排序算法_選擇_冒泡_歸并.md': {'path': '/linux/排序算法
{'path': '/linux/排序算法_選擇_冒泡_歸并.md', 'title': '排序算法_
'''
三. 視圖接口測試
1. 配置templates
- blog_manages ->settings.py
# 添加os.path.join(BASE_DIR, "templates"),
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates"), ],
'APP_DIRS': True,
2.寫測試視圖index
- blog_ user - > views.py
def index(request):
return render(request, 'blog_web/index.html')
- templates -> blog_web ->index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>主頁測試</h1>
</body>
</html>
3. 配置路由
- blog_manages - > urls.py
urlpatterns = [
# path('admin/', admin.site.urls),
path('web/', include('blog_user.urls',))
]
- blog_ user - > urls.py(新建urls.py文件)
from django.urls import path
import blog_user.views as v
urlpatterns = [
path('index/', v.index),
]
4. 測試
虛擬環(huán)境的終端輸入 python manage.py runserver
瀏覽器訪問下面地址 能看到主頁測試,沒看到證明打開的方式不對
http://127.0.0.1:8000/web/index/
四. 寫接口
1. 欄目分類查詢接口
- viwes
def cloumn(request):
return JsonResponse({
'code': 200,
'data': f.get_path(f.file_path)
})
- urls
from django.urls import path
import blog_user.views as v
urlpatterns = [
path('index/', v.index),
path('column/', v.cloumn),
]
- 測試
因為django默認的是 debug模式 只需要ctrl+s 程序就好重新執(zhí)行
http://127.0.0.1:8000/web/column/
2. 文章詳情接口
- viwes
def article(request, path1, path2):
return JsonResponse(f.get_file('/'+path1+'/'+path2))
- urls
path('article/<str:path1>/<str:path2>', v.article),
- 測試
因為django默認的是 debug模式 只需要ctrl+s 程序就好重新執(zhí)行
http://127.0.0.1:8000/web/article/linux/排序算法_選擇_冒泡_歸并.md
ok 今天就到這里 獲取文章詳情還有一個bug 擁有二級目錄(二級分類)
文章訪問會出現(xiàn)404