Skip to main content

Posts

Showing posts with the label python

How to support both JSON or Form Data in Flask Routes ?

I have been recently working on a flask web API project. One of my API routes' is expecting data to be posted from a form, or sent via JSON payload (Swagger UI).  In this blog, we'll explore a smart approach to handling both JSON and form data seamlessly within your Flask routes. The challenge was in creating routes that can gracefully handle both scenarios without cumbersome if-else blocks. data = request.json or request.form.to_dict() This single line of code drastically simplifies the route's logic. Let's break it down: request.json attempts to parse the incoming data as JSON. If the data isn't in JSON format, it returns None. request.form.to_dict() takes care of parsing form data into a dictionary. This method returns an empty dictionary if no form data is present. By using the or operator, we create a neat and efficient way to handle both JSON and form payload scenarios.  from flask import Flask, request app = Flask(__name__) @app.route('/process_data&#

How to plot Pandas Dataframe as a Table in Python using Plotly?

Sometime its necessary to plot the pandas Dataframe as a table in python/Jupyter notebook, for instance for an easy reference to the Data dictionary. This is made easy by using plotly. Step 1: Install Plolty  pip install plotly Step 2: Import Plotly import plotly.graph_objects as go Step 3:  Plot the table  # read the data dictonary data_dict = pd.read_csv("data_dictionary.csv") fig = go.Figure(data=[go.Table(     header=dict(values=list(data_dict.columns),                 fill_color='paleturquoise',                 align='left'),     cells=dict(values=data_dict.transpose().values.tolist(),                fill_color='lavender',                align='left')) ]) fig.show()