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.

Making SQL Queries

This article is to summarize how do we make SQL queries using different languages and their methods. Making connection to the database will not be covered here.

In the examples, we will be querying “SELECT * FROM employees where eid =and dept =”

It is not recommended to use SQL statements without placeholders in order to reduce the risk of SQL injection.

Java

In Java, we can use JDBC, Hibernate, or some other database frameworks to interact with databases. Generally, I would prefer to use methods that allow me to insert “values” into an sql query. With JDBC, we can use PreparedStatement method. There is also createStatement method, where you insert user-supplied values into the query directly.

Basically the flow looks like this:

  1. Get a “Connection” object, with DriverManager
  2. From “Connection” object, we create a “Statement” object with sql statement.
  3. From the statement object, we generate “ResultSet”.

PHP

PHP has more methods to interact with database. It also depends on the module the php interpreter is built with. We can use MySQL extension, PostgreSQL extension, or ADODB or PDO as generic abstraction interfaces.

With mysqli extension

NOTE: Why mysqli instead of mysql command? If we are using MySQL v4.1.3 and above, PHP manual recommends to use mysqli which is an improved version. Reference.

With PostgreSQL extension

With ADODB

With PDO

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: