- Notifications
You must be signed in to change notification settings - Fork21
maxpoletaev/django-micro
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Django Micro is lightweight wrapper around Django that turns it to the microframework for writing small applications in a single file.
tl;dr: See theexample_ of full-featured application.
- Configuration
- Views and routes
- Models and migrations
- Management commands
- Custom template tags
- Testing
- Admin interface
- Third party apps
$ pip install django-micro
Createapp.py file with following content.
fromdjango_microimportconfigure,route,runfromdjango.httpimportHttpResponseDEBUG=Trueconfigure(locals())@route('',name='homepage')defhomepage(request):name=request.GET.get('name','World')returnHttpResponse('Hello, {}!'.format(name))application=run()
Run the application.
$ python app.py runserver
Note: Parent directory of theapp.py file must have a valid python module name. Under the hood, Micro adds that directory toINSTALLED_APPS and uses it as a regular Django application.
The latest relase of django-micro supports only the latest stable release of Django. This is the only way to keep codebase of django-micro clean, without hacks for different versions of Django.
- Django version: >=2.1
- Python version: >=3.4
On the localhost the application runs with the built-inrunserver command and deploys as a standard WSGI application.
$ python app.py runserver$ gunicorn example.app --bind localhost:8000$ uwsgi --module example.app --http localhost:8000
This behaviour is provided by the single string:application = run() which actually just a shortcut for the following code.
if__name__=='__main__':fromdjango.core.managementimportexecute_from_command_lineexecute_from_command_line(sys.argv)else:fromdjango.core.wsgiimportget_wsgi_applicationapplication=get_wsgi_application()
The call of theconfigure function must be placed at the top of your application above the definition of views, models, and imports of other modules. It may violate PEP8, but this is the only way to make it works. You can’t define models or import models from another application until Django is configured.
I recommend to define all the configuration in the global namespace and callconfigure withlocals() argument. Don’t worry, configure takes onlyUPPERCASE variables.
fromdjango_microimportconfigureDEBUG=Trueconfigure(locals())
Routing is wrapped in a single functionroute. You can use it as a decorator.
fromdjango_microimportroute@route('blog/<int:year>/',name='year_archive')defyear_archive(request,year):returnHttpResponse('hello')
Or as a regular function.
defyear_archive(request):returnHttpResponse('hello')route('blog/<int:year>/',year_archive,name='year_archive')
Alsoroute may be used with class-based views.
@route('blog/<int:year>/',name='year_archive')classYearArchiveView(View):defget(request,year):returnHttpResponse('hello')# or directlyroute('blog/<int:year>/',YearArchiveView.as_view(),name='year_archive')
Micro uses the new simplified routing syntax which was introduced in Django 2.0. But if you’d like to use the regex-based routing syntax, just addregex=True to the decorator.
@route(r'^articles/(?P<year>[0-9]{4})/$',regex=True)defyear_archive(request,year):returnHttpResponse('hello')
You always can access theurlpatterns for the use low-level API.
fromdjango.urlsimportpathimportdjango_microasmicromicro.urlpatterns+= [path('',homepage,name='homepage'),]
Note: You can include third-party apps into Micro’surlpatterns, but currently can’t use Micro as a third-party app. Micro is a singleton, and you can’t create more that one instance of it.
Micro works well with models and migrations. Just define model in yourapp.py file. If you need migrations, createmigrations directory next to theapp.py and callpython app.py makemigrations.
blog├── __init__.py├── app.py└── migrations ├── __init__.py └── 0001_initial.py
fromdjango.dbimportmodelsclassPost(models.Model):title=models.CharField(max_length=255)classMeta:app_label='blog'
Note: You always need to setapp_label attribute inMeta of your models. For example, if application placed inblog/app.py, app_label should beblog.
For gettingapp_label you can useget_app_label shortcut.
fromdjango_microimportget_app_labelclassMeta:app_label=get_app_label()
You also can place models separately inmodels.py file. In this caseapp_label is not required, but this is not a micro-way ;)
Now you can create any management command without creating a file inyourapp/management/commands. Just defne command class in yourapp.py and wrap it to@command decorator.
fromdjango.core.management.baseimportBaseCommandfromdjango_microimportcommand@command('print_hello')classPrintHelloCommand(BaseCommand):defhandle(self,*args,**options):self.stdout.write('Hello, Django!')
You also can create function-based commands.
fromdjango_microimportcommand@commanddefprint_hello(cmd,**options):cmd.stdout.write('Hello, Django!')
Unfortunately, thecommand decorator uses a few dirty hacks for command registration. But everything works fine if you don’t think about it ;)
Usetemplate for register template tags. It works same as aregister object in tag library file.
fromdjango_microimporttemplate@template.simple_tagdefprint_hello(name):return'Hello, {}!'@template.filterdefremove_spaces(value):returnvalue.replace(' ','')
You don’t need to use theload tag. All template tags are global.
No magick. Use built-in test cases.
fromdjango.testimportTestCaseclassTestIndexView(TestCase):deftest_success(self):response=self.client.get('/')self.assertEqual(response.status_code,200)
To run tests which defined in app.py use the following command:
$ python app.py test __main__
Django-admin requires lots of dependencies in apps and middlewares. We’ve realized that it’s not a simple way to add a huge list of apps to your config just to use the admin interface. So we added a shortcutdjango_admin=True to theconfigure function that automatically includes all the needed dependencies.
fromdjango.contribimportadminfromdjango_microimportconfigureconfigure(locals(),django_admin=True)classPost(models.Model):title=models.CharField(max_length=255)content=models.TextField(blank=True)create_date=models.DateTimeField(auto_now_add=True)classMeta:app_label=get_app_label()ordering= ('-create_date',)@admin.register(Post)classPostAdmin(admin.ModelAdmin):passroute('admin/',admin.site.urls)
Django Micro is based on ideas from the following projects:
About
Django as a microframework
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors6
Uh oh!
There was an error while loading.Please reload this page.