entity ident could be even simpler with flask + pymongo instead of django

This commit is contained in:
Marco Zeisler 2021-04-10 17:16:50 +02:00
parent 20bb74416e
commit 8f49d56ba9
26 changed files with 29 additions and 431 deletions

View File

@ -1,6 +0,0 @@
venv
*.pyc
staticfiles
.env
*.sqlite3
homeschooling_be_app.egg-info

View File

@ -1,19 +0,0 @@
FROM python:3.8-slim
ENV PYTHONUNBUFFERED 1
RUN apt-get update
RUN apt-get install -y build-essential gcc
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN python -m pip install --upgrade pip
ENV PATH="/opt/venv/bin:$PATH"
RUN mkdir /code
WORKDIR /code
COPY setup.py /code/
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

View File

@ -1,20 +0,0 @@
# AIC Django Middleware
## Tips
* use Jetbrains Pycharm IDE
* create and use a virtual environment
## Setup
$ cd ./middleware
$ pip install -r requirements.txt
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser
$ python mangge.py runserver
## ERROR handling
<em>Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"</em>
<br>Install missing deps https://visualstudio.microsoft.com/visual-cpp-build-tools/

View File

@ -1,3 +0,0 @@
from django.contrib import admin
# Register your models here.

View File

@ -1,5 +0,0 @@
from django.apps import AppConfig
class AppBeConfig(AppConfig):
name = 'app_be'

View File

@ -1,3 +0,0 @@
from django.db import models
# Create your models here.

View File

@ -1,17 +0,0 @@
from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.sessions import SessionMiddlewareStack
from django.core.asgi import get_asgi_application
from .views.ws_api import CustomConsumer
application = ProtocolTypeRouter({
# Django's ASGI application to handle traditional HTTP requests
"http": get_asgi_application(),
# WebSocket send handler
"websocket": SessionMiddlewareStack(URLRouter([
url(r"^test-ws-endpoint/$", CustomConsumer.as_asgi()),
]))
})

View File

@ -1,3 +0,0 @@
from rest_framework import serializers
# add serializer here

View File

@ -1,221 +0,0 @@
"""
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import datetime
import os
# set the websocket routing module location here
ASGI_APPLICATION = 'app_be.routing.application'
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "{{ secret_key }}"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'app_be',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
"""
default permission and authentication classes
sets the standard privileges needed to access an api
for now, no classes necessary and therefore disabled!
"""
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated', # last comma is MANDATORY
[]
),
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # last comma is MANDATORY
[]
)
}
# configuration of jason web token authentication
JWT_AUTH = {
'JWT_VERIFY': True,
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_ALLOW_REFRESH': True,
# 60 minutes
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600),
# debug 10 seconds
# 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=10),
}
if DEBUG:
# install corsheaders to enable to run
# the rest (django) an gui (angular) server on two different ports
INSTALLED_APPS.append("corsheaders")
MIDDLEWARE.append('corsheaders.middleware.CorsMiddleware')
MIDDLEWARE.append('django.middleware.common.BrokenLinkEmailsMiddleware')
MIDDLEWARE.append('django.middleware.common.CommonMiddleware')
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = [
"*"
]
else:
ALLOWED_HOSTS = [
"*",
"127.0.0.1"
]
ROOT_URLCONF = 'app_be.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',
],
'debug': DEBUG,
},
},
]
WSGI_APPLICATION = 'app_be.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Change 'default' database configuration with $DATABASE_URL.
# DATABASES['default'].update(dj_database_url.config(conn_max_age=500, ssl_require=True))
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{asctime} - {levelname}: {message} ({pathname}:{lineno})',
'style': '{',
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'logfile': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': BASE_DIR + "/../logfile",
'formatter': 'verbose'
},
},
'loggers': {
'rdg': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
'rdg_rest': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
'rdg_angular': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
},
'root': {
'level': 'DEBUG',
'handlers': [] # pass a empty list to avoid duplicte log entries
},
}
# increase the maximum upload size of files
DATA_UPLOAD_MAX_MEMORY_SIZE = 104857600

View File

@ -1,15 +0,0 @@
from django.test import TestCase
# Create your tests here.
from rest_framework import status
from rest_framework.test import APITestCase
class AccountTests(APITestCase):
def test_create_account(self):
"""
Ensure we can create a new account object.
"""
url = '/test/'
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)

View File

@ -1,30 +0,0 @@
"""{{ project_name }} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from rest_framework.routers import DefaultRouter
from app_be.views.rest_api import TestApiClass
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^test/', TestApiClass.test_api),
]
router = DefaultRouter()
urlpatterns.extend(router.urls)

View File

@ -1,15 +0,0 @@
import logging
from django.http import JsonResponse
from rest_framework.decorators import api_view
logger = logging.getLogger(__name__)
class TestApiClass:
@staticmethod
@api_view(['GET'])
def test_api(request):
logger.debug('Test api call: {}'.format(request))
return JsonResponse({'Result': 'success'}, safe=False)

View File

@ -1,18 +0,0 @@
import logging
from channels.generic.websocket import WebsocketConsumer
logger = logging.getLogger(__name__)
class CustomConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def receive(self, text_data=None, bytes_data=None):
self.send('1. response: {}'.format(text_data))
self.send('2. response: {}'.format(text_data))
def disconnect(self, code):
pass

View File

@ -1,16 +0,0 @@
"""
WSGI config for {{ project_name }} 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/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ app_be }}.settings")
application = get_wsgi_application()

View File

@ -0,0 +1,27 @@
from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(app)
mongo.db.test.save({'_id': 0, 'foo': 'bar'})
mongo.db.test.save({'_id': 1, 'suu': 'sar'})
@app.route("/")
def home_page():
test_results = mongo.db.test.find()
results = []
try:
while True:
result = test_results.next()
results.append(result)
except StopIteration:
pass
return str(results)
if __name__ == '__main__':
app.run()

View File

@ -1,15 +0,0 @@
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_be.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
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?"
)
execute_from_command_line(sys.argv)

View File

@ -1,11 +1,2 @@
# install setup.py in dev mode
-e .
Django==3.2
djangorestframework==3.12.4
djangorestframework-jwt==1.11.0
django-cors-headers==3.7.0
channels==3.0.3
channels_redis==3.2.0
whitenoise==5.2.0
pika
flask
Flask-PyMongo

View File

@ -1,14 +0,0 @@
import os
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='homeschooling-be-app',
version='0.0.0',
packages=find_packages(),
include_package_data=True,
license='BSD License', # example license
description='DESCRIPTION'
)