Django1.8基于类的视图,用于经过身份验证的文件上载

时间:2015-08-05 03:06:18

标签: django django-class-based-views

是Django的新手,并尝试编写一个HTTP服务器,只有在身份验证后才能通过POST接受文件上传。相当多的教程建议CBV基于函数的视图,但是当我尝试执行POST时,会抛出以下错误。任何人都可以帮助解决我的错误吗?

Starting server, use <Ctrl-C> to stop.
----------------------------------------
Exception happened during processing of request from ('10.1.100.2', 30338)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 295, in
  _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
TypeError: __init__() takes exactly 1 argument (4 given)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('10.1.100.2', 30339)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 295, in 
  _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
TypeError: __init__() takes exactly 1 argument (4 given)
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('10.1.100.2', 30340)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 295, in 
  _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
TypeError: __init__() takes exactly 1 argument (4 given)
----------------------------------------

urls.py:

from django.conf.urls import include, url
from django.contrib import admin
import my_app.views
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^post/', my_app.views.Handler.as_view(), name='my_app'),
]

views.py:

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.http import Http404
from django.views.generic.base import View
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
import urlparse
import datetime
import SimpleHTTPServer
import SocketServer

class Handler(View, BaseHTTPRequestHandler):
    def do_HEAD(self):
        print "send header"
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_AUTHHEAD(self):
        print "send header"
        self.send_response(401)
        self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        if self.headers.getheader('Authorization') == None:
            self.do_AUTHHEAD()
            self.wfile.write('no auth header received')
            pass
        elif self.headers.getheader('Authorization') == 'Basic dGVzdDp0ZXN0':
            self.do_HEAD()
            self.wfile.write(self.headers.getheader('Authorization'))
            self.wfile.write('authenticated!')
            parsed_path = urlparse.urlparse(self.path)
            message_parts = [
                'CLIENT VALUES:',
                'client_address=%s (%s)' % (self.client_address,
                                            self.address_string()),
                'command=%s' % self.command,
                'path=%s' % self.path,
                'real path=%s' % parsed_path.path,
                'query=%s' % parsed_path.query,
                'request_version=%s' % self.request_version,
                '',
                'SERVER VALUES:',
                'server_version=%s' % self.server_version,
                'sys_version=%s' % self.sys_version,
                'protocol_version=%s' % self.protocol_version,
                '',
                'HEADERS RECEIVED:',
                ]
            for name, value in sorted(self.headers.items()):
                message_parts.append('%s=%s' % (name, value.rstrip()))
            message_parts.append('')
            message = '\r\n'.join(message_parts)
            self.send_response(200)
            self.end_headers()
            self.wfile.write(message)
            pass
        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.headers.getheader('Authorization'))
            self.wfile.write('not authenticated')
            pass


    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })

        self.send_response(200)
        self.end_headers()
        self.wfile.write('Client: %s\n' % str(self.client_address))
        self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
        self.wfile.write('Path: %s\n' % self.path)
        self.wfile.write('Form data:\n')

        for field in form.keys():
            field_item = form[field]
            if field_item.filename:
                # The field contains an uploaded file
                file_data = field_item.file.read()
                file_len = len(file_data)
                del file_data
                self.wfile.write('\tUploaded %s as "%s" (%d bytes)\n' % \
                        (field, field_item.filename, file_len))
            else:
                self.wfile.write('\t%s=%s\n' % (field, form[field].value))
        pass
server = HTTPServer(('', 8080), Handler)
print 'Starting server, use <Ctrl-C> to stop.'
server.serve_forever()

0 个答案:

没有答案