Tuesday, November 4, 2014

PDF in a Net, with Netius - the Python client

By Vasudev Ram

In a recent post, titled PDF in a Net, with Netius, a pure Python network library, I had shown how to use Netius, to serve a PDF to a client. I had shown the server side of that app and said that I would show the client side in a future post. This is that post.

Though the documentation has examples of using netius to create clients as well as servers, I chose not to use it for this example; instead I just used the requests HTTP library for Python. There was nothing in my code that required the extra features of a Netius client.

Here is my client for the Netius PDF server:

# netius_pdf_client.py

import requests

resp = requests.get('http://localhost:8080')
if resp.status_code != 200:
    print "get PDF failed"
else:
    with open('output.pdf', 'wb') as pdf_fil:
        pdf_fil.write(resp.content)
    print "PDF created in output.pdf"
As you can see, it's quite short. That's partly due to the fact that the output PDF name is hard-coded, so no need to pick it from a command-line argument, and also because I kept the code as simple as possible, for clarity.

The client uses the requests library to do an HTTP GET call to the endpoint localhost:8080 (on which the server is running).

The server then returns the PDF to the client, in a response with the Content-Type 'application/pdf' - see the server code in the previous post.

The client then writes the response content to disk, in the file 'output.pdf', with binary file mode - the 'wb' argument to open() - since the PDF is a binary file, not text).

Run the server (see the server code in the previous post linked to near the top of this post):
$ python netius_pdf_server.py
2014-11-04 22:00:45,733 [INFO] Booting netius 1.4.3 (CPython 2.7.8.final win32)
...
2014-11-04 22:00:45,795 [INFO] Serving 'WSGIServer' service on 127.0.0.1:8080 ..
.
2014-11-04 22:00:45,796 [INFO] Starting HTTP server with 'plain' encoding ...
(I renamed the server program from test_netius_wsgi_server.py (as shown in the server post) to netius_pdf_server.py.)

Then run the client in another terminal window:
$ python netius_pdf_client.py
The PDF file fetched from the server gets created on disk. Here's a screenshot of it, as shown in Foxit PDF Reader:


- Vasudev Ram - Dancing Bison Enterprises

Signup for email about new products from me.

Contact Page

No comments: