From 06a700925c0655b9643b0a6929e9aba7d8bbd20e Mon Sep 17 00:00:00 2001 From: Robin Schroer Date: Thu, 27 Oct 2016 15:46:55 +0100 Subject: [PATCH 1/2] Code test --- .dockerignore | 2 + .gitignore | 3 + Dockerfile | 9 ++ README.md | 59 ++++++++++++ Vagrantfile | 18 ++++ docker-compose.yml | 18 ++++ manage.py | 22 +++++ manapy | 3 + requirements.in | 3 + scripts/runserver | 10 ++ scripts/setup-server-user.sh | 33 +++++++ scripts/setup-server.sh | 15 +++ shiptrader/__init__.py | 0 shiptrader/admin.py | 3 + shiptrader/migrations/0001_initial.py | 43 +++++++++ shiptrader/migrations/__init__.py | 0 shiptrader/models.py | 19 ++++ shiptrader/tests.py | 3 + shiptrader/views.py | 3 + testsite/__init__.py | 0 testsite/settings.py | 129 ++++++++++++++++++++++++++ testsite/urls.py | 21 +++++ testsite/wsgi.py | 16 ++++ 23 files changed, 432 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 Vagrantfile create mode 100644 docker-compose.yml create mode 100755 manage.py create mode 100755 manapy create mode 100644 requirements.in create mode 100755 scripts/runserver create mode 100755 scripts/setup-server-user.sh create mode 100755 scripts/setup-server.sh create mode 100644 shiptrader/__init__.py create mode 100644 shiptrader/admin.py create mode 100644 shiptrader/migrations/0001_initial.py create mode 100644 shiptrader/migrations/__init__.py create mode 100644 shiptrader/models.py create mode 100644 shiptrader/tests.py create mode 100644 shiptrader/views.py create mode 100644 testsite/__init__.py create mode 100644 testsite/settings.py create mode 100644 testsite/urls.py create mode 100644 testsite/wsgi.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ccca24a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +.git +*.pyc \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b3f6532 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pyc +.vagrant +*.log \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5457092 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM alpine:3.6 + +RUN apk add --update py3-pip python3 postgresql postgresql-dev zlib-dev libjpeg-turbo-dev gcc python3-dev musl-dev make \ + && pip3 install --upgrade pip +RUN if [[ ! -e /usr/bin/python ]]; then ln -sf /usr/bin/python3 /usr/bin/python; fi + +WORKDIR /srv/python-code-test +ADD requirements.in /srv/python-code-test/ +RUN pip3 install -r requirements.in \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a83e86e --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# Ostmodern Python Code Test + +The goal of this exercise is to test that you know your way around Django and +REST APIs. Approach it the way you would an actual long-term project. + +The idea is to build a platform on which your users can buy and sell Starships. +To make this process more transparent, it has been decided to source some +technical information about the Starships on sale from the [Starship +API](https://swapi.co/documentation#starships). + +A Django project some initial data models have been created already. You may need +to do some additional data modelling to satify the requirements. + +## Getting started + +* This test works with either + [Docker](https://docs.docker.com/compose/install/#install-compose) or + [Vagrant](https://www.vagrantup.com/downloads.html) +* Get the code from `https://github.com/ostmodern/python-code-test` +* Do all your work in your own `develop` branch +* Once you have downloaded the code the following commands will get the site up + and running + +```shell +# For Docker +docker-compose up +# You can run `manage.py` commands using the `./manapy` wrapper + +# For Vagrant +vagrant up +vagrant ssh +# Inside the box +./manage.py runserver 0.0.0.0:8008 +``` +* The default Django "It worked!" page should now be available at + http://localhost:8008/ + +## Tasks + +Your task is to build a JSON-based REST API for your frontend developers to +consume. You have built a list of user stories with your colleagues, but you get +to decide how to design the API. Remember that the frontend developers will need +some documentation of your API to understand how to use it. + +We do not need you to implement users or authentication, to reduce the amount of +time this exercise will take to complete. You may use any external libraries you +require. + +* We need to be able to import all existing + [Starships](https://swapi.co/documentation#starships) to the provided Starship + Model +* A potential buyer can browse all Starships +* A potential buyer can browse all the listings for a given `starship_class` +* A potential buyer can sort listings by price or time of listing +* To list a Starship as for sale, the user should supply the Starship name and + list price +* A seller can deactivate and reactivate their listing + +After you are done, create a release branch in your repo and send us the link. diff --git a/Vagrantfile b/Vagrantfile new file mode 100644 index 0000000..6fab5ed --- /dev/null +++ b/Vagrantfile @@ -0,0 +1,18 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + +# Vagrantfile API/syntax version. Don't touch unless you know what you're doing! +VAGRANTFILE_API_VERSION = "2" + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + config.vm.box = "ubuntu/xenial64" + + # Django runserver networking + config.vm.network "forwarded_port", guest: 8008, host: 8008 + + config.vm.provision "shell", path:"./scripts/setup-server.sh" + + config.vm.provider :virtualbox do |vb, override| + vb.memory = 512 + end +end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0513217 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,18 @@ +version: "3" +services: + code-test: + build: + context: . + command: "scripts/runserver" + volumes: + - .:/srv/python-code-test + ports: + - "8008:8008" + links: + - postgresql + postgresql: + image: postgres:9.6 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: postgres diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..b99c032 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/manapy b/manapy new file mode 100755 index 0000000..b667b52 --- /dev/null +++ b/manapy @@ -0,0 +1,3 @@ +#!/bin/bash + +docker-compose run --rm code-test ./manage.py $* diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000..13869b0 --- /dev/null +++ b/requirements.in @@ -0,0 +1,3 @@ +django>=1.11,<2.0 +Pillow>=3.4.1,<3.5 +psycopg2>=2.6.2,<2.7 diff --git a/scripts/runserver b/scripts/runserver new file mode 100755 index 0000000..e53be2b --- /dev/null +++ b/scripts/runserver @@ -0,0 +1,10 @@ +#!/bin/sh + +until PGPASSWORD=postgres psql --host postgresql --username postgres -c '\l' > /dev/null; do + echo "Postgres is unavailable - sleeping" + sleep 1 +done + +export PYTHONUNBUFFERED=0 +./manage.py migrate +./manage.py runserver 0.0.0.0:8008 diff --git a/scripts/setup-server-user.sh b/scripts/setup-server-user.sh new file mode 100755 index 0000000..3215a14 --- /dev/null +++ b/scripts/setup-server-user.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# VirtualEnv and Django setup + +USER=ubuntu + +# Set up virtualenv directory for the user if required +if [ ! -d /home/$USER/.virtualenvs ]; then + mkdir /home/$USER/.virtualenvs +fi + +# write all the profile stuff for the user if required +grep -q virtualenvs /home/$USER/.bashrc +if [ $? -ne 0 ]; then + echo -e "\033[0;31m > Updating profile file\033[0m" + echo "source ~/.virtualenvs/code-test/bin/activate" >> /home/$USER/.bashrc + echo "cd /vagrant/" >> /home/$USER/.bashrc +fi + +echo -e "\033[0;34m > Setting up virtualenv\033[0m" +export WORKON_HOME=/home/$USER/.virtualenvs +export PIP_VIRTUALENV_BASE=/home/$USER/.virtualenvs +python3 -m venv $PIP_VIRTUALENV_BASE/code-test +source $PIP_VIRTUALENV_BASE/code-test/bin/activate + +# install requirements +echo -e "\033[0;34m > Installing the pip requirements.\033[0m" +$PIP_VIRTUALENV_BASE/code-test/bin/pip install -U pip +$PIP_VIRTUALENV_BASE/code-test/bin/pip install wheel==0.29.0 +$PIP_VIRTUALENV_BASE/code-test/bin/pip install -r /vagrant/requirements.in + +# setup db state +cd /vagrant +./manage.py migrate diff --git a/scripts/setup-server.sh b/scripts/setup-server.sh new file mode 100755 index 0000000..c9cbdc9 --- /dev/null +++ b/scripts/setup-server.sh @@ -0,0 +1,15 @@ +#!/bin/bash +USER=ubuntu + +apt-get update +apt-get install -y git vim build-essential python3.5-dev python3-venv \ + libncurses5-dev fabric postgresql-9.5 postgresql-server-dev-9.5 \ + libjpeg62-dev zlib1g-dev libfreetype6-dev + +sudo -u postgres psql -c "CREATE DATABASE postgres ENCODING='UTF8' TEMPLATE=template0;" +sudo -u postgres psql -c "CREATE USER ubuntu;" +sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO ubuntu;" +sudo -u postgres psql -c "ALTER USER ubuntu CREATEDB;" + +chmod +x /vagrant/scripts/setup-server-user.sh +sudo -H -u $USER /vagrant/scripts/setup-server-user.sh diff --git a/shiptrader/__init__.py b/shiptrader/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shiptrader/admin.py b/shiptrader/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/shiptrader/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/shiptrader/migrations/0001_initial.py b/shiptrader/migrations/0001_initial.py new file mode 100644 index 0000000..5a3bfc5 --- /dev/null +++ b/shiptrader/migrations/0001_initial.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.9 on 2018-01-16 13:15 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Listing', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255)), + ('price', models.IntegerField()), + ], + ), + migrations.CreateModel( + name='Starship', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('starship_class', models.CharField(max_length=255)), + ('manufacturer', models.CharField(max_length=255)), + ('length', models.FloatField()), + ('hyperdrive_rating', models.FloatField()), + ('cargo_capacity', models.BigIntegerField()), + ('crew', models.IntegerField()), + ('passengers', models.IntegerField()), + ], + ), + migrations.AddField( + model_name='listing', + name='ship_type', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='listings', to='shiptrader.Starship'), + ), + ] diff --git a/shiptrader/migrations/__init__.py b/shiptrader/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shiptrader/models.py b/shiptrader/models.py new file mode 100644 index 0000000..7fc3377 --- /dev/null +++ b/shiptrader/models.py @@ -0,0 +1,19 @@ +from django.db import models + + +class Starship(models.Model): + starship_class = models.CharField(max_length=255) + manufacturer = models.CharField(max_length=255) + + length = models.FloatField() + hyperdrive_rating = models.FloatField() + cargo_capacity = models.BigIntegerField() + + crew = models.IntegerField() + passengers = models.IntegerField() + + +class Listing(models.Model): + name = models.CharField(max_length=255) + ship_type = models.ForeignKey(Starship, related_name='listings') + price = models.IntegerField() diff --git a/shiptrader/tests.py b/shiptrader/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/shiptrader/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/shiptrader/views.py b/shiptrader/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/shiptrader/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/testsite/__init__.py b/testsite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/testsite/settings.py b/testsite/settings.py new file mode 100644 index 0000000..549b890 --- /dev/null +++ b/testsite/settings.py @@ -0,0 +1,129 @@ +""" +Django settings for testsite project. + +Generated by 'django-admin startproject' using Django 1.11.8. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +DOCKER = os.getenv('USER') != 'ubuntu' + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'a-z$8$66fyjy01^328r$5nmj=bzz2a8m%^-kf403!(ohrg5k_b' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'shiptrader', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'testsite.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'testsite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'postgres', + } +} + +if DOCKER: + DATABASES['default']['NAME'] = 'postgres' + DATABASES['default']['HOST'] = 'postgresql' + DATABASES['default']['USER'] = 'postgres' + DATABASES['default']['PASSWORD'] = 'postgres' + + +# Password validation +# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/testsite/urls.py b/testsite/urls.py new file mode 100644 index 0000000..0bd1a31 --- /dev/null +++ b/testsite/urls.py @@ -0,0 +1,21 @@ +"""testsite URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import url +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), +] diff --git a/testsite/wsgi.py b/testsite/wsgi.py new file mode 100644 index 0000000..a65c11b --- /dev/null +++ b/testsite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for testsite project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.settings") + +application = get_wsgi_application() From e8a9deccf2c760fda940711b041213ed191be3e9 Mon Sep 17 00:00:00 2001 From: Jakub Nyckowski Date: Wed, 13 Mar 2019 15:14:18 +0000 Subject: [PATCH 2/2] Initial solution implementation --- Dockerfile | 7 +- Pipfile | 18 ++ Pipfile.lock | 163 ++++++++++++++++++ SOLUTION.md | 53 ++++++ requirements.in | 3 - shiptrader/admin.py | 9 +- .../management/commands/import_ships.py | 53 ++++++ .../migrations/0002_auto_20190313_0239.py | 20 +++ .../migrations/0003_auto_20190313_0947.py | 27 +++ .../migrations/0004_auto_20190313_1407.py | 25 +++ .../migrations/0005_auto_20190313_1452.py | 40 +++++ shiptrader/models.py | 22 ++- shiptrader/serializers.py | 25 +++ shiptrader/views.py | 25 ++- testsite/settings.py | 26 ++- testsite/urls.py | 14 +- 16 files changed, 502 insertions(+), 28 deletions(-) create mode 100644 Pipfile create mode 100644 Pipfile.lock create mode 100644 SOLUTION.md delete mode 100644 requirements.in create mode 100644 shiptrader/management/commands/import_ships.py create mode 100644 shiptrader/migrations/0002_auto_20190313_0239.py create mode 100644 shiptrader/migrations/0003_auto_20190313_0947.py create mode 100644 shiptrader/migrations/0004_auto_20190313_1407.py create mode 100644 shiptrader/migrations/0005_auto_20190313_1452.py create mode 100644 shiptrader/serializers.py diff --git a/Dockerfile b/Dockerfile index 5457092..5166a80 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,10 @@ FROM alpine:3.6 RUN apk add --update py3-pip python3 postgresql postgresql-dev zlib-dev libjpeg-turbo-dev gcc python3-dev musl-dev make \ - && pip3 install --upgrade pip + && pip3 install --upgrade pip pipenv RUN if [[ ! -e /usr/bin/python ]]; then ln -sf /usr/bin/python3 /usr/bin/python; fi WORKDIR /srv/python-code-test -ADD requirements.in /srv/python-code-test/ -RUN pip3 install -r requirements.in \ No newline at end of file +ADD Pipfile /srv/python-code-test/ +ADD Pipfile.lock /srv/python-code-test/ +RUN pipenv install --deploy --system \ No newline at end of file diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..a1beaf4 --- /dev/null +++ b/Pipfile @@ -0,0 +1,18 @@ +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[dev-packages] +yapf = "*" + +[packages] +django = ">=1.11,<2.0" +djangorestframework = "*" +django-filter = "*" +Pillow = ">=3.4.1,<3.5" +psycopg2-binary = "*" +requests = "*" + +[requires] +python_version = "3.6" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000..2f1c3b9 --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,163 @@ +{ + "_meta": { + "hash": { + "sha256": "cf37637d8f502a28e6c491a978b9fd61da56a3c1d78660662695ec0625344f0b" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.6" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "certifi": { + "hashes": [ + "sha256:59b7658e26ca9c7339e00f8f4636cdfe59d34fa37b9b04f6f9e9926b3cece1a5", + "sha256:b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae" + ], + "version": "==2019.3.9" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "version": "==3.0.4" + }, + "django": { + "hashes": [ + "sha256:0a73696e0ac71ee6177103df984f9c1e07cd297f080f8ec4dc7c6f3fb74395b5", + "sha256:43a99da08fee329480d27860d68279945b7d8bf7b537388ee2c8938c709b2041" + ], + "index": "pypi", + "version": "==1.11.20" + }, + "django-filter": { + "hashes": [ + "sha256:3dafb7d2810790498895c22a1f31b2375795910680ac9c1432821cbedb1e176d", + "sha256:a3014de317bef0cd43075a0f08dfa1d319a7ccc5733c3901fb860da70b0dda68" + ], + "index": "pypi", + "version": "==2.1.0" + }, + "djangorestframework": { + "hashes": [ + "sha256:8a435df9007c8b7d8e69a21ef06650e3c0cbe0d4b09e55dd1bd74c89a75a9fcd", + "sha256:f7a266260d656e1cf4ca54d7a7349609dc8af4fe2590edd0ecd7d7643ea94a17" + ], + "index": "pypi", + "version": "==3.9.2" + }, + "idna": { + "hashes": [ + "sha256:c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407", + "sha256:ea8b7f6188e6fa117537c3df7da9fc686d485087abf6ac197f9c46432f7e4a3c" + ], + "version": "==2.8" + }, + "pillow": { + "hashes": [ + "sha256:0142d0508315428014badb00325742e2e3d90339734f58ddaa072f9ec15420c4", + "sha256:0ee9975c05602e755ff5000232e0335ba30d507f6261922a658ee11b1cec36d1", + "sha256:3e1b1993e65bb40e9751ba7d00acb57ad954687bcadf14cbca9e8faeb57af4d2", + "sha256:61b082064279d26dd292a4ced8d7a25fb8aea488dde9d71928ffc1c4f898cfcb", + "sha256:6831afdd1e5542faf5c197b2d535be2c95976778cd658c96276220d3c1a3f526", + "sha256:75a8fed85ca8e4ba87662f41563c7bb0c2c02b31739db132d8bfda2cdce9163f", + "sha256:78667f7252947a72c2dc439593d369ec7ec2f1f4443d73239ae196797fbd8e0b", + "sha256:85b237840ad8b30a1572bf9e3898a26c77910a56554d73ed4f58a42197c2e4c2", + "sha256:89f6b6e2ea7bcb842512a1c8168e0adf75de2ed64331971d5b65911e0313ea93", + "sha256:8ffabd1e2ee44be964b3f4df982a4be6ca29e93159c744f4b1a6519edf366bce", + "sha256:963aa56368688280f22c1f21e2b23992424f7cfe167f0ec300eb6453f03d6a49", + "sha256:979ca0d32b932fdd0ca9e3ec842e4bead6bba80612b45c7d77639d96d3453c7a", + "sha256:a44ed4fd02dde15d1968fb5bc732427d3e179f93cc8420927423a308d30040a1", + "sha256:a922540cc5881d3006d272e3ffdb693414a7e9bca2fa9443309cdd23eca0651c", + "sha256:b1dbc2d8a11505eea4537d43db20daa42b96126214cc4e291db73da174f23821", + "sha256:b28e94dfe4cfec91b1f9b6b07103f0dc18d195152499f936df7b7a6f0aa2ff67", + "sha256:bbbe42e9c2fb41bb78cfa6801880da29730836bc8e65eb6d8af5b7aa027a7151", + "sha256:be94b72de31747891c0a8cd45ab60e344f510f3f9f040fd55f1e25c0ddb6322c", + "sha256:c53c3d1a72d84f460091613894d4b610914acd874dcfcf74cbbd03970bdfa289", + "sha256:d94d5b6759be9401a23d8b8dcea8114d0d84aa2f2995886baa9923a8de2c78db", + "sha256:df68a56ff419eecb2a634f3acd735bd57bfbc31244efd18e822ac01cf9e31795", + "sha256:f9d2dd1c7007a97eb2832bcc30798bea181176b248d7362b6033d1c97e83c355", + "sha256:fbb384b0936c9e71c5456707699e0fcdf6ce1004c08766463b8f48035651eea3", + "sha256:fdc641ac432115e35d31441dbb253b016beea467dff402259d74b4df5e5f0f63" + ], + "index": "pypi", + "version": "==3.4.2" + }, + "psycopg2-binary": { + "hashes": [ + "sha256:19a2d1f3567b30f6c2bb3baea23f74f69d51f0c06c2e2082d0d9c28b0733a4c2", + "sha256:2b69cf4b0fa2716fd977aa4e1fd39af6110eb47b2bb30b4e5a469d8fbecfc102", + "sha256:2e952fa17ba48cbc2dc063ddeec37d7dc4ea0ef7db0ac1eda8906365a8543f31", + "sha256:348b49dd737ff74cfb5e663e18cb069b44c64f77ec0523b5794efafbfa7df0b8", + "sha256:3d72a5fdc5f00ca85160915eb9a973cf9a0ab8148f6eda40708bf672c55ac1d1", + "sha256:4957452f7868f43f32c090dadb4188e9c74a4687323c87a882e943c2bd4780c3", + "sha256:5138cec2ee1e53a671e11cc519505eb08aaaaf390c508f25b09605763d48de4b", + "sha256:587098ca4fc46c95736459d171102336af12f0d415b3b865972a79c03f06259f", + "sha256:5b79368bcdb1da4a05f931b62760bea0955ee2c81531d8e84625df2defd3f709", + "sha256:5cf43807392247d9bc99737160da32d3fa619e0bfd85ba24d1c78db205f472a4", + "sha256:676d1a80b1eebc0cacae8dd09b2fde24213173bf65650d22b038c5ed4039f392", + "sha256:6b0211ecda389101a7d1d3df2eba0cf7ffbdd2480ca6f1d2257c7bd739e84110", + "sha256:79cde4660de6f0bb523c229763bd8ad9a93ac6760b72c369cf1213955c430934", + "sha256:7aba9786ac32c2a6d5fb446002ed936b47d5e1f10c466ef7e48f66eb9f9ebe3b", + "sha256:7c8159352244e11bdd422226aa17651110b600d175220c451a9acf795e7414e0", + "sha256:945f2eedf4fc6b2432697eb90bb98cc467de5147869e57405bfc31fa0b824741", + "sha256:96b4e902cde37a7fc6ab306b3ac089a3949e6ce3d824eeca5b19dc0bedb9f6e2", + "sha256:9a7bccb1212e63f309eb9fab47b6eaef796f59850f169a25695b248ca1bf681b", + "sha256:a3bfcac727538ec11af304b5eccadbac952d4cca1a551a29b8fe554e3ad535dc", + "sha256:b19e9f1b85c5d6136f5a0549abdc55dcbd63aba18b4f10d0d063eb65ef2c68b4", + "sha256:b664011bb14ca1f2287c17185e222f2098f7b4c857961dbcf9badb28786dbbf4", + "sha256:bde7959ef012b628868d69c474ec4920252656d0800835ed999ba5e4f57e3e2e", + "sha256:cb095a0657d792c8de9f7c9a0452385a309dfb1bbbb3357d6b1e216353ade6ca", + "sha256:d16d42a1b9772152c1fe606f679b2316551f7e1a1ce273e7f808e82a136cdb3d", + "sha256:d444b1545430ffc1e7a24ce5a9be122ccd3b135a7b7e695c5862c5aff0b11159", + "sha256:d93ccc7bf409ec0a23f2ac70977507e0b8a8d8c54e5ee46109af2f0ec9e411f3", + "sha256:df6444f952ca849016902662e1a47abf4fa0678d75f92fd9dd27f20525f809cd", + "sha256:e63850d8c52ba2b502662bf3c02603175c2397a9acc756090e444ce49508d41e", + "sha256:ec43358c105794bc2b6fd34c68d27f92bea7102393c01889e93f4b6a70975728", + "sha256:f4c6926d9c03dadce7a3b378b40d2fea912c1344ef9b29869f984fb3d2a2420b" + ], + "index": "pypi", + "version": "==2.7.7" + }, + "pytz": { + "hashes": [ + "sha256:32b0891edff07e28efe91284ed9c31e123d84bea3fd98e1f72be2508f43ef8d9", + "sha256:d5f05e487007e29e03409f9398d074e158d920d36eb82eaf66fb1136b0c5374c" + ], + "version": "==2018.9" + }, + "requests": { + "hashes": [ + "sha256:502a824f31acdacb3a35b6690b5fbf0bc41d63a24a45c4004352b0242707598e", + "sha256:7bf2a778576d825600030a110f3c0e3e8edc51dfaafe1c146e39a2027784957b" + ], + "index": "pypi", + "version": "==2.21.0" + }, + "urllib3": { + "hashes": [ + "sha256:61bf29cada3fc2fbefad4fdf059ea4bd1b4a86d2b6d15e1c7c0b582b9752fe39", + "sha256:de9529817c93f27c8ccbfead6985011db27bd0ddfcdb2d86f3f663385c6a9c22" + ], + "version": "==1.24.1" + } + }, + "develop": { + "yapf": { + "hashes": [ + "sha256:edb47be90a56ca6f3075fe24f119a22225fbd62c66777b5d3916a7e9e793891b", + "sha256:f58069d5e0df60c078f3f986b8a63acfda73aa6ebb7cd423f6eabd1cb06420ba" + ], + "index": "pypi", + "version": "==0.26.0" + } + } +} diff --git a/SOLUTION.md b/SOLUTION.md new file mode 100644 index 0000000..6d55c90 --- /dev/null +++ b/SOLUTION.md @@ -0,0 +1,53 @@ +Q&A +--- + +*We need to be able to import all existing Starships to the provided Starship Model* + +`./manage.py import_ships` + +*A potential buyer can browse all Starships* + +`http://localhost:8008/starships/` + +*A potential buyer can browse all the listings for a given starship_class* + +Example: + +`http://localhost:8008/listings?ship_type__starship_class=Star dreadnought` + +*A potential buyer can sort listings by price or time of listing* + +`http://localhost:8008/listings?ordering=price` + +`http://localhost:8008/listings?ordering=created` + +*To list a Starship as for sale, the user should supply the Starship name and list price* + +Example: + +`POST http://localhost:8008/listings/43/` + +```json +{ + "ship_name": "abc", + "price": 1020 +} +``` + +*A seller can deactivate and reactivate their listing* + +Example: + +`PATCH http://localhost:8008/listings/43/` +```json +{ + "active": false +} +``` +or activate with `"active": true` + +Other +--- + +I migrated the project from `pip` to `pipenv`. +I formatted the code with `yapf` to be consistent and follow PEP8 rules. \ No newline at end of file diff --git a/requirements.in b/requirements.in deleted file mode 100644 index 13869b0..0000000 --- a/requirements.in +++ /dev/null @@ -1,3 +0,0 @@ -django>=1.11,<2.0 -Pillow>=3.4.1,<3.5 -psycopg2>=2.6.2,<2.7 diff --git a/shiptrader/admin.py b/shiptrader/admin.py index 8c38f3f..c7e2d4b 100644 --- a/shiptrader/admin.py +++ b/shiptrader/admin.py @@ -1,3 +1,10 @@ from django.contrib import admin -# Register your models here. +from shiptrader.models import Starship + + +class StarshipAdmin(admin.ModelAdmin): + model = Starship + + +admin.site.register(Starship, StarshipAdmin) \ No newline at end of file diff --git a/shiptrader/management/commands/import_ships.py b/shiptrader/management/commands/import_ships.py new file mode 100644 index 0000000..3f9a189 --- /dev/null +++ b/shiptrader/management/commands/import_ships.py @@ -0,0 +1,53 @@ +import requests +from django.core.management import BaseCommand + +from shiptrader.models import Starship, Listing +from shiptrader.serializers import StarshipSerializer + + +class Command(BaseCommand): + def handle(self, *args, **kwargs): + starship_url = 'https://swapi.co/api/starships/' + records = [] + while starship_url: + print('Reading a page...') + req = requests.get(url=starship_url) + req.raise_for_status() + json_data = req.json() + starship_url = json_data['next'] # last page sets this value to None + records += [*json_data['results']] + + print(f'Fetched {len(records)} records') + + for record in records: + ship = Starship.objects.all().filter(name=record['name']) + if ship: + print(f"Ship {record['name']} already exists") + continue + try: + starship_data = { + "name": record['name'], + 'starship_class': record['starship_class'], + 'manufacturer': record['manufacturer'], + 'length': record['length'], + 'hyperdrive_rating': record['hyperdrive_rating'], + 'cargo_capacity': record['cargo_capacity'], + 'crew': record['crew'], + 'passengers': record['passengers'], + } + starship = StarshipSerializer(data=starship_data) + + if not starship.is_valid(): + for e in starship.errors.keys(): + del starship_data[e] + starship = StarshipSerializer(data=starship_data) + if not starship.is_valid(): + raise ValueError('we tried, but failed again :(') + + ship_obj = starship.save() + + Listing.objects.create( + ship_type=ship_obj, price=record['cost_in_credits']) + print(f'Saved {ship_obj.name}') + except ValueError as e: + print(e) diff --git a/shiptrader/migrations/0002_auto_20190313_0239.py b/shiptrader/migrations/0002_auto_20190313_0239.py new file mode 100644 index 0000000..1f51d57 --- /dev/null +++ b/shiptrader/migrations/0002_auto_20190313_0239.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.20 on 2019-03-13 02:39 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('shiptrader', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='listing', + name='price', + field=models.BigIntegerField(), + ), + ] diff --git a/shiptrader/migrations/0003_auto_20190313_0947.py b/shiptrader/migrations/0003_auto_20190313_0947.py new file mode 100644 index 0000000..9291e81 --- /dev/null +++ b/shiptrader/migrations/0003_auto_20190313_0947.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.20 on 2019-03-13 09:47 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('shiptrader', '0002_auto_20190313_0239'), + ] + + operations = [ + migrations.AddField( + model_name='listing', + name='active', + field=models.BooleanField(default=True), + ), + migrations.AddField( + model_name='listing', + name='created', + field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), + preserve_default=False, + ), + ] diff --git a/shiptrader/migrations/0004_auto_20190313_1407.py b/shiptrader/migrations/0004_auto_20190313_1407.py new file mode 100644 index 0000000..92a5f85 --- /dev/null +++ b/shiptrader/migrations/0004_auto_20190313_1407.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.20 on 2019-03-13 14:07 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('shiptrader', '0003_auto_20190313_0947'), + ] + + operations = [ + migrations.RemoveField( + model_name='listing', + name='name', + ), + migrations.AddField( + model_name='starship', + name='name', + field=models.CharField(default='', max_length=255), + preserve_default=False, + ), + ] diff --git a/shiptrader/migrations/0005_auto_20190313_1452.py b/shiptrader/migrations/0005_auto_20190313_1452.py new file mode 100644 index 0000000..9de1a65 --- /dev/null +++ b/shiptrader/migrations/0005_auto_20190313_1452.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.20 on 2019-03-13 14:52 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('shiptrader', '0004_auto_20190313_1407'), + ] + + operations = [ + migrations.AlterField( + model_name='starship', + name='cargo_capacity', + field=models.BigIntegerField(null=True), + ), + migrations.AlterField( + model_name='starship', + name='crew', + field=models.IntegerField(null=True), + ), + migrations.AlterField( + model_name='starship', + name='hyperdrive_rating', + field=models.FloatField(null=True), + ), + migrations.AlterField( + model_name='starship', + name='length', + field=models.FloatField(null=True), + ), + migrations.AlterField( + model_name='starship', + name='passengers', + field=models.IntegerField(null=True), + ), + ] diff --git a/shiptrader/models.py b/shiptrader/models.py index 7fc3377..aaa7741 100644 --- a/shiptrader/models.py +++ b/shiptrader/models.py @@ -2,18 +2,26 @@ class Starship(models.Model): + name = models.CharField(max_length=255) starship_class = models.CharField(max_length=255) manufacturer = models.CharField(max_length=255) - length = models.FloatField() - hyperdrive_rating = models.FloatField() - cargo_capacity = models.BigIntegerField() + length = models.FloatField(null=True) + hyperdrive_rating = models.FloatField(null=True) + cargo_capacity = models.BigIntegerField(null=True) + + crew = models.IntegerField(null=True) + passengers = models.IntegerField(null=True) - crew = models.IntegerField() - passengers = models.IntegerField() + def __str__(self): + return self.starship_class class Listing(models.Model): - name = models.CharField(max_length=255) ship_type = models.ForeignKey(Starship, related_name='listings') - price = models.IntegerField() + price = models.BigIntegerField() + active = models.BooleanField(default=True) + created = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return self.ship_type.name diff --git a/shiptrader/serializers.py b/shiptrader/serializers.py new file mode 100644 index 0000000..74e51ed --- /dev/null +++ b/shiptrader/serializers.py @@ -0,0 +1,25 @@ +from rest_framework import serializers +from rest_framework.generics import get_object_or_404 + +from shiptrader.models import Starship, Listing + + +class StarshipSerializer(serializers.ModelSerializer): + class Meta: + model = Starship + fields = ('name', 'starship_class', 'manufacturer', 'length', + 'hyperdrive_rating', 'cargo_capacity', 'crew', 'passengers') + + +class ListingSerializer(serializers.ModelSerializer): + ship_name = serializers.CharField(max_length=255, write_only=True) + ship_type = StarshipSerializer(read_only=True) + + class Meta: + model = Listing + fields = ('id', 'price', 'ship_type', 'active', 'created', 'ship_name') + + def create(self, validated_data): + ship_name = validated_data.pop('ship_name') + ship = get_object_or_404(Starship, name=ship_name) + return Listing.objects.create(**validated_data, ship_type=ship) diff --git a/shiptrader/views.py b/shiptrader/views.py index 91ea44a..8f1b0d5 100644 --- a/shiptrader/views.py +++ b/shiptrader/views.py @@ -1,3 +1,24 @@ -from django.shortcuts import render +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework import viewsets, filters -# Create your views here. +from shiptrader.models import Starship, Listing +from shiptrader.serializers import StarshipSerializer, ListingSerializer + + +class StarshipViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows Starships to be viewed or edited. + """ + queryset = Starship.objects.all().order_by('name') + serializer_class = StarshipSerializer + + +class ListingViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows Listings to be viewed or edited. + """ + queryset = Listing.objects.all().order_by('-created') + serializer_class = ListingSerializer + filterset_fields = ('ship_type__starship_class', ) + filter_backends = (filters.OrderingFilter, DjangoFilterBackend) + ordering_fields = ('active', 'price') diff --git a/testsite/settings.py b/testsite/settings.py index 549b890..fb413cf 100644 --- a/testsite/settings.py +++ b/testsite/settings.py @@ -17,7 +17,6 @@ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ @@ -29,7 +28,6 @@ ALLOWED_HOSTS = [] - # Application definition INSTALLED_APPS = [ @@ -40,6 +38,7 @@ 'django.contrib.messages', 'django.contrib.staticfiles', 'shiptrader', + 'rest_framework', ] MIDDLEWARE = [ @@ -72,7 +71,6 @@ WSGI_APPLICATION = 'testsite.wsgi.application' - # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases @@ -89,25 +87,36 @@ DATABASES['default']['USER'] = 'postgres' DATABASES['default']['PASSWORD'] = 'postgres' - # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + 'NAME': + 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + 'NAME': + 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + 'NAME': + 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + 'NAME': + 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] +REST_FRAMEWORK = { + 'DEFAULT_PAGINATION_CLASS': + 'rest_framework.pagination.PageNumberPagination', + 'PAGE_SIZE': + 10, + 'DEFAULT_FILTER_BACKENDS': + ('django_filters.rest_framework.DjangoFilterBackend', ), +} # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ @@ -122,7 +131,6 @@ USE_TZ = True - # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ diff --git a/testsite/urls.py b/testsite/urls.py index 0bd1a31..74ea6e4 100644 --- a/testsite/urls.py +++ b/testsite/urls.py @@ -13,9 +13,17 @@ 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ -from django.conf.urls import url +from django.conf.urls import include, url from django.contrib import admin +from rest_framework import routers + +from shiptrader import views + +router = routers.DefaultRouter() +router.register(r'starships', views.StarshipViewSet) +router.register(r'listings', views.ListingViewSet) urlpatterns = [ - url(r'^admin/', admin.site.urls), -] + url(r'^', include(router.urls)), + url(r'^admin/', include(admin.site.urls)), +] \ No newline at end of file