Django,如何处理fetch请求?

问题描述 投票:0回答:1

我正在做一个使用平板扫描仪的Django项目。由于扫描需要很长的时间,我必须解决超时错误。在搜索和尝试了多种方法后,我最终采用了线程化的fetch调用。

我如何改变fetch调用来做我想要的事情?目前,我得到的是一个空白页,显示了由以下函数返回的字典 free_scan_crop. 请注意,我是JavaScript新手。我只是复制了JS的这一点。

我想发生什么。

  • 当表单被提交时,一个模态显示出来。
  • 扫描仪完成后:将用户发送到主页,并显示信息。

扫描.html

<div class="modal fade" id="scanDocument" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Scanning</h5>
      </div>
      <div class="modal-body">
        Please wait...
      </div>
    </div>
  </div>
</div>

<script>
  formElem.onsubmit = async (e) => {
    e.preventDefault();

    let response = await fetch("{% url 'core:free_scan' %}", {
      method: 'GET',
      body: new FormData(formElem)
    });

    let result = await response.json();

    alert(result.message);
  };
</script>

视图.py

def free_scan_crop(request):

    form = FreeScanForm(request.GET)
    if form.is_valid():
        file_name = form.cleaned_data['file_name']
        # Grab the rest of the fields from the form...

        x = threading.Thread(
            target=scan_crop,
            args=(request, file_name, top_left_x, top_left_y, bottom_right_x, bottom_right_y, dpi),
        )
        return x.start()  # Questions: is this correct?

        return JsonResponse({"scanning": True})

    # invalid form
    return JsonResponse({"scanning": False})

def scan_crop(request, file_name, top_left_x, top_left_y, bottom_right_x, bottom_right_y, dpi):

    # This method runs for a long time
    image = ScannerServiceConnection().scan_roi(
        top_left_x,
        top_left_y,
        bottom_right_x,
        bottom_right_y,
        dpi
    )

    if image is None:
        # No connection to the scanner
        messages.error(request, 'Check scanner service status')
    else:
        # store image
        image.save(<file_path>)
        messages.success(request, 'saved image')

    # Please note that I want to send a message to the user to inform them on the status of the scan
    return render(request, 'home.html')
javascript django fetch
1个回答
0
投票

特别感谢 vlaz 感谢通过JS聊天的帮助。

fetch调用现在已经能正常工作了。我不能让fetch显示模式,所以做了一个小函数来实现。

扫描仪是作为一个服务通过 rpyc. 我不得不禁用超时设置,以防止它抛出超时错误。注意,这个Django应用是在用户系统上离线运行的。


rpyc.connect(
    host="localhost",
    port=18861,
    config={'sync_request_timeout': None},
)

scan.html

<form class="form" action="" method="post" id="free_scan_from">

{% csrf_token %}

{% bootstrap_form form %}

{% buttons %}
<button type="submit" id="save_button" class="btn btn-primary" onclick="modalFunction()" name="action"
  value="save_crop">
  <i class="fa fa-save"></i> Scan & Save
</button>
{% endbuttons %}

</form>


<script>
  // show the modal when the file_name field has a value
  function modalFunction() {
    if (document.getElementById("id_file_name").value !== "") {
      $('#scanBanknote').modal('show');
    }
  }
</script>

<script>
  const formElem = document.querySelector("free_scan_from")
  formElem.onsubmit = async (e) => {

    e.preventDefault();

    let response = await fetch("{% url 'core:free_scan' %}", {
      //cannot have a body with GET
      method: 'POST',
      body: new FormData(formElem)
    });

    let result = await response.text();

    alert(result);
  };
</script>

视图.py


def free_scan_crop(request):
    form = FreeScanForm(request.POST)
    if form.is_valid():
        file_name = form.cleaned_data['file_name']
        # grab the rest of the fields

        image = ScannerServiceConnection().scan_roi(
            top_left_x,
            top_left_y,
            bottom_right_x,
            bottom_right_y,
            dpi
        )

        if image is None:
            messages.error(request, 'Check scanner service status')
        else:
            # store image
            image.save(<file_path>)
            messages.success(request, 'image saved')

        return render(request, 'free_scan_preview.html')

    # invalid form
    context = {'form': form}
    return render(request, "free_scan_crop.html", context)

© www.soinside.com 2019 - 2024. All rights reserved.