Make a simple app and learn PostgreSQL, Django, React, Python, and GraphQL

Dongyob (Eric)
6 min readApr 17, 2019
  1. Install NodeJS, an editor, PostgreSQL, pgAdmin and Python (and add to PATH)
  • Go to nodejs.org and install long term support version of node to enable npm. Npm helps managing and installing packages essential for react.
  • Install a code editor of your choice. ie) Visual Studio Code
  • Go to postgresql.org. download and install latest version of PostgreSQL database. This installer includes the PostgreSQL server, pgAdmin; a graphical tool for managing and developing your databases, and StackBuilder; a package manager that can be used to download and install additional PostgreSQL tools and drivers. Stackbuilder includes management, integration, migration, replication, geospatial, connectors and other tools.
  • Go to python.org and download Python. Before an installation, make sure to check a box on “Add Python to PATH” to make Python commands available globally.
  • If Python commands do not work outside of Python app, re-add Python to PATH by either 1) reinstalling Python or 2) manually adding Python to PATH. To manually re-add Python to PATH, follow below.
1. On windows search box, type python
2. Right click on python app and open file location
3. Right click on python (x.x) version shortcut, open file location
4. Copy the address of the file location
5. Type environment variables in the Windows search box, click on it
6. In the settings, click on environment variables
7. Select Path in the user variables, click edit, click new, paste the copied address
8. repeat number 7 in the system variables section. Then hit Ok

2. Setup virtual environment using Python (for PC)

  • Virtual environment can isolate dependencies (i.e Graphene, PostgreSQL libraries) installed for the project from the global environment. Isolated dependencies make project deployment faster and make it easy to track all required dependencies for the project. (fig 2.1) Follow below steps to create virtual environment.
Step 1: $pip install pipenv #for Windows PC, install on global env
Step 2: Create Project folder and go into that folder
Step 3: $pipenv shell #which activates venv and creates pipfile, showing all installed dependencies)environment) (fig 2.1)
Step 4: $pipenv install (...dependencies)
Step 5: $exit (to exit out of venv)
Misc 1: $pipenv -h (shows all commands)
Misc 2: $pip freeze # shows all dependencies on current scope
Fig 2.1 pipfile shows all dependencies installed and isolated for the project

3. Install dependencies to virtual environment

  • Below are examples of dependencies I install to make Django, GraphQL and PostgreSQL available to the project
$pipenv install [following]:requests
json
django
graphene-django
django-graphql-jwt (makes django json web token usable with graphql)
django-cors-headers (for white-listing frontend server connection)
psycopg2 (for postgresql)
psycopg2-binary (for postgresql)
--dev autopep8 Indentation errors
*NOTE: If pipenv doesn't work for some reason, try py -m and then entering your commands

4. Start Django project and create its apps

  • While the virtual environment mode is enabled, generate Django project automatically using below command.
$django-admin startproject [project name] # creates project
  • Multiple apps can be created inside the Django project. Django breaks the project into small application for separation of concerns. Run below commands to create apps.
$django-admin startapp [app name] #creates app. 
//Make sure to create app using startapp in app folder
//Note that app is subset of project
//startproject contains settings module
//startapp contains models module
  • Run below code to launch the django project.
$python manage.py runserver #runs server
$./manage.py help # shows all available commands
$django-admin help # shows all available commands

$python --version #shows the current version of the python

5. Setup PostgreSQL in a Django project

  • Replace database settings with below codes in Django project settings to enable PostgreSQL.
Note that setup requirments may change due to version update.
  • Whenever changes are made to the database, run following code to sync the database.
$python manage.py makemigrations
$python manage.py migrate

6. Add Required Models & Create Instances

  • Before writing any code for the project, I like to visualize database structure using RDBMS (Relational Database Management System) diagram. I find it much easier to plan out and visualize the project using this diagram. Not forgetting to mention, it helps building an efficient database structure as well. Below is a simplified example of RDBMS diagram for a simple Django project, I will use to illustrate how I would create models and related instances and perform other things throughout this article.
Note that Product Category has recursive(self calling) one/none to many relationship. In depth knowledge in RDBMS is beyond the scope or this article. Please check other internet sources to conceptualize. Product and Product Category have one to many relationship; One Product can only have one Product Category but one Product Category may have multiple Products.
  • Below shows how RDBMS diagram above is converted and written in Python codes as a “product” app model.
  • Make above app model available to the project by adding below codes on Django project settings
  • SQL Table (model) instances can be created using the prompt commands illustrated below.
$ python manage.py shell
>>>from product.models import Product
>>>product.objects.create(productNumber="8625_Typ2_Cl2_Red", description="Red Anodize", productCategory = ProductCategory.objects.get(category="Anodization"))*productCategory here is a foreign key.

7. Setup Graphene Django

  • After completing data model structure and its instances for the Django app, setup Graphene (GraphQL) to the Django project using below codes in the Django project settings. Graphene is a middleware that does the legwork in seriving backend data API to the frontend.
  • Create a schema.py in the Django project apps that have model.py files. Note that schema.py makes the data accessible to graphene from the database. Query enables reading on data and Mutation enables creating, updating and deleting data.
  • Make app schemas availabe to Django project by adding below schema.py file to the main project folder.
  • Enable GraphQL view through url.py in Djago project.

8. Test Grapql Queries and Mutations

  • Query example below
  • Mutation example below

9. Django Security Tips

1. DEBUG=False #never forget this when deployed
2. SECRET_KEY #should be long and not be predictable
3. A known seed makes your random number generator completely predictable. seed is number ie) random.seed(1234). random number generator is not truly random.
4. development and production secret_key should always be different.(and when the environment changes, you also should change the scret_key)
5. pickling, converting your code to binary is not recommended for production because it's risky and it only works with python interpreter. Also never unpickle data received from an untrusted or unauthenticated source.
6. it is not safe to call yaml.load with any data received from an untrusted source. yaml.load is as powerful as pickle.load and so may call many python function. Use yaml.safe_load instead when you are forced to use it.
7.json is more secure because it's fundamentally more limited on what you can express. Do not do silly stuff like eval() on Json. use built-in deserializer.
8.XML is also used for serialization and deserialization. Billion laughs attack can eat up your entire memory with a small XML file. but it's not destructive. You should never trust user created XML.
9.Never trust user input.
10. be wary of SQL injection attack take advantage of Django ORM where possible.
  1. Documentation
django-graphql-jwt 
https://docs.djangoproject.com/en/3.0/

2. Django idea in brief

  • Django breaks the project into small application for separation of concerns.
  • Ships with ORM (Object-Relational Mapper) that can be used to interact with application data from various relational databases such as SQLLite, PostgresSQL and MySQL. Django can easily migrate the data from one type of relational database to another.
  • Comes with many useful prebuilt features such as jwt, etc to speed up the app building process

Another way to create virtual env:

Step 1: $python -m venv ./venv (creates venv folder in the project)
Step 2: source ./venv/Scripts/activate (activates venv in vscode)
Step 3: $deactivate (leave the venv)
Misc 1: $lsvirtualenv -b (list all virtualenv)
Misc 2: $ rmvirtualenv [venvironment name] (removes venv)

--

--