Etiqueta: python

Quickly create web services using OpenAPI

OpenAPI is a documentation format created by Swagger to document how a web service works. It defines the paths, the methods and parameters. Let’s know how to quickly create web services using OpenAPI

Why I use it?

Usually documentation is one of the tasks that developers don’t like because it can be boring, hard, and take time. In this case it is really quick and it can be a way to increase your productivity, because this documentation can be used to generate.

Starting with OpenAPI

The OpenAPI format can be generated and viewed with a lot of tools, but my favorite is Apicurio, a free tool from Redhat. A great feature of it is that it can be collaborative

Apicurio studio
How Apicurio looks like

The Apicurio screen is splited on 4 parts

  • Paths: In this part you can see the paths the application uses, you can also click on it to view more details.
  • Data Types: The data types that the application will use and the relation with other data types.
  • Responses : The diferent types of responses of the application
  • Design: The content of this part can change to edit the details of the previous parts
Example of the configuration of a path

Once we have our OpenAPI defined , here starts the magic. We can generate a template code for our applications. To do this you can use this application https://github.com/OpenAPITools/openapi-generator.

Before generation, the code you will need to download is the OpenAPI definition from the Apicurio web

OpenAPI to Flask

If you are used toPython Flask is a great micro framework to create web applications.

openapi-generator-clo generate -g python-flask -i OpenApi.json -o ./code

OpenAPI to Angular

OpenApi can also help you if you are developing a frontend application. You can generate the service of the API using a simple command and it will generate you the code of the service

openapi-generator-cli generate -g typescript-angular -i OpenApi.json -o ./code

5 Python tricks

This is a short list of less known tricks that I use in Python

Delete repeated elements of a list

An easy way to delete repeated elements from a list is to convert it to a set and then convert to a list. This works because a set can’t have repeated elements.

a = [1,1,2,3]
print(list(set(a)))
[1, 2, 3]

Serve static files with HTTP

The python interpreter has the SimpleHttp module which is very useful. If you run this command on a directory you will be able to access to the files thought http.

python3 -m http.server 8080

Join a list of strings with a string separator

A useful not so known str function it’s the join method. You can use this to join a list with a string

",".join(["1","2","3"])
'1,2,3'

With this you don’t have to control if it’s the last element of the list to add the separator

Use a dictionary to pass parameters to a function

Sometimes you need to send data to functions and you need to adapt the same data to the function parameters, you can do this with the operator ** . This operator passes the values of the dictionary to a function using the key as a parameter name:

def function1(param1):
   print(f"function1:{param1}")

def function2(param2):
   print(f"function2:{param2}")

data ="hi"
data_function1 = {"param1": data}
data_function2 = {"param2": data}
function1(**data_function1)
function2(**data_function2)

Make ifs more readables

On of the zen of python is “Readability counts.” . This example shows a correct way to check None and False values on an if

# Wrong way
value = None
if value is None:
   print("No value")

# Wrong way
value = False
if value == False:
   print("Value False)

# Correct way
if not value:
   print("value false or None)

Sentry

Sentry is another service you don’t know that you need it until you try it.Basically Sentry is a service that catches the exceptions in your code and sends it to a web service to be analyzed, also sends you an email to notify you.

Sentry server is an opensource server that can be installed on your own server, also sentry can work as a SaS and you can use it at https://sentry.io/welcome/

Sentry can work with multiple languages from Python, to JS or Go, you can check all the supported languages here https://sentry.io/platforms/

Configuring sentry with python

First of all you need to create a project like this:

If you use some framework you can specify

Once you created the project you will get an screen like this

After this you will need to install the sentry package with this command:

pip install --upgrade sentry-sdk

You will need to add this on the package, if you use a setyp.py add it on the install_requires key or if you use it on a requirements.txt file you need to add it.

Now we need to initialize the sentry code. We do it adding this code on the entry point of the code.

import sentry_sdk
sentry_sdk.init(
    "!Place here your project DSN"
    traces_sample_rate=1.0
)

With this we have our script configured to catch all the exceptions with Sentry.

Extra usage

We can make our code notify an exception manually with sentry with this code:

from sentry_sdk import capture_exception
try:
    a=1/0
catch Exception as e:
    capture_exception(e)

Also can notify suspicious data without sending an exception with this code:

from sentry_sdk import capture_message
capture_message("Somthing strange")

Remote debug

Usually when you develop an application it will not run on the same computer where you are developing. This can caused unexpected behaviors when you deploy it,usually cause by permissions, software/package versions,configuration,ect.. or just that we write an error on our code that we didn’t notice. In those cases, it’s difficult to know what is failing but we can use remote debug to check the application state when it fails.

Tip:

If you are trying to debug a python package and the debugger doesn’t stop, try to install it with the -e flag

I use two tools in these cases:

Visual studio code remote ssh

To remote debug (and develop) with Visual Studio code you mus to install Remote ssh extenison

Once you install it, you can add a host that looks like this:

Add a new host on remote ssh.

And finally open a remote project:

Connect to a remote ssh and run a script.

After this, you can use Visual Studio code like on your own machine

PUDB

Pudb is a package to debug python applications via CLI. If you are used to and feel comfortable using CLI tools this can be a good tool to debug your python application.

To debug it with pudb you need to install the package with pip:

pip install pudb

On your code , add the following code where you want to stop:

import pudb;pu.db

Once the execution reaches the previous line, you will get a window that looks like this:

You can use the following shortcuts to interact with the pudb:

  • Ctrl+x: Go to command line or return to the code
  • n: Step to the next instruction
  • s: Step into
  • c: Continue
  • b: Toggle breakpoint

© 2024 Another dev

Tema de Anders NorenAmunt ↑