HTTP and HTTPS server with Python

Python 2 has already included an HTTP server module in its later versions. And running the server is as simple as this:

It starts the server on port 8000 (by default), and if we want to run on a different port, we will just add the new port number at the end of the command.

With Python 3, the package merged into http.server. So we would call:

When we need to customize how the server behaves (e.g. to run the server on a specific IP address), we can write a very simple python codes:

If we want HTTPS server, we will need to use built-in “ssl” module. We need to wrap the httpd socket with wrap_socket method. The certificate needs to be in PEM format (RFC1422).

In general, we just need a socket and a handler to serve.

Python: Pyql module to obtain stock quotes from Y! Finance

I just made an initial attempt to fetch the stock quotes via YQL, and put the codes into a module. The method “lookup” will return a list of python dictionary item(s), based on the information decoded from Yahoo’s JSON data.

The current snapshot is posted on Google Code. The code doesn’t work with Python 3. It should work fine with Python 2.2 or higher.

To clone the source codes to a local resource, please feel free to do so via mercurial.

Example Usage:

YQL, Python, and Yahoo Finance

YQL is the way to get information from Web Services using SQL-like queries. It also provides us a console where we can test our queries and generate the REST query. To see how it works, just go to the console page, and enter the following as the YQL statement:

And set the output to either “XML” or “JSON”, and click “Test”. I personally prefer JSON and will continue to use JSON throughout the example. I unchecked the “Diagnostics” and emptied the text field next to “JSON”.

The command will fetch the information related to the stock quote FFIV (F5 Networks, NASDAQ) from Yahoo Finance. Inside “Formatted View” window, you will see the result like this:

Below that text field, we can find the REST statement which we can use to send query to the server. It looks like this for our query:

This is how we can fetch stock information using YQL and receive information in JSON. Since this is a public data, we can directly send the REST, otherwise we need the API keys to access the data.

Let’s see how we can fetch the information via Python.

That should print the whole JSON response. We can use simplejson module to parse the result. It looks like this:

The python statements are pretty much self-explanatory.

Here’s another example from Yahoo, to get stock information from open data tables.