Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Django as a microframework

License

NotificationsYou must be signed in to change notification settings

maxpoletaev/django-micro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

85 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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.

What works

Installation

$ pip install django-micro

Quick start

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.

Compatibility

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

Run and deployment

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()

Configuration

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())

Views and routes

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.

Models and migrations

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 ;)

Management commands

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 ;)

Custom template tags

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.

Testing

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__

Admin interface

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)

Credits

Django Micro is based on ideas from the following projects:

About

Django as a microframework

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors6


[8]ページ先頭

©2009-2025 Movatter.jp