Skip to content

Instantly share code, notes, and snippets.

@kingbuzzman
Last active October 7, 2021 10:51
Show Gist options
  • Save kingbuzzman/0197da03c52ae9a798c99d0cf58c758c to your computer and use it in GitHub Desktop.
Save kingbuzzman/0197da03c52ae9a798c99d0cf58c758c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Stolen from: https://mlvin.xyz/django-single-file-project.html
import datetime
import inspect
import os
import sys
from types import ModuleType
import django
from django.conf import settings
from django.urls import include, path, reverse
from django.apps import apps, AppConfig
from django.http import HttpResponse
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# The current name of the file, which will be the name of our app
APP_LABEL, _ = os.path.splitext(os.path.basename(os.path.abspath(__file__)))
# Migrations folder need to be created, and django needs to be told where it is
APP_MIGRATION_MODULE = '%s_migrations' % APP_LABEL
APP_MIGRATION_PATH = os.path.join(BASE_DIR, APP_MIGRATION_MODULE)
# Create the folder and a __init__.py if they don't exist
if not os.path.exists(APP_MIGRATION_PATH):
os.makedirs(APP_MIGRATION_PATH)
open(os.path.join(APP_MIGRATION_PATH, '__init__.py'), 'w').close()
# Hack to trick Django into thinking this file is actually a package
sys.modules[APP_LABEL] = sys.modules[__name__]
sys.modules[APP_LABEL].__path__ = [os.path.abspath(__file__)]
settings.configure(
DEBUG=True,
ROOT_URLCONF='%s.urls' % APP_LABEL,
MIDDLEWARE=(),
INSTALLED_APPS=['django.contrib.contenttypes', 'django.contrib.auth', APP_LABEL],
MIGRATION_MODULES={APP_LABEL: APP_MIGRATION_MODULE},
SITE_ID=1,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
},
LOGGING={},
STATIC_URL='/static/'
)
django.setup()
# Setup the AppConfig so we don't have to add the app_label to all our models
def get_containing_app_config(module):
if module == '__main__':
return apps.get_app_config(APP_LABEL)
return apps._get_containing_app_config(module)
apps._get_containing_app_config = apps.get_containing_app_config
apps.get_containing_app_config = get_containing_app_config
# Your code below this line
# ##############################################################################
from django.test import TestCase # noqa: E402 isort:skip
from django import db # noqa: E402 isort:skip
from django.contrib import auth
import factory
from faker import Faker
import datetime
fake = Faker()
urlpatterns = []
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = auth.models.User
django_get_or_create = ('username',)
first_name = fake.first_name()
last_name = fake.last_name()
email = factory.LazyAttribute(lambda obj: "{}.{}@gmail.com".format(obj.last_name, obj.first_name).lower())
username = factory.Sequence(lambda n: 'user' + str(n))
@classmethod
def create_user_login_data(cls, year=2000):
"""
Creates 3 users for every day in the year and sets the `last_login` to said date.
"""
next_year = year
for month in range(1, 12 + 1):
next_month = month + 1
if next_month > 12:
next_month = 1
next_year += 1
num_days_in_month = (datetime.date(next_year, next_month, 1) - datetime.date(year, month, 1)).days
for day in range(1, num_days_in_month + 1):
cls.create_batch(3, last_login=datetime.datetime(year, month, day))
class SimpleTestCase(TestCase):
def setUp(self):
UserFactory.create_user_login_data()
def test_count(self):
# The year 2000 was a leap year and there was one more day, (365 + 1) * 3 = 1098
self.assertEqual(auth.models.User.objects.count(), 1098)
def test_month_grouping(self):
start_date = datetime.datetime.strptime('2000-5-5' , '%Y-%m-%d')
month_end_date = datetime.datetime.strptime('2000-6-5' , '%Y-%m-%d')
qs = (auth.models.User.objects.values('last_login__month', 'last_login__year')
.annotate(data=db.models.Count('*'))
.order_by('last_login__year', 'last_login__month'))
qs = qs.filter(last_login__range=[start_date, month_end_date])
result = []
for item in qs:
result.append({
'month': datetime.date(1900, item['last_login__month'] , 1).strftime('%B'),
'data': item['data']
})
self.assertEqual(result, [{'month': 'May', 'data': 81}, {'month': 'June', 'data': 15}])
# Your code above this line
# ##############################################################################
# Used so you can do 'from <name of file>.models import *'
models_module = ModuleType('%s.models' % (APP_LABEL))
tests_module = ModuleType('%s.tests' % (APP_LABEL))
urls_module = ModuleType('%s.urls' % (APP_LABEL))
urls_module.urlpatterns = urlpatterns
for variable_name, value in list(locals().items()):
# We are only interested in models
if inspect.isclass(value) and issubclass(value, db.models.Model):
setattr(models_module, variable_name, value)
# We are only interested in tests
if inspect.isclass(value) and issubclass(value, TestCase):
setattr(tests_module, variable_name, value)
# Setup the fake modules
sys.modules[models_module.__name__] = models_module
sys.modules[tests_module.__name__] = tests_module
sys.modules[urls_module.__name__] = urls_module
sys.modules[APP_LABEL].models = models_module
sys.modules[APP_LABEL].tests = tests_module
sys.modules[APP_LABEL].urls = urls_module
if __name__ == "__main__":
# Hack to fix tests
argv = [arg for arg in sys.argv if not arg.startswith('-')]
if len(argv) == 2 and argv[1] == 'test':
sys.argv.append(APP_LABEL)
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
else:
from django.core.wsgi import get_wsgi_application
get_wsgi_application()
@kingbuzzman
Copy link
Author

In order to run the code above run the following:

curl -L https://gist.githubusercontent.com/kingbuzzman/0197da03c52ae9a798c99d0cf58c758c/raw/month_data.py > month_data.py
pip install django==3.1 factory-boy==3.2.0
python month_data.py test

If you want the REAL copy and paste version:

docker run -it --rm python:3.7 bash -c '
curl -L https://gist.githubusercontent.com/kingbuzzman/0197da03c52ae9a798c99d0cf58c758c/raw/month_data.py > month_data.py
pip install django==3.1 factory-boy==3.2.0
python month_data.py test
'

Answers stackoverflow question: https://stackoverflow.com/questions/69478156/calculate-monthwise-data-in-django-python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment