基于django的简单ftp实现

来源:互联网 发布:香港城市大学 知乎 编辑:程序博客网 时间:2024/05/17 23:31

目标环境 在d:/web/

1. 建立工程

D:\web>django-admin startproject ftp

D:\web>python manage.py startapp sample

2.修改sample/models.py添加对象

class PathItem:    name = ""    parent = ""    url = ""    def __init__(self, name, parent):        self.name = name        self.parent = parent        self.url = "folder/" + os.path.join(parent, name)class FileItem:    name = ""    parent = ""    url = ""    canRead = False    def __init__(self, name, parent):        self.name = name        self.parent = parent        self.url = "file/" + os.path.join(parent, name)

3.修改views.py

def index(request):    current = 'd:/'    context_dic = {}    context_dic['current'] = current    ps = os.listdir(current)    path = []    file = []    for n in ps:        v = os.path.join(current, n)        if os.path.isdir(v):            p = PathItem(n, current)            path.append(p)        else:            f = FileItem(n, current)            file.append(f)    context_dic['path'] = path    context_dic['file'] = file    return render(request, 'index.html', context_dic)def show_folder(request, url):    current = url    context_dic = {}    context_dic['current'] = current    ps = os.listdir(current)    path = []    file = []    for n in ps:        v = os.path.join(current, n)        if os.path.isdir(v):            p = PathItem(n, current)            path.append(p)        else:            f = FileItem(n, current)            file.append(f)    #context_dic['parent'] = os.path.pardir(url)    context_dic['path'] = path    context_dic['file'] = file    return  render(request, 'index.html', context_dic)

4.添加sample\templaste\index.html

<html><head>    <title>Title</title></head>    {% if current %}    <h1>        {{ current}}    </h1>    <br>        {% if parent %}        <a href="{{ parent }}">../</a>        {% endif %}        {% if path %}            {% for p in path %}            <a href="{{p.name}}">{{  p.name }}</a>            </br>            {% endfor %}        {% endif %}        <p>-----</p>        {% if file %}            {% for f in file %}                {% if f.canRead %}                    <a href="{{ f.url }}">{{ f.name }}</a></br>                {% else %}                    {{ f.name }}</br>                {% endif %}            {% endfor %}        {% else %}        file not exist        {% endif %}    </body>{% endif %}</html>

5.修改ftp/setting.py

添加app

INSTALLED_APPS = [    ....,    'sample',]

添加模板路径
TEMPLATE_PATH = os.path.join(BASE_DIR, 'sample/template')TEMPLATES = [    {        'DIRS': [TEMPLATE_PATH,],

6.修改ftp/urls.py

from sample import viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^folder/(?P<url>.+)/$', views.show_folder),    url(r'^$', views.index),]

7.运行

D:\web>python manage.py runserver

8.访问

http://127.0.0.1:8000



原创粉丝点击