Categories
React Answers

How to intercept and handle browser’s back button in React Router v6?

Sometimes, we want to intercept and handle browser’s back button in React Router v6.

In this article, we’ll look at how to intercept and handle browser’s back button in React Router v6.

How to intercept and handle browser’s back button in React Router?

To intercept and handle browser’s back button in React Router, we can listen for changes in the history object with the navigation.listen method.

For instance, we write

import { BrowserHistory } from "history";
import React, { useContext } from "react";
import { UNSAFE_NavigationContext } from "react-router-dom";

export default function usePathname() {
  const [state, setState] = React.useState(window.location.pathname);

  const navigation = useContext(UNSAFE_NavigationContext)
    .navigator;
  React.useLayoutEffect(() => {
    if (navigation) {
      navigation.listen((locationListener) =>
        setState(locationListener.location.pathname)
      );
    }
  }, [navigation]);

  return state;
}

to create the usePathname hook to listen for for navigation with navigation.listen.

We call it with a callback to listen for navigation.

In it, we call setState with locationListener.location.pathname to save the latest URL we navigated to as the value of state.

Conclusion

To intercept and handle browser’s back button in React Router, we can listen for changes in the history object with the navigation.listen method.

Categories
Python Answers

How to deploy a minimal Python Flask app in Docker?

Sometimes, we want to deploy a minimal Python Flask app in Docker.

In this article, we’ll look at how to deploy a minimal Python Flask app in Docker.

How to deploy a minimal Python Flask app in Docker?

To deploy a minimal Python Flask app in Docker, we create a Dockerfile in our Flask project directory.

For instance, we write

FROM dreen/flask
MAINTAINER dreen
WORKDIR /src


RUN mkdir -p /src
COPY . .

EXPOSE 5000
CMD ["python", "index.py"]

in our Dockerfile.

Then in index.py, we write

# ...

if __name__ == '__main__':
    app.run(host='0.0.0.0')

to run the app and expose it to all computers in the local network so that it can be served over the Internet.

Then we run

sudo docker run -i -p 5000:5000 -d my-project

to create the Docker image from the Flask project which is in the my-project directory with the Dockerfile inside.

Conclusion

To deploy a minimal Python Flask app in Docker, we create a Dockerfile in our Flask project directory.

Categories
Python Answers

How to add a link to Python Flask static files with url_for?

Sometimes, we want to add a link to Python Flask static files with url_for.

In this article, we’ll look at how to add a link to Python Flask static files with url_for.

How to add a link to Python Flask static files with url_for?

To add a link to Python Flask static files with url_for, we can call it with the view name and the URL parameters.

For instance, we write

url_for('static', filename='path/to/file')

to call url_for with the name of the endpoint and the URL parameter filename‘s value respectively.

Conclusion

To add a link to Python Flask static files with url_for, we can call it with the view name and the URL parameters.

Categories
Python Answers

How to send data from HTML form to a Python script in Flask?

Sometimes, we want to send data from HTML form to a Python script in Flask.

In this article, we’ll look at how to send data from HTML form to a Python script in Flask.

How to send data from HTML form to a Python script in Flask?

To send data from HTML form to a Python script in Flask, we can use the request.form dictionary to get the data.

For instance, w ewrite

from flask import request

@app.route('/add_region', methods=['POST'])
def add_region():
    #...
    return (request.form['file_path'])

to get the form data with the request.form dict.

And then we create our form with

<form action="{{ url_for('add_region') }}" method="post">
    Project file path: <input type="text" name="file_path"><br>
    <input type="submit" value="Submit">
</form>

in our template.

request.form['file_path'] has the value of the input with name attribute set to file_path in our form.

action is {{ url_for('add_region') }} which is the URL to the add_region endpoint.

Categories
Python Answers

How to get POSTed JSON in Python Flask?

Sometimes, we want to get POSTed JSON in Python Flask.

In this article, we’ll look at how to get POSTed JSON in Python Flask.

How to get POSTed JSON in Python Flask?

To get POSTed JSON in Python Flask, we can use the request.json property.

For instance, we write

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    return jsonify({"uuid":uuid})

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

to create the add_message route that gets the JSON payload from request.json.

request.json returns a dictionary.

We make add_message accept POST requests with

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])

Conclusion

To get POSTed JSON in Python Flask, we can use the request.json property.