Categories
Python Answers

How to solve cross origin resource sharing error with Flask and Python?

Sometimes, we want to solve cross origin resource sharing error with Flask and Python.

In this article, we’ll look at how to solve cross origin resource sharing error with Flask and Python.

How to solve cross origin resource sharing error with Flask and Python?

To solve cross origin resource sharing error with Flask and Python, we can use the flask-cors package.

To install it, we run

pip install -U flask-cors

Then we use it by writing

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def hello_world():
   return "Hello, cross-origin-world!"

to call CORS with app to enable CORS throughout the app.

Conclusion

To solve cross origin resource sharing error with Flask and Python, we can use the flask-cors package.

Categories
Python Answers

How to convert date to timestamp with JavaScript?

Sometimes, we want to convert date to timestamp with JavaScript.

In this article, we’ll look at how to convert date to timestamp with JavaScript.

How to convert date to timestamp with JavaScript?

To convert date to timestamp with JavaScript, we can split the date string with split.

And then we pass the parts into the Date constructor.

For instance, we write

const myDate = "26-02-2022";
const [date, month, year] = myDate.split("-");
const newDate = new Date(year, month - 1, date);
console.log(newDate.getTime());

to call myDate.split with '-' to split the date string by '-'.

Then we create a new Date object with the year, month, and date.

We subtract month by 1 before we pass it into Date since JavaScript date’s months starts ranges from 0 for January and ends with 11 for December.

And then we call getTime to get the timestamp.

Conclusion

To convert date to timestamp with JavaScript, we can split the date string with split.

And then we pass the parts into the Date constructor.

Categories
Python Answers

How to pretty print nested dictionaries with Python?

Sometimes, we want to pretty print nested dictionaries with Python.

In this article, we’ll look at how to pretty print nested dictionaries with Python.

How to pretty print nested dictionaries with Python?

To pretty print nested dictionaries with Python, we call json.dumps with the indent argument.

For instance, we write

import json

print(
    json.dumps(
        {"a": 2, "b": {"x": 3, "y": {"t1": 4, "t2": 5}}}, sort_keys=True, indent=4
    )
)

to print the JSON string returned by json.dumps.

We call it with indent set to 4 to indent by 4 spaces in each level.

Conclusion

To pretty print nested dictionaries with Python, we call json.dumps with the indent argument.

Categories
Python Answers

How to iterate over model instance field names and values in template with Python Django?

Sometimes, we want to iterate over model instance field names and values in template with Python Django.

In this article, we’ll look at how to iterate over model instance field names and values in template with Python Django.

How to iterate over model instance field names and values in template with Python Django?

To iterate over model instance field names and values in template with Python Django, we can use a for loop.

For instance, we write

from django.forms.models import model_to_dict


def show(request, object_id):
    object = FooForm(data=model_to_dict(Foo.objects.get(pk=object_id)))
    return render_to_response("foo/foo_detail.html", {"object": object})

in the show view that passes the object object to the foo_detail.html template.

Then in the template, we write

{% for field in object %}
    <li><b>{{ field.label }}:</b> {{ field.data }}</li>
{% endfor %}

to loop through the object attributes and get the attribute name from label and the attribute value from data.

Conclusion

To iterate over model instance field names and values in template with Python Django, we can use a for loop.

Categories
Python Answers

How to get list from Python Pandas dataframe column or row?

Sometimes, we want to get list from Python Pandas dataframe column or row.

In this article, we’ll look at how to get list from Python Pandas dataframe column or row.

How to get list from Python Pandas dataframe column or row?

To get list from Python Pandas dataframe column or row, we use the tolist method.

For instance, we write

import pandas as pd

data_dict = {
    "one": pd.Series([1, 2, 3], index=["a", "b", "c"]),
    "two": pd.Series([1, 2, 3, 4], index=["a", "b", "c", "d"]),
}

df = pd.DataFrame(data_dict)
col_one_list = df["one"].tolist()

to create the df data frame from the data_dict dict.

Then we get column one’s values with df['one'] and call tolist to return the values in the series as a list.

Conclusion

To get list from Python Pandas dataframe column or row, we use the tolist method.