简体   繁体   English

Django,如何处理获取请求

[英]Django, how to handle fetch request

I'm working on a Django project that uses a flatbed scanner.我正在开发一个使用平板扫描仪的 Django 项目。 Since scanning takes a long time I must work around getting a timeout error.由于扫描需要很长时间,我必须解决超时错误。 After searching and trying multiple things I ended up with threading an a fetch call.在搜索并尝试了多件事之后,我最终处理了一个 fetch 调用。

How do I alter the fetch call to do what I want?如何更改 fetch 调用以执行我想要的操作? I currently get send to a blank page that shows the dictionary that was returned by free_scan_crop .我目前被发送到显示由free_scan_crop返回的字典的空白页。 Please note that I am new to JavaScript.请注意,我是 JavaScript 的新手。 I just copied this bit of JS.我只是复制了这段JS。

What I would like to happen:我想发生的事情:

  • A modal shows up when the form is submitted提交表单时显示模式
  • When the scanner is done: send user to home page and show message扫描仪完成后:将用户发送到主页并显示消息

scan.html扫描.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>

views.py视图.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')

A special thanks to vlaz for helping out via the JS chat.特别感谢vlaz通过 JS 聊天提供帮助。

The fetch call is now working like it should. fetch 调用现在可以正常工作了。 I couldn't get fetch to show the modal so made a little function to do that.我无法获取显示模态,所以做了一点 function 来做到这一点。

The scanner is running as a service via rpyc .扫描仪通过rpyc作为服务运行。 I had to disable the timeout setting to keep it from throwing timeout errors.我不得不禁用超时设置以防止它引发超时错误。 Note, this Django application runs offline on the user's system.请注意,此 Django 应用程序在用户系统上脱机运行。


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

scan.html扫描.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>

views.py视图.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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM