DEV Community

Cover image for How to deploy a Python/Flask App to Vercel
Andrew Baisden
Andrew Baisden

Posted on • Edited on

How to deploy a Python/Flask App to Vercel

This is just a quick simple example of course more complex applications will work as well.

Prerequisites

Step 1

Create an account with Vercel if you don't already have one.

Vercel is a cloud platform for static sites and Serverless Functions that fits perfectly with your workflow. It enables developers to host Jamstack websites and web services that deploy instantly, scale automatically, and requires no supervision, all with no configuration.

Step 2

Use npm to install Vercel globally on your computer https://www.npmjs.com/package/vercel

npm i -g vercel
Enter fullscreen mode Exit fullscreen mode

Step 3

Make sure that you have the latest version of Python3 installed and the Flask framework with pip3

https://pypi.org/project/Flask/

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Setup the project

Create a project

If you are having problems getting the virtual environment to work then read this documentation https://docs.python.org/3/library/venv.html

mkdir vercel-python-app
cd vercel-python-app
python3 -m venv venv
. venv/bin/activate
cd venv
touch index.py
Enter fullscreen mode Exit fullscreen mode

Open the project in your code editor and then create a Python/Flask server in the index.py file

from flask import Flask


app = Flask(__name__)


@app.route('/')
def home():
    return 'Home Page Route'


@app.route('/about')
def about():
    return 'About Page Route'


@app.route('/portfolio')
def portfolio():
    return 'Portfolio Page Route'


@app.route('/contact')
def contact():
    return 'Contact Page Route'


@app.route('/api')
def api():
    with open('data.json', mode='r') as my_file:
        text = my_file.read()
        return text
Enter fullscreen mode Exit fullscreen mode

Setup the development environment by running these commands in your terminal.

export FLASK_APP=index.py   
export FLASK_ENV=development
Enter fullscreen mode Exit fullscreen mode

If you are using Windows then see here for the environment variable syntax https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application

Now create a data.json file and put it in the root folder for venv and add the .json below into it

[
    {
        "id": 1,
        "first_name": "Rene",
        "last_name": "Clemmett",
        "email": "rclemmett0@linkedin.com",
        "gender": "Male",
        "ip_address": "42.86.99.75"
    },
    {
        "id": 2,
        "first_name": "Rustie",
        "last_name": "Chrishop",
        "email": "rchrishop1@bloomberg.com",
        "gender": "Male",
        "ip_address": "197.128.10.252"
    },
    {
        "id": 3,
        "first_name": "Joe",
        "last_name": "Cocklie",
        "email": "jcocklie2@ustream.tv",
        "gender": "Male",
        "ip_address": "124.81.44.28"
    },
    {
        "id": 4,
        "first_name": "Diane",
        "last_name": "Catt",
        "email": "dcatt3@sogou.com",
        "gender": "Female",
        "ip_address": "169.47.61.184"
    },
    {
        "id": 5,
        "first_name": "Quinton",
        "last_name": "Shellsheere",
        "email": "qshellsheere4@icq.com",
        "gender": "Male",
        "ip_address": "2.57.97.184"
    },
    {
        "id": 6,
        "first_name": "Lena",
        "last_name": "Paull",
        "email": "lpaull5@tmall.com",
        "gender": "Female",
        "ip_address": "121.4.165.63"
    },
    {
        "id": 7,
        "first_name": "Corena",
        "last_name": "Lamswood",
        "email": "clamswood6@hud.gov",
        "gender": "Female",
        "ip_address": "78.65.53.3"
    },
    {
        "id": 8,
        "first_name": "Justinian",
        "last_name": "Nequest",
        "email": "jnequest7@virginia.edu",
        "gender": "Male",
        "ip_address": "62.24.98.224"
    },
    {
        "id": 9,
        "first_name": "Vladimir",
        "last_name": "Boeter",
        "email": "vboeter8@addthis.com",
        "gender": "Male",
        "ip_address": "87.119.34.255"
    },
    {
        "id": 10,
        "first_name": "Jillene",
        "last_name": "Eades",
        "email": "jeades9@amazon.de",
        "gender": "Female",
        "ip_address": "159.173.99.31"
    }
]
Enter fullscreen mode Exit fullscreen mode

Run the command below to see your Python/Flask app working locally in the browser

flask run
Enter fullscreen mode Exit fullscreen mode

Deploying to Vercel

Make sure that you are in the root folder for your project so inside of the venv folder and then run the command vercel in your terminal.

Use the project setup settings below as a guide to setup your own project with Vercel.

? Set up and deploy “~/Desktop/username/vercel-python-app/venv”? [Y/n] y
? Which scope do you want to deploy to? username
? Link to existing project? [y/N] n
? What’s your project’s name? venv
? In which directory is your code located? ./
> Upload [====================] 98% 0.0sNo framework detected. Default Project Settings:
- Build Command: `npm run vercel-build` or `npm run build`
- Output Directory: `public` if it exists, or `.`
- Development Command: None
? Want to override the settings? [y/N] n
Enter fullscreen mode Exit fullscreen mode

Once that is complete it is going to give you some links. The app is NOT going to work yet it is only going to give you a browser file download of your index.py file. You need to create a vercel.json file and put it in the root folder so that Vercel knows that it is a Python application. And it is very important that your index.py file remains in the root folder along with your other server side code for the project otherwise your app won't work.

Create a vercel.json file and put it in the root of your project folder and then add the code below

{
    "version": 2,
    "builds": [
        {
            "src": "./index.py",
            "use": "@vercel/python"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "/"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Next manually create a requirements.txt file and put it in the root folder with the code below

flask==1.0.2
Enter fullscreen mode Exit fullscreen mode

When creating a more complex application that has multiple packages installed it is best to use the command below for automatically creating a requirements.txt file. This is the equivalent to a package.json file which you should be familiar with if you have worked with Node. You will need to have your dependancies install on the server for it to work. However for this simple example it is not required as the only package that we are using is flask.

pip3 freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

Now run the command vercel --prod to deploy your app. Open the Production link and your app should be working online with full working routes.

Latest comments (47)

Collapse
 
tesaabi profile image
tesaabi

Hii, i've followed all the steps but still got this on the web

404: NOT_FOUND
Code: NOT_FOUND

Collapse
 
tesaabi profile image
tesaabi
Collapse
 
tesaabi profile image
tesaabi

update ^ the link above is not it

im using flas 2.2.3 cant it work with that version because when i try to deploy/ prod it gives me this "Error: Unable to find any supported Python versions." error

Collapse
 
an4s911 profile image
Anas Basheer

Hi. I know this is an old post, but there are still people who are following this tutorial I believe just like me. But as of the latest update in the vercel.json file, the "version": 2" should not be used anymore. For more details you can refer to vercel.com/docs/projects/project-c....

I hope you can update the existing code you provided and it will help others in the future, because I followed your tutorial and got completely stuck and was trying to figure out what was going wrong, the deployment always resulted in 404: NOT FOUND, and I was so confused.

Collapse
 
kyarottobacon profile image
Osman

i know i am absolutely late for the topic.but i gotta ask something..looked up everywhere to find a project that contains more than 1 python files deployed on vercel.in addition to app.py,i have 2 more classes with functions.deployment was an issue so i merged them all in app.py.want to set it up properly now.how should i write my vercel.json file? tried many things but could not manage to deploy.

Collapse
 
an4s911 profile image
Anas Basheer

Hi there, has it been resolved yet?

When you say more than 1 python file, you mean that you have more than 2 flask app files? It is possible, but there should always be one main module which imports all the other files, and that is the one you should include the vercel.json file.

Collapse
 
kyarottobacon profile image
Osman

I am importing the other files from "app.py" and the error i get is "module not found".

Collapse
 
nathanpamart profile image
Nathanpamart

Hi Andrew, just followed your post and it worked well for me. One question, I am trying to a build an app with next.js for the frontend and flask as the backend, within the same project on Vercel. How would you suggest setting this up?

Collapse
 
andrewbaisden profile image
Andrew Baisden

Hey I hope you found a solution sorry about the slow response I have a LOT of messages to check these days.

Collapse
 
johnnjuki profile image
John Njuki

So helpful. Thanks

Collapse
 
leerob profile image
Lee Robinson

Hey there! Thank you for writing this.

We now have a one-click deployable Flask example included in our documentation, as well as Django and a simple Python API.

Collapse
 
pierosalazaras1 profile image
Piero Salazar Ascencio

Hello, I have a app web deployed in vercel but when i add a library notify or plyer for web notifications my deploy not load. Maybe a suggestion plse?

Collapse
 
andrewbaisden profile image
Andrew Baisden

Hi I am going to archive this article because Vercel have changed their API and this code does not work as well anymore. They advise people to use Serverless Functions.

Collapse
 
gnvageesh profile image
GNVageesh

What command should we run after making an update to the project? And thanks for this tutorial

Kindly let me

Collapse
 
zeraye profile image
Jakub Rudnik

You are using flask==2.0.1? Unfortunately vercel don't support it (I think so, I'm not vercel dev).
Quick fix:
requirements.txt

flask==1.1.4
Enter fullscreen mode Exit fullscreen mode

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "./index.py",
      "use": "@vercel/python"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "index.py"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
whiterock profile image
whiterock

Thank you so much for this! I specifically signed up to this website for the sole reason to thank you - this information cannot be found anywhere else and I struggled with Flask 2.0.1 and vercel for hours today.

Collapse
 
huogerac profile image
Roger Camargo

Hi everyone!
It did work, however, I'd suggest few changes to make this post simpler:

  • Create the virtualenv first, preferably outside the project (instead of venv inside vercel-python-app, use ~/.venv/vercel for example)
  • active our virtualenv and install Flask
  • create the vercel-python-app folder, the index.py and the data.json
  • make sure it is working locally
  • create the requirements.txt and vercel.json inside the project folder (vercel-python-app)
  • lastly, inside the vercel-python-app (instead of venv folder), run the vercel command. In this way the deploy will work at first! It won't send all the site-packages, you won't need to duplicate the files

In another word, in this way, you can use the default python/flask structure. Just adding the vercel.json and running the vercel cmd, you make the deploy. Awesome!