我正在玩Django中的文件上传,但是我收到了这个错误:
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/bli1/Development/Django/TrinityTaaS/parser/views.py" in handle_uploaded_file
35. f = open(log_file, "r")
Exception Type: TypeError at /parser/events/
Exception Value: coercing to Unicode: need string or buffer, WSGIRequest found
我不确定如何解决这个问题。
views.py
def handle_uploaded_file(log_file):
print "HI"
json_beacons = []
f = open(log_file, "r")
# log regex for events
beacon1 = re.compile(r'.*\[DataCapture\]\s+(?P<beacon_var>\[(.*)\])')
beacon2 = re.compile(r'.*\[DataCapture\]\s+Event:\s+\{.*\}(?P<beacon_var>\{.*\})')
for chunk in f.chunk():
log_entry = re.search(beacon1, chunk)
if log_entry:
beacon_json = log_entry.group("beacon_var")
json_beacons.append(beacon_json[1:-1])
return json_beacons
def upload_file(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
json_beacons = handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
forms.py
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
答案 0 :(得分:1)
由于错误表明log_file
是一个响应对象,我猜您实际上是在网址配置中引用handle_uploaded_file
而不是upload_file
。
答案 1 :(得分:1)
除了SmileyChris提到的可能不正确的url配置外,open
还需要一个包含文件路径的字符串,而request.FILES
包含表示此处记录的文件的对象:https://docs.djangoproject.com/en/dev/ref/files/uploads/#uploaded-files < / p>
您无需open
上传的文件,只需使用其read
或chunks
方法即可获取上传的内容。