Code

Python Flask Server Cheat Sheet

May 15, 2020
python-flask-server-cheat-sheet

I recently been doing online courses for Web Development with Python and I got a couple of projects going on using Flask and Django. There is always that time when I just forget what command to use switching between different libraries so I made a compilation of code snippets and commands for Flask, so I can easily get them when I forget.

This post will be continually updated for as long as I use Flask. Feel free to add your own snippet in the comments section and I can list them here as well (with a link to your url). I’d like to keep this tidy and easy to use, so for now, I’ll just list down my most commonly used snippets you can run straight from your terminal (LINUX server commands).

$ flask run # run flask server without params
$ FLASK_ENV=development flask run # run flask server on development mode (changes are auto applied without having to restart the server
$ flask run -p 8080 # run flask server on port 8080
$ flask run -h '0.0.0.0' # if accessing server from another computer in the network, you need to specify this so it is accessible
$ flask run -p 8080 -h '0.0.0.0' # run flask with both params

When you’re done developing your app and want to run flask server in the background, you can use the following commands. Thanks to this helpful tutorial (Running a Python Script in the Background) from Parametric thoughts.

$ nohup python app.py & # run flask server in the background
$ ps -ef | grep app.py # check flask server process in the background, this shows the process ID for when you want to kill (terminate) the process
$ kill -9 PID # where PID is what you get from previous command output

Here are python scripts to use for configuring Flask server with Postgres, this works on my current setup: Python 3.7, Flask 1.1.2

app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql://postgres:postgres@localhost:5432/databasename'

For the above code, the database username and password is both ‘postgres’ and the host is ‘localhost’ on post 5432.

As I continue to write Python scripts, I will keep updating this cheat list, both for myself and for your guys who find it useful. Next up, I’ll keep a list of cheat sheet for Django too. It’s a work in progress right now. If you have a snippet you’d like to share, feel free to write it in comments and I’ll get around to including it here with a heartfelt thanks to you.

You Might Also Like

Share your thoughts

avatar
  Subscribe  
Notify of