Built-in Python3 web server functionality - wsgiref & http.server

Chris Angelico rosuav at gmail.com
Sun Jun 7 20:13:37 EDT 2015


On Mon, Jun 8, 2015 at 5:13 AM, Eric <ericgorr at gmail.com> wrote:
> I am trying to better understand the built-in python3 web server functionality and have just started reading the documentation.
>
> There seem to be two options provided by Python 3.
>
> 1.
> wsgiref
> https://docs.python.org/3/library/wsgiref.html
>
> 2.
> http.server
> https://docs.python.org/3/library/http.server.html
>
>
> Both options appear to offer a simple way to get a simple web server up and running. It does appear that wsgiref is built on top of http.server. Is this correct?
>
> Would it be correct to say that wsgiref is a high(er?)-level framework for designing web-based applications where as http.server is operating at a lower level? While one could do everything with just http.server, if wsgiref was appropriate for a particular use case, it would be the path to follow.
>
> Any insights into this topic would be appreciated.
>
> Are there any good python 3 books covering this functionality?

What are you actually trying to accomplish here? At what level of
abstraction do you want to work?

http.server is pretty low level:
https://github.com/Rosuav/Yosemite/blob/master/Yosemite.py

But if you want a higher level, I would recommend using something like Flask:
https://github.com/Rosuav/MinstrelHall/blob/master/mh.py

Yosemite.py runs as a stand-alone program, listens on a port, and can
be controlled by a web browser. It's a web server. But if you look
through the code, you'll see how raw an interface it is; that's not a
big problem for Yosemite, as it's an extremely thin layer over a file
system, so it's basically pulling out a few special cases ("/stop"
etc) and then looking for something at the exact path it was given.

Minstrel Hall runs inside Apache, via Passenger. You can also run it
directly, in which case it makes use of an internal
bind/listen/accept/dispatch loop, so it can also be called a web
server. But it's much more clearly operating as a web site, with
separate top-level functions that clearly show what URLs they're
handling. There's support for parameterized URLs like
http://minstrelhall.com/campaign/6 (comes through to campaign(id=6)),
and heaps of other features that a simple example like MH won't show
off. If you want to make a web site that's still maintainable after
it's grown bigger than the ~300 lines of code that Yosemite.py has, I
strongly recommend using a framework like Flask.

On the flip side, if you want a quick-and-dirty program that shows you
a whole lot of extremely raw information about what the web browser is
trying to do, http.server is a very handy tool, and it doesn't require
any extra installations (Flask isn't part of the standard library, so
you'd need to pip install it).

High or low abstraction level?

ChrisA



More information about the Python-list mailing list