Using Python Libraries in Django

2k views Asked by At

![invoice][1]

![python script][2]

[1]: [2]: https://i.stack.imgur.com/Y6Ebm.png

Hello! I would appreciate if someone could help me with a doubt I have about using Python libraries in Django. I will try to be as clear as possible so here it goes:

In my job I work with invoices that are all saved in a specific directory (PDF files) and they all have the same structure. In my job I am interested in only one specific value in a row which is a number. My job is to extract that value from all the invoices and sum them all. So, I made a python script in which I use the libraries Pandas, os and PDFplumber and it works great. In code.png, you can see the loop I use to extract the row and value that I want by using PDFplumber and then sum all these values. In invoice.png you can see how PDFplumber divides the invoice in rows and in columns.

So, here is the thing: I want to deploy a Django App so that other people in the enterprise can use the python script I use ( they don't know anything about Python programming). So, I would want to deploy a Django app in which they can upload the directory with all the PDF files and then use the python script I show in code.png. But I'm having problems with the logic behind it. My questions are:

  1. Can we use any python libraries in Django ( such as PDFplumber, pandas, etc) ?
  2. Would I put my python script in views.py? (Something like this)

app/views.py

import os
import pdfplumber
import pandas as pd
from django.shortcuts import render


def function(request):
    
    #Use the directory with the images uploaded by the user.
    #Python script shown in code.png
    # data = response obtained from the python script.
    return render(request, 'app/response.html',{"data":data})

Thank you beforehand!

2

There are 2 answers

0
Code-Apprentice On BEST ANSWER

Can we use any python libraries in Django ( such as PDFplumber, pandas, etc) ?

Yes, a Django app is just Python code. You can add whatever python code you want, including import pandas or whatever.

Would I put my python script in views.py? (Something like this)

While you can write the code in the way you describe, I suggest you organize it more logically. The view function should only handle the request and return a response. Any business logic, such as parsing PDF files, should be in a separate file. Organize your code in a way that makes sense for the task you are trying to complete.

0
Mihai On

Django is just another Python library so you can definitely use other libs together with Django. Adding your code in views.py is a very good start your project. The downside of views.py is that it will block the call until a response is received. If it takes too lonk you may get HTTP timeouts so other solutions can be explored but I would for sure start with the code in views.py.