10.05.2018       Выпуск 229 (07.05.2018 - 13.05.2018)       Статьи

Что такое hug?

Кортко о микро-фреймворке


Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

Hug is an API development framework implemented in Python 3. It is a micro-framework (minimalistic web application framework), which means that it contains as little code and integrations as possible to make it fully functional, which in turn provides greater performance, as in its own website indicates we can summarize Hug in 4 words “Obvious. Clean. Radically simple”.

In the following image we can see a performed benchmark done by pycnic:

In the graph we can see the number of requests per second made to different Python frameworks, with Hug being in third place with a little more than 3000 requests  per second, which deams this framework a great alternative to powerful and modern frameworks like Flask.

Much of this performance is obtained thanks to the fact that it is compiled with Cython

Aside from that, Hug has a very powerful feature: The same development of an endpoint of an API serves to consume via HTTP, from a terminal or from local use, which translates into that Hug can be used as a python library.

Following the previous point, being a micro-framework, it also greatly simplifies the implementation of an API, so making an API REST with this framework is quite simple and can be done in a few minutes, a clear example of its simplicity can be seen below:

Another point to consider when deciding to create your API with Hug is that it contains no database system integration, so you should use a library such as SQLAlchemy. Some Developers, who are used to frameworks such as Django may perceive this as a negative, but they really shouldn't because thanks to this, it is possible to abstract from the framework and use the same code for different applications which are not attached to a single framework or database

First steps with Hug

To start developing at Hug we highly recommend you to do the  quickstart out of interest, some of the elements needed to define a new endpoint would be:

  • @hug.cli: With this decorator it will be specified that the method can be used by means of a command line as follows:

  • hug -f example_cli.py -c endpoint param1 param2

  • @hug.get:With this decorator you will specify that the method can be usedthrough an HTTP request. There are decorators for the different HTTP methods..

  • @hug.local:  With this decorator it will be specified that the method will be able to be used using python code, so you can import and use it as python code.

How to document our API?

This frameworkalready provides a documentation system for it, by means of which all endpoints are listed and the parameters received and examples of requests are specified.

For the documentation of the parameters received by the endpoint, the nomenclature proposed by hug must be used, as follows: age:hug.types.number where for each type of data there will be a different type. This also acts as a validator of the data received when a request is made to the endpoint.

To document the API with examples, you can use the Decorator for HTTP methods to parameterize the example that will be shown in the documentation: examples="param1=Param_test&param2=30"

API Version

For the API versioning, hug uses a trivial system passing as a parameter in the HTTP endpoint decorator, through which it is possible to define endpoints for each version of the API, being able to define a method for several versions of the same. The API versioning is implemented as follows:

  • versions=1:This is to indicate a single version for the API.

  • versions=range(2, 5):This indicates multiple versions of the API for the same endpoint.

Testing HUG

Within the framework there is a library to implement the tests of the different endpoints, being able to integrate them into other testing frameworks such as unittest, pytest, etc..

This library contained within hug is used as follows:

response = hug.test.get(python_module, 'endpoint_name', {'param1: 'param_1', 'param2: 25})

With this we will have the answer that we are going to receive from hug and we will be able to implement the necessary tests according to the testing framework that is being used.

Problems with HUG

One of the identified problems that can occur when using HUGs is in the pre-processing of requests (this problem is actually inherited by falcon, the framework that hugs).

In particular, the problem occurs if you want to get the parameters specified in the request, since the body of the request is specified in a stream, which means that it can only be read once and if, in the method that pre-processes the request you need to read the body of the request, you will leave the stream empty and hug will not be able to obtain the input parameters.

To solve this, we made a little snippet:


def process_data(request, response):

   body = request.stream.read()

   stream = io.BytesIO(body)

   request.body_params = body.decode('utf-8')

   request.stream = stream

In this snippet what we will do is read the body of the stream, create a new stream with the result obtained when reading the original one, add a new field to the request object (body_params) where we will have the body of the request to use whenever we want and finally, we assign the new stream to the request so that hug can follow its normal flow.

We have worked with HUG on a number of projects with quite good results in both performance and development speed, so we believe it is an option to contemplate considering that their user community is currently growing.


Лучшая Python рассылка

Разместим вашу рекламу

Пиши: mail@pythondigest.ru

Нашли опечатку?

Выделите фрагмент и отправьте нажатием Ctrl+Enter.

Система Orphus