Forums

Problem with uploading files to dropbox

Hi, I am trying to make my python backend to work in a manner that it generates a PDF from the data it receives by POST, and upload it to Dropbox, along with an image file.

I have a free account

Here is how I am handling the post request

 def post(self, request):
    data = request.data
    data['volunteer_dob'] = datetime.datetime.strptime(data['volunteer_dob'], "%d-%m-%Y").strftime("%Y-%m-%d")
    photo = data['volunteer_photo']
    try:
        data['volunteer_photo'] = upload(photo.read(), 'volunteers/photos/' + data['volunteer_name'] + '_' + data['contact_number'] + '_' + photo.name)
        print("Returned Data of Photo: " + data['volunteer_photo'])
        upload(pdfUtil.render_to_pdf('volunteer_form.html', {
           'pagesize':'A4',
           'logo_image': 'http://fourseasonskashmir.com/assets/media/logo.png',
           'profile_image': data['volunteer_photo'].replace('?dl=0', '?raw=1'),
           'name': data['volunteer_name'],
           'previous_experience': data['volunteer_previous_experience'],
           'address': data['address'],
           'country': data['country'],
           'state': data['state'],
           'pincode': data['pincode'],
           'contact_number': data['contact_number'],
           'age': data['volunteer_age'],
           'dob': data['volunteer_dob'],
           'email': data['volunteer_email'],
           'website': data['volunteer_website'],
        }), 'volunteers/' + data['volunteer_name'] + '_' + data['contact_number'] + '.pdf')
    except dropbox.ApiError:
        return makeresponse(Response(Errors.TIMEOUT, status=status.HTTP_400_BAD_REQUEST))
    except DropboxFileAlreadyExists:
        return makeresponse(Response(Errors.ALREADY_REGISTERED, status=status.HTTP_400_BAD_REQUEST))
    except DropboxUploadError:
        return makeresponse(Response(Errors.TIMEOUT, status=status.HTTP_400_BAD_REQUEST))

    serializer = VolunteerSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        response = Response(serializer.data, status=status.HTTP_201_CREATED)
        return makeresponse(response)
    response = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    return makeresponse(response)

This works fine when I use it at my own PC, but doesn't work on PythonAnywhere. Here is the log message:

2017-05-18 13:56:13,732: Not Found: /
2017-05-18 13:56:18,823: Request to files/upload
2017-05-18 13:56:18,830: Starting new HTTPS connection (1): content.dropboxapi.com
2017-05-18 13:56:19,696: Request to sharing/create_shared_link_with_settings
2017-05-18 13:56:19,698: Starting new HTTPS connection (1): api.dropboxapi.com
2017-05-18 13:56:22,819: Internal Server Error: /workwithus/volunteer#012Traceback (most recent call last):#012  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 39, in inner#012    response = get_response(request)#012  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response#012    response = self.process_exception_by_middleware(e, request)#012  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response#012    response = wrapped_callback(request, *callback_args, **callback_kwargs)#012  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view#012    return view_func(*args, **kwargs)#012  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view#012    return self.dispatch(request, *args, **kwargs)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/rest_framework/views.py", line 483, in dispatch#012    response = self.handle_exception(exc)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/rest_framework/views.py", line 443, in handle_exception#012    self.raise_uncaught_exception(exc)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/rest_framework/views.py", line 480, in dispatch#012    response = handler(request, *args, **kwargs)#012  File "/home/fourseasons/django_backend_fourseasons/WorkWithUs/views.py", line 63, in post#012    'website': data['volunteer_website'],#012  File "/home/fourseasons/django_backend_fourseasons/WorkWithUs/pdfUtil.py", line 12, in render_to_pdf#012    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/document.py", line 97, in pisaDocument#012    encoding, context=context, xml_output=xml_output)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/document.py", line 59, in pisaStory#012    pisaParser(src, context, default_css, xhtml, encoding, xml_output)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 708, in pisaParser#012    pisaLoop(document, context)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 648, in pisaLoop#012    pisaLoop(node, context, path, **kw)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 593, in pisaLoop#012    pisaLoop(nnode, context, path, **kw)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 593, in pisaLoop#012    pisaLoop(nnode, context, path, **kw)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 593, in pisaLoop#012    pisaLoop(nnode, context, path, **kw)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 477, in pisaLoop#012    attr = pisaGetAttributes(context, node.tagName, node.attributes)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/parser.py", line 117, in pisaGetAttributes#012    nv = c.getFile(nv)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/context.py", line 848, in getFile#012    return getFile(name, relative or self.pathDirectory)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/util.py", line 673, in getFile#012    file = pisaFileObject(*a, **kw)#012  File "/home/fourseasons/.local/lib/python3.5/site-packages/xhtml2pdf/util.py", line 581, in __init__#012    conn.request("GET", path)#012  File "/usr/lib/python3.5/http/client.py", line 1106, in request#012    self._send_request(method, url, body, headers)#012  File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request#012    self.endheaders(body)#012  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders#012    self._send_output(message_body)#012  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output#012    self.send(msg)#012  File "/usr/lib/python3.5/http/client.py", line 877, in send#012    self.connect()#012  File "/usr/lib/python3.5/http/client.py", line 849, in connect#012    (self.host,self.port), self.timeout, self.source_address)#012  File "/usr/lib/python3.5/socket.py", line 711, in create_connection#012    raise err#012  File "/usr/lib/python3.5/socket.py", line 702, in create_connection#012    sock.connect(sa)#012OSError: [Errno 101] Network is unreachable

Hopefully, you guys can help me

You need to route your requests through the proxy: http://help.pythonanywhere.com/pages/403ForbiddenError/

The upload works for the photos, but fails for the PDF. And it is a 101 error, not a 111

It's the same thing, just reported differently. Maybe your PDF rendering is trying to get external assets that are not on the whitelist. Try the PDF rendering in a console.

Ok, so I fixed the 101 error, which was being called because I was accessing an Image from my website (which wouldn't be in PythonAnywhere Whitelist). I am still getting the 111 Connection Refused error. I tried configuring the dropbox api, but it still doesn't work

I tried this solution and also I modified my code to:

dbox = dropbox.Dropbox(os.environ.get('DROPBOX_ACCESS_TOKEN'), dropbox.create_session(proxies={'http': 'http://proxy.server:3128'}))

But it still shows 111 Connection Refused

"Connection refused" means it's not using the proxy. Find the line of code that is raising the error and try to work out what it's trying to access and why it's not using the proxy.

I solved it. Apparently, the pdf generating libraries weren't using the proxy, so I stored the required stuff in a temp folder, which gets deleted after their use is done