Points to Note When Deploying Pytorch in Python via a Rest API in Flask

Mustapha Unubi Momoh
2 min readAug 5, 2022

Like many people, have you tried to follow the tutorial on the Pytorch website to deploy your model, and also to make inferences with your deployed deep learning model but were barraged with errors including ‘‘requests’ not defined’, error? Here’s how you can solve one of these errors:

‘requests’ not defined:

We both know that the cause of this error is quite obvious —surely, the fix should be quite easy you might think. Yes and No!

The obvious culprit is a missing “requests” library. Yet, the error persists after you’ve installed ‘requests’. Like many experts (speaking, impostorically ¯\_(ツ)_/¯) out there, I spent the better part of my week trying to fix this error. How could the solution to an error be so obvious and so elusive at the same time? Lol, I finally gave in and took a break.

The fix: What I later found is that if you are building in a virtual environment (venv), you should endeavor to install “requests” in that environment. The first step to resolving this error is navigating to the project folder and installing “requests” by running this command:

Step 1: pipenv install requests

Ensure that venv is active. You can activate it by using the command activate.

Step 2: Open your test.py file i.e. the python file that contains the logic for your POST request and ensure it contains the import requests command. The file simulates a client. Take note of the ‘s’ in ‘requests’

by the Author

Step 3: Start the web server. If you are on Windows make sure to:

  1. set FLASK_ENV = development
  2. set FLASK_APP = app.py
  3. flask run
by the Author

Step 4: Once the server is live, launch a new command prompt window or a new terminal in vscode. Navigate to the project directory, and activate the virtual environment (very important). Lastly, run the test.py file.

by the Author

Voila, test.py will now run without throwing requests not defined error.

Hit the follow button for more on deploying deep learning models. 😊

--

--

Mustapha Unubi Momoh

A Python Developer and Data Scientist passionate about Computer vision and NLP