Skip to content

Instantly share code, notes, and snippets.

@postfalk
Last active September 1, 2017 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postfalk/2dcd2b49ae32d9ead109ccfba2f4de59 to your computer and use it in GitHub Desktop.
Save postfalk/2dcd2b49ae32d9ead109ccfba2f4de59 to your computer and use it in GitHub Desktop.
Minimum Django in one file
# This script is one of the smallest environments where Django models are
# fully functional.
# https://stackoverflow.com/questions/1297873/
# how-do-i-write-a-single-file-django-application
import os
import sys
from datetime import datetime
import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase
NAME = 'test'
def main():
class MyModel(models.Model):
applied_date = models.DateTimeField(null=True, blank=True)
modified_date = models.DateTimeField(null=True, blank=True)
@property
def applied(self):
if self.applied_date:
return self.applied_date > self.modified_date
return False
@applied.setter
def applied(self, value):
if value:
self.applied_date = datetime.now()
else:
self.modified_date = datetime.now()
self.save()
# SyncDB after model definition
syncdb(MyModel)
m = MyModel.objects.create(modified_date='2001-01-01')
m.applied = True
print MyModel.objects.count()
print MyModel.objects.all()[0].applied_date
assert MyModel.objects.all()[0].applied == True
def setup():
with open(NAME + '.db', 'w'):
pass
settings.configure(
DEBUG=True,
DATABASES={
DEFAULT_DB_ALIAS: {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': NAME + '.db'}},)
app_config = AppConfig(NAME, sys.modules['__main__'])
apps.populate([app_config])
django.setup()
original_new_func = ModelBase.__new__
@staticmethod
def patched_new(cls, name, bases, attrs):
if 'Meta' not in attrs:
class Meta:
app_label = NAME
attrs['Meta'] = Meta
return original_new_func(cls, name, bases, attrs)
ModelBase.__new__ = patched_new
def syncdb(model):
connection = connections[DEFAULT_DB_ALIAS]
with connection.schema_editor() as editor:
editor.create_model(model)
def teardown():
os.remove(NAME + '.db')
if __name__ == '__main__':
setup()
main()
teardown()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment