문제

Django Python Server에서 사용자가 파일을 업로드 할 수있는 URL을 사용자 정의했습니다. 이제 문제는 브라우저를 칠 때 파일을 성공적으로 업로드 할 수 있지만 CURL을 사용하여 같은 것을 시도 할 때 그렇게 할 수 없다는 것입니다.

views.py

import json

from django.http import HttpResponse
from django.template import Context, RequestContext
from django.shortcuts import render_to_response, get_object_or_404

# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from sdm.models import Document
from sdm.forms import DocumentForm

def lists(request):
   # Handle file upload
   if request.method == 'POST':
     form = DocumentForm(request.POST, request.FILES)
     if form.is_valid():
        newdoc = Document(docfile = request.FILES['docfile'])
        newdoc.save()

        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('sdm:lists'))

else:
    form = DocumentForm() # A empty, unbound form

# Load documents for the list page
documents = Document.objects.all()

# Render list page with the documents and the form
return render_to_response(
    'sdm/lists.html',
    {'documents': documents, 'form': form},
    context_instance=RequestContext(request)
)

........ ........ ........ ........

lists.html

 <!DOCTYPE html>
 <html>
 <head>
    <meta charset="utf-8">
    <title>Minimal Django File Upload Example</title>   
 </head>
 <body>
 <!-- List of uploaded documents -->
 {% if documents %}
    <ul>
    {% for document in documents %}
        <li><a href="{{document.docfile.url }}">{{ document.docfile.name }}</a></li>
    {% endfor %}
    </ul>
 {% else %}
    <p>No documents.</p>
 {% endif %}

    <!-- Upload form. Note enctype attribute! -->
    <form action="{% url sdm:lists %}" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <p>{{form.non_field_errors }}</p>
        <p>{{form.docfile.label_tag }} {{form.docfile.help_text }}</p>
        <p>
            {{ form.docfile.errors }}
            {{ form.docfile }}
        </p>
        <p><input type="submit" name="press" value="Upload" /></p>
    </form>
 </body>
</html> 

브라우저에서

enter image description here

터미널에서 나는 시도했다

 $ curl --request PUT --upload-file filename http://wings.spectrumserver/sdm/lists

 $ curl --form upload-file=filename  --form press=Upload 

 http:// wings. spectrumserver/sdm/lists

$ curl --upload-file filename http://wings.spectrumserver/sdm/lists
$ curl --upload-file filename press=upload http://wings.spectrumserver/sdm/lists

$ curl -H 'Expect:' -F data=@filename -F submit=Upload wings.spectrumserver/sdm/lists

// In all cases, No error but no file upload

나는 다른 변형을 시도했지만 아무것도 작동하지 않는 것 같습니다. 또한 "CSRF 토큰 오류 없음"을 제공하는 다른 명령도 있습니다. 나는 또한 제거를 시도했다 csrf token 항목 양식 html file 그리고 setting.py 그러나 아무것도 효과가 없었습니다.

나는 Curl과 Python을 모두 처음 사용합니다. 주요 목적은 일부 Python 스크립트를 사용하여 파일을 업로드하는 것입니다. Curl을 통해 업로드 할 수 있다고 생각하면 CURL 라이브러리를 사용하여 Python 스크립트에서 동일한 사항을 복제 할 수 있다고 생각했습니다. 따라서이 작업이 진행되지 않으면이 서버에 파일을 업로드하기 위해 일부 Python 코드를 제안 할 수 있습니다.

편집하다 :

$ curl -i -F name=press -F f13 wings.spectrumserver/sdm/lists
Warning: Illegally formatted input field!
curl: option -F: is badly used here
curl: try 'curl --help' or 'curl --manual' for more information

edit2- 헤더 응답 (F13은 포함되지 않은 새 파일)

$ curl -i http://wings.spectrumserver/sdm/lists

HTTP/1.1 200 OK
날짜 : Thu, 2013 년 11 월 7 일 23:19:18 GMT 서버 : Apache/2.2.22 (Ubuntu)
vary : accept-encoding content-length : 1263 컨텐츠 유형 : text/html; charset = UTF-8

최소 Django 파일 업로드 예제

    <ul>

        <li><a href="/media/documents/2013/10/28/templates.zip">documents/2013/10
    /28/templates.zip</a></li>

        <li><a href="/media/documents/2013/11/07/list">documents/2013/11/07/list</a>
    </li>

        <li><a href="/media/documents/2013/11/07/f1">documents/2013/11/07/f1</a></li>

        <li><a href="/media/documents/2013/11/07/f12">documents/2013/11/07/f12</a></li>

        <li><a href="/media/documents/2013/11/07/hello.html">documents/2013/11
        /07/hello.html</a></li>

    </ul>


    <!-- Upload form. Note enctype attribute! -->
    <form action="/sdm/lists" method="post" enctype="multipart/form-data">

   <!--            
   -->        <p></p>
        <p><label for="id_docfile">Select a file</label> max. 42 megabytes</p>
        <p>

            <input type="file" name="docfile" id="id_docfile" />
        </p>
        <p><input type="submit" name="press" value="Upload" /></p>
    </form>
  </body>
</html> 
도움이 되었습니까?

해결책

다음과 같은 것을 시도하십시오.

curl -i --form docfile=@localfilename http://wings.spectrumserver/sdm/lists

작동하지 않으면 헤더 응답을 게시하십시오. -i 컬에 헤더 응답을 인쇄하도록 지시합니다.

다른 팁

나는 그것이 누락 된 CSRF 토큰이라고 생각합니다.

{% csrf_token %}

django 문서를보십시오 크로스 사이트 요청 위조 보호. 양식이 동일한 도메인에서 제출되도록 생성 된 토큰입니다. 템플릿에서 태그를 제거하여 CSRF 보호를 비활성화 할 수 있습니다. 또는 시도하십시오 여기 컬을 사용하여 통과하는 방법에.

btw 당신이 원하는 모든 것이 파이썬 스크립트를 사용하여 업로드하는 것입니다. 요청.

url = 'http://wings.spectrumserver/sdm/lists'
files = {'file': open('file.ext', 'rb')}
r = requests.post(url, files=files)

나는 이것을 컬로 솔질하는 것을 도울 수 없다.

그러나 Python3을 프로그래밍 할 수 있다면 :

Django는 크로스 사이트 참조 위조 (CSRF)를 보호합니다.

CSRF 쿠키와 숨겨진 CSRF를 양식에 사용해야합니다.

따라서 먼저 브라우저와 같은 다운로드 페이지를 가져 와서 CSRF를 추출 하고이 데이터를 포함하여 게시물을 작성해야합니다.

게시물은 멀티 파트/양식 데이터 형식이어야합니다.

Linux 시스템 에서이 형식이 어떻게되는지 확인하는 한 가지 방법 :

1- 양식 동작이 (say)를 가리키는 Django 업로드 페이지 생성 http://127.0.0.1:2222/

2- 터미널을 열고 실행 : NC -L 127.0.0.1 2222 & 1 | 더 적은

3- 업로드 페이지에서 브라우저를 열고 양식을 작은 텍스트로 채우고 업로드하고 업로드 버튼을 누릅니다. 브라우저는 불만을 제기 할 것입니다.

4- 터미널에서 브라우저가 Post & Multipart/Data -Form을 사용하여 파일을 업로드하는 방법을 알 수 있습니다.

솔루션을 구현하려면 :

5- 링크를 확인하십시오 http://blog.spotflux.com/uploading-files-python-3 여기서 python3을 사용하여 게시물을 멀티 파트/양식 데이터 형식으로 만듭니다.

6- 쿠키를 게시물에 포함시키기 위해이 예에서 약간의 변경을해야합니다.

html 페이지를 구문 분석하려면 html.parser.htmlparser를 사용하십시오.

잘 작동하지만 코드를 게시 할 수는 없습니다.

requests.get () 및 requests.post ()를 사용하려고하지 않았습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top