Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • aasmuha/tdt4242-base
  • sebastvi/tdt4242-base
  • haavafar/tdt4242-base
  • tdt4242-spring-2021-t17/tdt4242-base
  • tmwang/tdt4242-base
  • tdt4242-group-t4/tdt4242-base
  • andstorh/tdt4242-base
  • reaas/tdt4242-base
  • andrerim/tdt4242-base
  • kristohh/tdt4242-base
  • andreajj/tdt4242-base
  • vegarms/tdt4242-base
  • andrend/tdt4242-base
  • haavarhu/tdt4242-base
  • mathilah/tdt4242-base
  • tmmothe/tdt4242-base
  • miriams/tdt4242-base
  • harkamas/tdt4242-base
  • chrisclo/tdt-4242-group-13
  • estherv/tdt4242-base
  • mariueng/tdt-4242-secfit
  • haakogun/secfit-haakon
  • haakonrj/tdt-4242-35
  • tdt4242-group-5/secfit
  • haakonjf/tdt-4242-gruppe6
  • nikolard/tdt-4242-sec-fit
  • tdt4242-gr24/tdt4242-base
  • abdulfaa/tdt4242-base
  • jmjohnse/tdt-4242-group-37-use
  • owengg/tdt-4242-base-owen-forked
  • ktsiow/tdt4242-base
  • olechrib/tdt4242-group16
  • eytan/tdt-4242-base-group-33
