Python - servers

From NoskeWiki
Jump to navigation Jump to search

About

NOTE: This page is a daughter page of: Python


Some of the most used python HTTP server libraries, ordered by popularity, according to ChatGPT in Sep 2023 are:

  • Flask (with extensions like Flask-RESTful)
    • Flask remains one of the most popular web frameworks in the Python ecosystem due to its simplicity and flexibility.
    • PyPI Downloads: Over 100 million for Flask (exact numbers can vary) | GitHub Stars: 55k+ for Flask
  • Django REST framework (DRF)
    • Built on top of Django, DRF has become a standard for many developers when building RESTful APIs, especially for projects that also use Django for the web application.
    • PyPI Downloads: Over 70 million | GitHub Stars: 20k+
  • FastAPI
    • FastAPI has seen a surge in popularity because of its performance, ease of use, and automatic generation of OpenAPI documentation. Its use of modern Python typing has also been a distinguishing feature.
    • PyPI Downloads: Over 30 million | GitHub Stars: 35k+
  • Tornado
    • Tornado has been a consistent choice for developers requiring non-blocking web servers and has a significant user base.
    • PyPI Downloads: Over 100 million | GitHub Stars: 20k+
  • Falcon
    • Praised for its minimalist approach and performance, Falcon is often chosen for high-performance applications.
    • PyPI Downloads: Several million | GitHub Stars: 8k+
  • Sanic
    • Sanic gained attention for its asynchronous capabilities, allowing for fast HTTP responses.
    • PyPI Downloads: Several million | GitHub Stars: 15k+
  • Pyramid
    • While it might not be as popular as Flask or Django, Pyramid has a dedicated user base and is known for its modularity.
  • Starlette
    • As a lightweight ASGI framework, Starlette often serves as a foundation for other frameworks (like FastAPI) but can also be used directly for building APIs.
  • Connexion
    • Especially useful for projects that want to define APIs using the OpenAPI specification, Connexion offers a unique approach to building RESTful services.
  • CherryPy
    • CherryPy has been around for a while and is known for its object-oriented approach to building web applications.


Python Servers

Flask

A little example using Flask:

First install Flask with:

$ pip3 install Flask

Then:

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks = [
    {'id': 1, 'title': 'Do homework', 'done': False},
    {'id': 2, 'title': 'Buy groceries', 'done': True}
]

@app.route('/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

@app.route('/tasks', methods=['POST'])
def create_task():
    new_task = {
        'id': len(tasks) + 1,
        'title': request.json['title'],
        'done': request.json.get('done', False)
    }
    tasks.append(new_task)
    return jsonify({'task': new_task}), 201

@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = next((t for t in tasks if t['id'] == task_id), None)
    if task is None:
        return jsonify({'error': 'Task not found'}), 404
    return jsonify({'task': task})

if __name__ == '__main__':
    print("""WHEN RUNNING TRY OPEN: http://127.0.0.1:5000/tasks/1

... and create a new task with:
 $ curl -X POST -H "Content-Type: application/json" -d '{"title": "New task"}' http://127.0.0.1:5000/tasks       
""")
    app.run(debug=True)

Now test it with:

$ curl -X GET http://127.0.0.1:5000/tasks
$ curl -X POST -H "Content-Type: application/json" -d '{"title": "New task"}' http://127.0.0.1:5000/tasks
$ curl -X GET http://127.0.0.1:5000/tasks/3


Django

1. Setup

First, you'll need to install Django and Django REST framework:

$ pip install django djangorestframework

2. Create a new Django project

$ django-admin startproject mybookapi
$ cd mybookapi

3. Create a new app

$ python manage.py startapp books

4. Define the Book model

In books/models.py:

from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=200)
    
    def __str__(self):
        return self.name

5. Register the model

In books/admin.py:

from django.contrib import admin
from .models import Book

admin.site.register(Book)

6. Create the serializer

In books/serializers.py:

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'name']

7. Create the API view

In books/views.py:

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListCreate(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

8. Configure URLs

First, add the new app and the rest_framework to the INSTALLED_APPS in mybookapi/settings.py:

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'books',
]

Then, configure the URL in mybookapi/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/books/', include('books.urls')),
]

Now, create a new file books/urls.py:

from django.urls import path
from .views import BookListCreate

urlpatterns = [
    path('', BookListCreate.as_view(), name='book-list-create'),
]

9. Run migrations and start the server

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

With this setup, you can navigate to http://127.0.0.1:8000/api/books/ to interact with the API. Use tools like curl or Postman to POST new books and GET the list of books.


Links