Example #1
0
def showUploadPage(request, username, path):
    '''
    Show a page for user to select a file to upload.

    username: The user that the file will belone to.(Later users may be able to access other's files, so then username might be different to request.username)
    path: The path to upload to.

    Return a httpRespond.
    '''
    if not request.user.is_authenticated() or not request.user.username == username:
        return showMessagePage(request, '错误', '您没有权限')

    if request.method == "POST":
        form = UploadForm(request.POST,request.FILES)
        if form.is_valid():
            cd = form.cleaned_data

            # Save the file
            path = form.cleaned_data['path']
            fullPath = os.path.join(settings.USER_FILE_PATH, escapePath(username), escapePath(path), os.path.split(cd['file'].name)[-1])
            if not os.path.exists(os.path.dirname(fullPath)):
                os.makedirs(os.path.dirname(fullPath))
            if cd['override'] and os.path.exists(fullPath):
                    os.remove(fullPath)
            if not os.path.exists(fullPath):
                saveUploadedFile(cd['file'], fullPath)
                return showMessagePage(request, '操作成功', u'您成功上传了文件"%s"' % os.path.basename(fullPath), next = './')
            else:
                return showMessagePage(request, '同名文件', '发现同名文件。请选择覆盖文件以继续上传')
    form = UploadForm(initial = dict({'path': path}.items() + request.POST.items()))
    return render(request, 'fileManager/upload.html',
        dict({'form':form,
              'path': path}.items() + csrf(request).items()))
Example #2
0
def showFileOrFolder(request, username, path):
    '''
    Show things in the path.

    username: The user that the file will belone to.(Later users may be able to access other's files, so then username might be different to request.username)
    path: The path to be shown.

    Return a httpRespond.
    '''
    if not request.user.is_authenticated() or not request.user.username == username:
        return showMessagePage(request, '错误', '您没有权限')

    fullPath = os.path.join(settings.USER_FILE_PATH, escapePath(username), escapePath(path))

    if request.method in ('GET', 'POST') and os.path.exists(fullPath):
        if request.method == 'GET': # Show confirm page
            if 'delete' in request.GET:
                return render(request, 'fileManager/deleteConfirm.html', dict({'path': path}.items() + csrf(request).items()))
            elif 'rename' in request.GET:
                return render(request, 'fileManager/renameForm.html', dict({'path': path,
                                                                            'form': RenameForm(initial = {'path' : path}),
                                                                            }.items() + csrf(request).items()))

        if request.method == 'POST': # Do the action
            if 'delete' in request.POST:
                if os.path.isdir(fullPath):
                    shutil.rmtree(fullPath)
                else:
                    os.remove(fullPath)
                return showMessagePage(request, '操作成功', u'您已删除"%s"' % path, next = '../')
            elif 'rename' in request.POST:
                form = RenameForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    destPath = os.path.join(settings.USER_FILE_PATH, escapePath(username), escapePath(cd['path']))
                    if not os.path.exists(os.path.dirname(destPath)):
                        os.makedirs(os.path.dirname(destPath))
                    os.rename(fullPath, destPath)
                    return showMessagePage(request, '操作成功', u'您已移动"%s"至"%s"' % (path, cd['path']), next = '../')
                else:
                    return render(request, 'fileManager/renameForm.html', dict({'path': path,
                                                                            'form': RenameForm(initial = {'path' : path}),
                                                                            }.items() + csrf(request).items()))
    # Display
    if os.path.isdir(fullPath):
        return showFolderPage(request, username, fullPath, path)

    if os.path.isfile(fullPath):
        ext = os.path.splitext(fullPath)[-1]
        downloadURL = u'/download/%s/%s' % (username, path)
        if ext in viewForType.keys():
            return viewForType[ext](request, fullPath, path, downloadURL)
        else:
            return showDonloadPage(request, username, fullPath, path, downloadURL)

    return showMessagePage(request, '错误', '路径不存在')
Example #3
0
def showLogOutPage(request):
    """
    Log out a user
    """
    if request.method != "POST" or not "logout" in request.POST:
        raise Http404("无效的请求")
    if not request.user.is_authenticated():
        return showMessagePage(request, "无法登出", "您尚未登录")
    auth.logout(request)
    return showMessagePage(request, "成功", "您已成功登出")
