Skip to content

Latest commit

 

History

History
52 lines (43 loc) · 3.04 KB

README.md

File metadata and controls

52 lines (43 loc) · 3.04 KB

Cython FastAPI template

Python FastAPI С


A sample Python API written on FastAPI with helping modules for compiling into a single binary using Cython-ization and Python/C API.

Based on perfomance testing, Cython can speed up your project by 3.35 times.

You can check my article about cythonized FastAPI projects with benchmarks (on Russian) on my blog - difhel.dev/blog/cython-fastapi-benchmark. This article also contains some comprehensive instructions how to build and run this code.

Project structure

  • main.pyx - main file, code written on Python (without Cython-flavored feautures), the entry point of the project.
  • routes - the routes of API (in this example only one router - ftl with method /method/ftl.test)
  • builder.c - C code for compiling file main.c. main.c is auto-generated C-code generated by Cython. This file is a build artifact produced by cythonizing main.pyx, the source code.
  • Makefile - makefile for the project. Options:
    • cythonize - runs cython main.pyx, cythonizing source code.
    • build - translates the project to main.c and compiles it to main.<arch>.so shared library file
    • gcc - compiles the file main.c to app.o
    • run - start the project with environment variable PYTHONPATH=pwd (needed for Python API)
    • clean - delete build artifacts

Dependencies and requirements

  • You are using OS Linux with the bash shell.
  • To be honest, this project does not contain any platform-specific things, so you can run it on Windows either, but you should install a C compiler. In case you are using Windows, you can try MinGW compiler. You will also need GNU make for Windows (of course, unless you want to copy and paste all the commands from the Makefile directly).

Python libraries

  • Of course, you should have FastAPI installed (pip3 install fastapi)
  • You should have an ASGI server. In this project cythonized version of uvicorn is used. (pip3 install "uvicorn[standart]")
  • Make sure you have Cython installed (pip3 install cython)

C compiler

  • You can use any C compiler that can build Python/C API code, but I recommend you to use standart gcc compiler. (sudo apt-get install gcc)

Run the project

make && make run

Check the server

$ curl -i http://localhost:5000/method/ftl.test
HTTP/1.1 200 OK
date: Sat, 16 Sep 2023 08:58:08 GMT
server: uvicorn
content-length: 16
content-type: application/json

{"ping":"pong2"}