33 results
Show changes
Commits on Source (29)
Showing
with 799 additions and 7 deletions
stages:
- test
- staging
test:
image: python:3.8
stage: test
script:
# this configures Django application to use attached postgres database that is run on `postgres` host
- cd backend/secfit
- apt-get update -qy
- pip install -r requirements.txt
staging:
type: deploy
image: ruby
stage: staging
script:
- apt-get update -qy
- apt-get install -y ruby-dev
- gem install dpl
- dpl --provider=heroku --app=<your-frontend-app-name> --api-key=$HEROKU_STAGING_API_KEY
- dpl --provider=heroku --app=<your-backend-app-name> --api-key=$HEROKU_STAGING_API_KEY
only:
- master
web: gunicorn --pythonpath 'backend/secfit' secfit.wsgi --log-file -
\ No newline at end of file
......@@ -8,6 +8,8 @@ SecFit (Secure Fitness) is a hybrid mobile application for fitness logging.
Docker
Python 3.8.10
Git
Windows hosts must use Education or more advanced versions to run Docker \
......@@ -15,7 +17,7 @@ Download: https://innsida.ntnu.no/wiki/-/wiki/English/Microsoft+Windows+10
### Install:
$ git clone https://gitlab.stud.idi.ntnu.no/kyleo/secfit.git \
$ git clone https://gitlab.stud.idi.ntnu.no/<your_username>/tdt4242-base.git \
$ cd secfit/
### Run:
......@@ -23,6 +25,18 @@ $ cd secfit/
$ docker-compose up --build \
Hosts the application on http://localhost:9090 with default settings
You might have to run Docker with administrator privileges to get it to run properly:
#### Windows:
Either open the terminal as administrator (Windows key -> Search "cmd" -> "Run as administrator")
or
$ runas /user/Administrator "docker-compose up --build"
#### Unix/OSX:
$ sudo docker-compose up --build
## Technology
- **deployment** Docker
......@@ -126,3 +140,48 @@ If you want to run this as a mobile application
It's possible you will need to add the platforms you want to run and build.
The following documentation can be used to run the application in an Android emulator: \
https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html
## Continuous integration
WARNING: Do not perform penetration testing on Heroku applications
Continuous integration will build the code pushed to master and push it to your heroku app so you get a live version of your latest code by just pushing your code to GitLab.
1. Make sure you have the right python version (3.8.10) and have all other requirements installed.
2. Create a heroku account and an app for both the frontend and the backend. (Choose Europe as your region)
3. Select buildpacks for the two apps. The backend uses Python while the frontend uses nodejs.
* Heroku > Settings > Buildpacks > Add buildpack
* Both applications need the buildpack https://github.com/heroku/heroku-buildpack-multi-procfile.git too.
4. Set the two projects in the .gitlab-cs.yml file by replacing `<Your-herokuproject-name>` with the name of the Heroku apps you created. Commit and push your change.
`- dpl --provider=heroku --app=<Your-herokuproject-name> --api-key=$HEROKU_STAGING_API_KEY`
5. Set/Add varibles at GitLab
* GitLab > settings > ci > Variables > Expand
* Key = `HEROKU_STAGING_API_KEY`
* Value = Your API Key from Heroku (Heroku > Account Settings > API Key > Reveal)
* Type = Variable, Environment scope = All(default)
* Protect should not be enabled and Mask should be enabled
6. Add heroku database for the backend
* Heroku > Resources > Add ons > search for `postgres` > add "Heroku Postgres"
* Choose the free plan.
7. Set variables for the backend on Heroku. Heroku > Settings > Config vars > Reveal vars
* `DATABASE_URL` = Should be set by default. If not here is where you can find it: Heroku > Resources > postgress > settings > view credentials > URI
* `IS_HEROKU` = `IS_HEROKU`
* `PROCFILE` = `Procfile`
8. Set variables for the frontend on heroku. Heroku > Settings > Config vars > Reveal vars. Insert the URL for your backend app and the path to your Procfile. (Example: `https://secfit-group01-v22-backend.herokuapp.com`)
* `BACKEND_HOST` = `https://<SECFIT_BACKEND>.herokuapp.com`
* `PROCFILE` = `frontend/Procfile`
9. Push the repository to both of the heroku applications
* Follow the guides on https://devcenter.heroku.com/articles/git#for-an-existing-heroku-app
* Make sure you install the heroku CLI https://devcenter.heroku.com/articles/heroku-cli
* Make sure you log in to the heroku CLI ($ heroku login)
* Make sure you create a remote for the frontend and backend apps (Example: heroku git:remote -a secfit-group01-v22-frontend)
* Push your code to both apps (Your URLs can also be found on the settings page on your Heroku apps)
* Example: $ git push https://git.heroku.com/secfit-group01-v22-frontend.git master
* Make sure you use `master` and not `main` as your target branch
10. On GitLab go to CI / CD in the repository menu and select `Run Pipeline` if it has not already started. When both stages complete the app should be available on heroku. The log should state that the app was deployed.
11. Setup the applications database.
* Log in to the Heroku CLI by entering `heroku login` if you have not already done this. This opens a webbrowser and you accept the login request.
* Migrate database by entering
`heroku run python backend/secfit/manage.py migrate -a <heroku-app-name>`. `Heroku run` will run the folowing command on your heroku instance. Remember to replace `<heroku-app-name>` with your backend app name
* and create an admin account for the backend by running
`heroku run python backend/secfit/manage.py createsuperuser -a <heroku-app-name>`.
* seed database `heroku run python backend/secfit/manage.py loaddata backend/secfit/seed.json -a <heroku-app-name>`
"""Module for registering models from meals app to admin page so that they appear
"""
from django.contrib import admin
# Register your models here.
from .models import Meal, MealFile
admin.site.register(Meal)
admin.site.register(MealFile)
"""AppConfig for meals app
"""
from django.apps import AppConfig
class MealsConfig(AppConfig):
"""AppConfig for meals app
Attributes:
name (str): The name of the application
"""
name = "meals"
# Generated by Django 3.1 on 2021-10-20 15:17
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import meals.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Meal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('date', models.DateTimeField()),
('notes', models.TextField()),
('calories', models.IntegerField()),
('is_veg', models.BooleanField(default=False)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='meals', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-date'],
},
),
migrations.CreateModel(
name='MealFile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=meals.models.meal_directory_path)),
('meal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='files', to='meals.meal')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='meal_files', to=settings.AUTH_USER_MODEL)),
],
),
]
"""
Mixins for the meals application
"""
class CreateListModelMixin(object):
"""Mixin that allows to create multiple objects from lists.
Taken from https://stackoverflow.com/a/48885641
"""
def get_serializer(self, *args, **kwargs):
"""If an array is passed, set serializer to many.
kwargs["many"] will be set to true if an array is passed. This argument
is passed when retrieving the serializer.
Args:
*args: Variable length argument list passed to the serializer.
**kwargs: Arbitrary keyword arguments passed to the serializer, including "many".
Returns:
[type]: [description]
"""
if isinstance(kwargs.get("data", {}), list):
kwargs["many"] = True
return super(CreateListModelMixin, self).get_serializer(*args, **kwargs)
"""Contains the models for the meals Django application. Users
log meals (Meal). The user can also upload files (MealFile) .
"""
import os
from django.db import models
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from django.contrib.auth import get_user_model
class OverwriteStorage(FileSystemStorage):
"""Filesystem storage for overwriting files. Currently unused."""
def get_available_name(self, name, max_length=None):
"""https://djangosnippets.org/snippets/976/
Returns a filename that's free on the target storage system, and
available for new content to be written to.
Args:
name (str): Name of the file
max_length (int, optional): Maximum length of a file name. Defaults to None.
"""
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
# Create your models here.
class Meal(models.Model):
"""Django model for a meal that users can log.
A meal has several attributes, and files uploaded by the user.
Attributes:
name: Name of the meal
date: Date and time the meal was consumed
notes: Notes about the meal
calories: Total amount of calories in the meal
is_veg: Whether the meal was vegetarian or not
owner: User that logged the meal
"""
name = models.CharField(max_length=100)
date = models.DateTimeField()
notes = models.TextField()
calories = models.IntegerField()
is_veg = models.BooleanField(default=False)
owner = models.ForeignKey(
get_user_model(), on_delete=models.CASCADE, related_name="meals"
)
class Meta:
ordering = ["-date"]
def __str__(self):
return self.name
def meal_directory_path(instance, filename):
"""Return path for which meal files should be uploaded on the web server
Args:
instance (MealFile): MealFile instance
filename (str): Name of the file
Returns:
str: Path where workout file is stored
"""
return f"meals/{instance.meal.id}/{filename}"
class MealFile(models.Model):
"""Django model for file associated with a meal. Basically a wrapper.
Attributes:
meal: The meal for which this file has been uploaded
owner: The user who uploaded the file
file: The actual file that's being uploaded
"""
meal = models.ForeignKey(Meal, on_delete=models.CASCADE, related_name="files")
owner = models.ForeignKey(
get_user_model(), on_delete=models.CASCADE, related_name="meal_files"
)
file = models.FileField(upload_to=meal_directory_path)
"""Contains custom parsers for serializers from the meals Django app
"""
import json
from rest_framework import parsers
# Thanks to https://stackoverflow.com/a/50514630
class MultipartJsonParser(parsers.MultiPartParser):
"""Parser for serializing multipart data containing both files and JSON.
This is currently unused.
"""
def parse(self, stream, media_type=None, parser_context=None):
result = super().parse(
stream, media_type=media_type, parser_context=parser_context
)
data = {}
new_files = {"files": []}
# for case1 with nested serializers
# parse each field with json
for key, value in result.data.items():
if not isinstance(value, str):
data[key] = value
continue
if "{" in value or "[" in value:
try:
data[key] = json.loads(value)
except ValueError:
data[key] = value
else:
data[key] = value
files = result.files.getlist("files")
for file in files:
new_files["files"].append({"file": file})
return parsers.DataAndFiles(data, new_files)
"""Contains custom DRF permissions classes for the meals app
"""
from rest_framework import permissions
from meals.models import Meal
class IsOwner(permissions.BasePermission):
"""Checks whether the requesting user is also the owner of the existing object"""
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
class IsOwnerOfMeal(permissions.BasePermission):
"""Checks whether the requesting user is also the owner of the new or existing object"""
def has_permission(self, request, view):
if request.method == "POST":
if request.data.get("meal"):
meal_id = request.data["meal"].split("/")[-2]
meal = Meal.objects.get(pk=meal_id)
if meal:
return meal.owner == request.user
return False
return True
def has_object_permission(self, request, view, obj):
return obj.meal.owner == request.user
class IsReadOnly(permissions.BasePermission):
"""Checks whether the HTTP request verb is only for retrieving data (GET, HEAD, OPTIONS)"""
def has_object_permission(self, request, view, obj):
return request.method in permissions.SAFE_METHODS
"""Serializers for the meals application
"""
from rest_framework import serializers
from rest_framework.serializers import HyperlinkedRelatedField
from meals.models import Meal, MealFile
class MealFileSerializer(serializers.HyperlinkedModelSerializer):
"""Serializer for a MealFile. Hyperlinks are used for relationships by default.
Serialized fields: url, id, owner, file, meal
Attributes:
owner: The owner (User) of the MealFile, represented by a username. ReadOnly
meal: The associate meal for this MealFile, represented by a hyperlink
"""
owner = serializers.ReadOnlyField(source="owner.username")
meal = HyperlinkedRelatedField(
queryset=Meal.objects.all(), view_name="meal-detail", required=False
)
class Meta:
model = MealFile
fields = ["url", "id", "owner", "file", "meal"]
def create(self, validated_data):
return MealFile.objects.create(**validated_data)
class MealSerializer(serializers.HyperlinkedModelSerializer):
"""Serializer for a Meal. Hyperlinks are used for relationships by default.
This serializer specifies nested serialization since a meal consists of MealFiles.
Serialized fields: url, id, name, date, notes, calories, owner, is_veg, owner_username, files
Attributes:
owner_username: Username of the owning User
files: Serializer for MealFiles
"""
owner_username = serializers.SerializerMethodField()
files = MealFileSerializer(many=True, required=False)
class Meta:
model = Meal
fields = [
"url",
"id",
"name",
"date",
"notes",
"calories",
"is_veg",
"owner",
"owner_username",
"files",
]
extra_kwargs = {"owner": {"read_only": True}}
def create(self, validated_data):
"""Custom logic for creating MealFiles, and a Meal.
This is needed to iterate over the files, since this serializer is nested.
Args:
validated_data: Validated files
Returns:
Meal: A newly created Meal
"""
files_data = []
if "files" in validated_data:
files_data = validated_data.pop("files")
meal = Meal.objects.create(**validated_data)
for file_data in files_data:
MealFile.objects.create(
meal=meal, owner=meal.owner, file=file_data.get("file")
)
return meal
def update(self, instance, validated_data):
"""Custom logic for updating a Meal.
This is needed because each object in files must be iterated
over and handled individually.
Args:
instance (Meal): Current Meal object
validated_data: Contains data for validated fields
Returns:
Meal: Updated Meal instance
"""
instance.name = validated_data.get("name", instance.name)
instance.date = validated_data.get("date", instance.date)
instance.notes = validated_data.get("notes", instance.notes)
instance.is_veg = validated_data.get("is_veg", instance.is_veg)
instance.calories = validated_data.get("calories", instance.calories)
instance.save()
# Handle MealFiles
if "files" in validated_data:
files_data = validated_data.pop("files")
files = instance.files
for file, file_data in zip(files.all(), files_data):
file.file = file_data.get("file", file.file)
# If new files have been added, creating new MealFiles
if len(files_data) > len(files.all()):
for i in range(len(files.all()), len(files_data)):
MealFile.objects.create(
meal=instance,
owner=instance.owner,
file=files_data[i].get("file"),
)
# Else if files have been removed, delete MealFiles
elif len(files_data) < len(files.all()):
for i in range(len(files_data), len(files.all())):
files.all()[i].delete()
return instance
def get_owner_username(self, obj):
"""Returns the owning user's username
Args:
obj (Meal): Current Meal
Returns:
str: Username of owner
"""
return obj.owner.username
\ No newline at end of file
"""
Tests for the meals application.
"""
from django.test import TestCase
# Create your tests here.
from django.urls import path, include
from meals import views
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
# This is messy and should be refactored
urlpatterns = format_suffix_patterns(
[
path("", views.api_root),
path("api/meals/", views.MealList.as_view(), name="meal-list"),
path(
"api/meals/<int:pk>/",
views.MealDetail.as_view(),
name="meal-detail",
),
path(
"api/meal-files/",
views.MealFileList.as_view(),
name="meal-file-list",
),
path(
"api/meal-files/<int:pk>/",
views.MealFileDetail.as_view(),
name="mealfile-detail",
),
path("", include("users.urls")),
]
)
"""Contains views for the meals application. These are mostly class-based views.
"""
from rest_framework import generics, mixins
from rest_framework import permissions
from rest_framework.parsers import (
JSONParser,
)
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from django.db.models import Q
from rest_framework import filters
from meals.parsers import MultipartJsonParser
from meals.permissions import (
IsOwner,
IsOwnerOfMeal,
IsReadOnly,
)
from meals.mixins import CreateListModelMixin
from meals.models import Meal, MealFile
from meals.serializers import MealSerializer
from meals.serializers import MealFileSerializer
from django.core.exceptions import PermissionDenied
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.response import Response
import json
from collections import namedtuple
import base64, pickle
from django.core.signing import Signer
@api_view(["GET"])
def api_root(request, format=None):
return Response(
{
"users": reverse("user-list", request=request, format=format),
"meals": reverse("meal-list", request=request, format=format),
"meal-files": reverse(
"meal-file-list", request=request, format=format
),
}
)
class MealList(
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
):
"""Class defining the web response for the creation of a Meal, or displaying a list
of Meals
HTTP methods: GET, POST
"""
serializer_class = MealSerializer
permission_classes = [
permissions.IsAuthenticated
] # User must be authenticated to create/view meals
parser_classes = [
MultipartJsonParser,
JSONParser,
] # For parsing JSON and Multi-part requests
filter_backends = [filters.OrderingFilter]
ordering_fields = ["name", "date", "owner__username"]
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
def get_queryset(self):
qs = Meal.objects.none()
if self.request.user:
qs = Meal.objects.filter(Q(owner=self.request.user)).distinct()
return qs
class MealDetail(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView,
):
"""Class defining the web response for the details of an individual Meal.
HTTP methods: GET, PUT, DELETE
"""
queryset = Meal.objects.all()
serializer_class = MealSerializer
permission_classes = [
permissions.IsAuthenticated
& IsOwner
]
parser_classes = [MultipartJsonParser, JSONParser]
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class MealFileList(
mixins.ListModelMixin,
mixins.CreateModelMixin,
CreateListModelMixin,
generics.GenericAPIView,
):
queryset = MealFile.objects.all()
serializer_class = MealFileSerializer
permission_classes = [permissions.IsAuthenticated & IsOwnerOfMeal]
parser_classes = [MultipartJsonParser, JSONParser]
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
def get_queryset(self):
qs = MealFile.objects.none()
if self.request.user:
qs = MealFile.objects.filter(
Q(owner=self.request.user)).distinct()
return qs
class MealFileDetail(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView,
):
queryset = MealFile.objects.all()
serializer_class = MealFileSerializer
permission_classes = [
permissions.IsAuthenticated
& IsOwner
]
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
python-3.8.6
\ No newline at end of file
python-3.8.10
\ No newline at end of file
#import logging
import os
import dj_database_url
from django.test.runner import DiscoverRunner
MAX_CONN_AGE = 600
def settings(config, *, db_colors=False, databases=True, test_runner=True, staticfiles=True, allowed_hosts=True, logging=True, secret_key=True):
# Database configuration.
# TODO: support other database (e.g. TEAL, AMBER, etc, automatically.)
if databases:
# Integrity check.
if 'DATABASES' not in config:
config['DATABASES'] = {'default': None}
conn_max_age = config.get('CONN_MAX_AGE', MAX_CONN_AGE)
if db_colors:
# Support all Heroku databases.
# TODO: This appears to break TestRunner.
for (env, url) in os.environ.items():
if env.startswith('HEROKU_POSTGRESQL'):
db_color = env[len('HEROKU_POSTGRESQL_'):].split('_')[0]
#logger.info('Adding ${} to DATABASES Django setting ({}).'.format(env, db_color))
config['DATABASES'][db_color] = dj_database_url.parse(url, conn_max_age=conn_max_age, ssl_require=True)
if 'DATABASE_URL' in os.environ:
#logger.info('Adding $DATABASE_URL to default DATABASE Django setting.')
# Configure Django for DATABASE_URL environment variable.
config['DATABASES']['default'] = dj_database_url.config(conn_max_age=conn_max_age, ssl_require=True)
#logger.info('Adding $DATABASE_URL to TEST default DATABASE Django setting.')
# Enable test database if found in CI environment.
if 'CI' in os.environ:
config['DATABASES']['default']['TEST'] = config['DATABASES']['default']
#else:
#logger.info('$DATABASE_URL not found, falling back to previous settings!')
if test_runner:
# Enable test runner if found in CI environment.
if 'CI' in os.environ:
config['TEST_RUNNER'] = 'django_heroku.HerokuDiscoverRunner'
# Staticfiles configuration.
if staticfiles:
#logger.info('Applying Heroku Staticfiles configuration to Django settings.')
config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles')
config['STATIC_URL'] = '/static/'
# Ensure STATIC_ROOT exists.
os.makedirs(config['STATIC_ROOT'], exist_ok=True)
# Insert Whitenoise Middleware.
try:
config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES']))
except KeyError:
config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE']))
# Enable GZip.
config['STATICFILES_STORAGE'] = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
if allowed_hosts:
#logger.info('Applying Heroku ALLOWED_HOSTS configuration to Django settings.')
config['ALLOWED_HOSTS'] = ['*']
"""
if logging:
logger.info('Applying Heroku logging configuration to Django settings.')
config['LOGGING'] = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
'pathname=%(pathname)s lineno=%(lineno)s ' +
'funcname=%(funcName)s %(message)s'),
'datefmt': '%Y-%m-%d %H:%M:%S'
},
'simple': {
'format': '%(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'testlogger': {
'handlers': ['console'],
'level': 'INFO',
}
}
}
"""
# SECRET_KEY configuration.
if secret_key:
if 'SECRET_KEY' in os.environ:
#logger.info('Adding $SECRET_KEY to SECRET_KEY Django setting.')
# Set the Django setting from the environment variable.
config['SECRET_KEY'] = os.environ['SECRET_KEY']
......@@ -12,6 +12,8 @@ https://docs.djangoproject.com/en/3.1/ref/settings/
from pathlib import Path
import os
from .djangoHeroku import settings
# Get the GROUPID variable to accept connections from the application server and NGINX
......@@ -43,6 +45,7 @@ ALLOWED_HOSTS = [
"10." + groupid + ".0.4",
"molde.idi.ntnu.no",
"10.0.2.2",
# ADD HEROKU URL HERE
]
# Application definition
......@@ -56,6 +59,7 @@ INSTALLED_APPS = [
"django.contrib.staticfiles",
"rest_framework",
"workouts.apps.WorkoutsConfig",
"meals.apps.MealsConfig",
"users.apps.UsersConfig",
"comments.apps.CommentsConfig",
"corsheaders",
......@@ -95,12 +99,22 @@ WSGI_APPLICATION = "secfit.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
is_prod = os.environ.get("IS_HEROKU", None)
if is_prod:
settings(locals())
if 'DATABASE_URL' in os.environ:
import dj_database_url
print("\n\n\n\n\nHEI\n\n\n\n\n\n")
DATABASES = {'default': dj_database_url.config()}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
}
# CORS Policy
CORS_ORIGIN_ALLOW_ALL = (
......
......@@ -21,6 +21,7 @@ from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("workouts.urls")),
path("", include("meals.urls")),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
......