Example #4
0
def showLogOutPage(request):
    '''
    Log out a user

    Return a httpRespond.
    '''
    if request.method != 'POST' or not 'logout' in request.POST:
        raise Http404('无效的请求')
    if not request.user.is_authenticated():
        return showMessagePage(request, '无法登出', '您尚未登录')
    auth.logout(request)
    return showMessagePage(request, '成功', '您已成功登出', next = '/login/')
Example #5
0
def showLogInPage(request, next = None):
    '''
    Show a log-in page.
    If the request contains 'username' and 'password', then login the user.

    Return a http respond.
    '''
    # Decide whether to show a success page
    if request.method == 'GET' and 'successful' in request.GET:
        if not next:
            next = '/view/%s/' % request.user.username
        return showMessagePage(request, '成功', '登录成功', next = next)

    error = ''

    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect(request.POST.get('next', '/'))
        else:
            error = '错误的用户名或密码'

    
    return render(request, 'auth/login.html',
                dict({'error': error,
                'next': request.GET.get('next', '/login/?successful=successful')
                }.items()+csrf(request).items()))
Example #6
0
def showLogInPage(request, next="/showtable/"):
    """
    Show a log-in page.
    If the request contains 'username' and 'password', then login the user.
    
    Return a http respond.
    """
    # Decide whether to show a success page
    if request.method == "GET" and "successful" in request.GET:
        return showMessagePage(request, "成功", "登录成功")
    error = ""
    if request.method == "POST":
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return HttpResponseRedirect(request.POST.get("next", "/"))
        else:
            error = "错误的用户名或密码"
    # assert False
    return render(
        request,
        "auth/login.html",
        dict(
            {"error": error, "next": request.GET.get("next", "/login/?successful=successful&next=" + next)}.items()
            + csrf(request).items()
        ),
    )
Example #7
0
def downloadFile(request, username, path):
    if not request.user.is_authenticated() or not request.user.username == username:
        return showMessagePage(request, '错误', '您没有权限')

    fullPath = os.path.join(settings.USER_FILE_PATH, escapePath(username), escapePath(path))
    respond = HttpResponse(yieldFile(fullPath))
    respond['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(fullPath).encode('utf-8')
    return respond
Example #8
0
def showTablePage(request, path):
    '''
    Display a table for a request.
    
    path: The path of csv file
    
    Return a httpRespond.
    '''
    # Decide whether the user can view the file
    if not request.user.is_authenticated():
        return showMessagePage(request, '无法访问', '您没有登录,不能访问这个页面')
    initPara = {'itemPerPage': 50, 'haveHeading': False, 'page': 1}
    cd = initPara
    # Get parameters from query string
    if request.method == 'GET' and 'submit' in request.GET:
        form = tablePageSettingsForm(request.GET)
        if form.is_valid():
            cd = form.cleaned_data
        else:
            cd = initPara
    else:
        form = tablePageSettingsForm(initPara)
        cd = initPara
        try:
            cd['page'] = int(request.GET.get('page', '1'))
        except ValueError:
            cd['page'] = 1
    # Fetch the file
    csvfile = file(path, 'rb')
    reader = csv.reader(csvfile)
    lines = list(reader)

    # Paging
    if cd['haveHeading']:
        paginator = Paginator(lines[1:], cd['itemPerPage'])
    else:
        paginator = Paginator(lines, cd['itemPerPage'])

    try:
        content = paginator.page(cd['page'])
    except PageNotAnInteger:
        content = paginator.page(1)
    except EmptyPage:
        content = paginator.page(paginator.num_pages)

    # Rend
    if cd['haveHeading']:
        heading = list(lines[0])
    else:
        heading = []
    respond = render(request, 'showdata/table.html',
                {'title': '表格 ' + path,
                'path': path,
                'page_range': friendlyPageRange(paginator.page_range, content.number),
                'paginator': paginator,
                'content': content,
                'table_headings': heading,
                'form': form})

    # Finishing
    csvfile.close()

    return respond