/Python-C

Python C API Example

Primary LanguageC

Python-C

Note!: This is NOT a PROPER example of a HTTP client with sockets in C. Its main purpose is to teach how to build Python modules using the Python C API!

I used Python 3.8.10 and gcc 9.4.0

See the code of the 'HTTP client' in src/ directory and myhttp.c for Python C extention code.

The 1st step:

Install <Python.h> to enable the inclusion of the header in your code:

sudo apt-get install python3-dev

The 2nd step:

Configure localhost:

  1. Open /etc/hosts with any editor and paste this code:
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

The 3rd step:

Install MyHttp package

  1. Install the package globally:
sudo python3 setup.py install

Check installation with:

pip3 freeze

You should see this in result your installed modules:

...
MyHttp==1.0.0
...
  1. Or install it locally:
sudo python3 setup.py build

Codes below will create a .so file in build/ folder.

4th step:

Test your code:

Note: Before testing with localhost, run server.py (default port is: 8080):

python3 server.py

Run test.py as:

python3 test.py --full-print

When the --full-print flag is provided, the test.py will print full responses.


Use --no-external or --no-internal to exclude external or local requests, respectively.