Logan is a toolkit for building standalone Django applications

Related tags

Django logan
Overview

Logan

Logan is a toolkit for running standalone Django applications. It provides you with tools to create a CLI runner, manage settings, and the ability to bootstrap the process.

Let's take the Sentry project for example, it specifies that it wants to use logan for running the application:

setup(
    name='sentry',
    install_requires=['logan'],
    entry_points={
        'console_scripts': [
            'sentry = logan.runner:run_app',
        ],
    },
)

It then defines several Django Management Commands as part of it's project, via the standard structure of sentry/management/commands/.py.

Now when we call sentry. it's actually piping that to the logan runner. Logan simply loads the predefined settings file (which defaults to PROJECT_CONF, or ~/.project/project.conf.py) and then passes the command off to Django's internal representation of django-admin.py. In this case, PROJECT is determined by the caller of logan.runner, which is "sentry". If it were "foo-bar", PROJECT would be FOO_BAR, and "project" would still be "foo-bar".

In most cases, you're also going to want to provide a default configuration to inherit from, as well as a template to generate for the user if their configuration does not exist.

To do this, within our sentry project we create a simple script, lets call put it in sentry/logan_runner.py:

from logan.runner import run_app

def generate_settings():
    """
    This command is run when ``default_path`` doesn't exist, or ``init`` is
    run and returns a string representing the default data to put into their
    settings file.
    """
    return ""

def main():
    run_app(
        project='sentry',
        default_config_path='~/.sentry/',
        default_settings='sentry.conf.defaults',
        settings_initializer='sentry.logan_runner.generate_settings',
        settings_envvar='SENTRY_CONF',
    )

if __name__ == '__main__':
    main()

We'd then slightly adjust our entry point in our setup.py:

setup(
    name='sentry',
    install_requires=['logan'],
    entry_points={
        'console_scripts': [
            'sentry = sentry.logan_runner:main',
        ],
    },
)

You'll now be able to access the sentry command as if it were django-admin.py. Even better, it will be configurable via an arbitrary settings file, and inherit any default settings you've specified:

# Note: run_gunicorn is provided by the gunicorn package
sentry run_gunicorn 0.0.0.0:8000 -w 3

Extra Applications

A need might come up to allow the user to register additional settings. These will automatically apply based on keynames prefixed with EXTRA_ assuming the base key (the latter part of the setting name) is of type list or tuple.

For example, to register additional INSTALLED_APPS, you would simply specify this in your custom (user) configuration:

EXTRA_INSTALLED_APPS = (
    'foo.bar',
)

This will ensure your default setting's INSTALLED_APPS do not have to be modified, and the user can specify additional apps with ease.

If you wish to disable this functionality, simply pass allow_extra=False to run_app:

run_app(
    # ...,
    allow_extras=False,
)
Comments
  • logan and celery

    logan and celery

    i have a problem running celery from the app "binary" after i installed it with logan.

    as a test, i created a django project. runserver works fine. i can start the runserver and celery using

    python manage.py runserver
    python manage.py celeryd -E -B
    

    after i installed the project, i am be able to start it.

    eukalypse_now runserver
    

    this is VERY awesome. however, i can not start celery

    eukalypse_now celeryd -E -B
    ...
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/desch/.virtualenvs/empty1/local/lib/python2.7/site-packages/billiard-2.7.3.18-py2.7-linux-x86_64.egg/billiard/forking.py", line 502, in main
        prepare(preparation_data)
      File "/home/desch/.virtualenvs/empty1/local/lib/python2.7/site-packages/billiard-2.7.3.18-py2.7-linux-x86_64.egg/billiard/forking.py", line 642, in prepare
        file, path_name, etc = imp.find_module(main_name, dirs)
    ImportError: No module named eukalypse_now
    
    

    i am not sure if this is a problem in billiard handels something or in how logan created the binary. billiard only looks for the module in the ./bin path of the project in the virtualenv.

    any idea?

    opened by kinkerl 6
  • Python 3 compatibility

    Python 3 compatibility

    I changed a few lines to make logan python3 compatible:

    1. "print " --> "print("
    2. "except Exception, e" --> "except Exception as e"
    3. "raise ConfigurationError unicode(e), exc_info[2] " --> "raise ConfigurationError(unicode(e), exc_info[2])"
    4. iteritems --> items
    5. execfile is gone, I used http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0

    Also, I removed unittest2 because I couldn't get it to run in python3.

    Do you like it? What can I improve?

    opened by dmr 5
  • logan.importer.ConfigurationError: (u'cannot import name _uuid_generate_random

    logan.importer.ConfigurationError: (u'cannot import name _uuid_generate_random

    raise ConfigurationError(unicode(e), exc_info[2])", "logan.importer.ConfigurationError: (u'cannot import name _uuid_generate_random', <traceback object at 0x7f4039597a70>)"]

    At python 2.7 when trying to install sentry from ansible

    opened by pypetey 3
  • Is this project dead?

    Is this project dead?

    I started investigating some faults, wanted to fix, then I came here and saw I had already investigated this before and done a pull request all the way back in May.

    This has not been merged and a new release has not been put up on pypi.

    Is this project dead? Why is that so? Do you want someone else to take over maintainership? I could do that, though I'd mostly maintain, not develop.

    Hope everything is OK and there's not worse reasons for project being stale.

    opened by odinho 3
  • Django template / Cookiecutter template for bootstrapping with logan

    Django template / Cookiecutter template for bootstrapping with logan

    I really like the way sentry is structured and I was wondering if we could create a Django template or a Cookiecutter template where the project structure could be like sentry and packaging/distribution of the project becomes really easy and the project itself is an app that is standalone. Would love to hear your thoughts.

    opened by sumansai14 2
  • Django 1.9 fail

    Django 1.9 fail

    File "/usr/local/lib/python2.7/dist-packages/logan/importer.py", line 24, in <module>
        from django.utils.importlib import import_module
    ImportError: No module named importlib
    

    From Django sources:

    warnings.warn("django.utils.importlib will be removed in Django 1.9.",
        RemovedInDjango19Warning, stacklevel=2)
    
    opened by pashinin 2
  • additional method similar to generate_settings?

    additional method similar to generate_settings?

    Hi everyone,

    I use logan for a project and logan generates a projectname.conf.py, cool. This behavior worked for us when the project was small. But now we have many more scenarios and I'd like to use logan to generate a "working directory" for me with the following content:

    projectname.conf.py
    nginx.conf
    gunicorn.conf.py
    Procfile
    

    To do this I'd add another method like logan.settings.create_default_settings which could be executed after config was generated and is optional. Before I start implementing this I'd like to get some opinions.

    Is this a good idea? How do you solve this problem in your projects? Is there a roadmap for logan?

    opened by dmr 2
  • Release a new version?

    Release a new version?

    The 0.5.10 build on pypi seems to have some errors in Python 3. It looks like this was fixed in #16, but a new version hasn't been released since then.

    Any chance you could bump the version, so that we don't have to install from git on Python 3?

    opened by csinchok 1
  • Logan on Pypi is outdated

    Logan on Pypi is outdated

    Hi!

    I'm working on a FreeBSD port of Logan and noticed that the version currently rolled out through Cheeseshop (https://pypi.python.org/pypi/logan) depends on Django <1.5 and was released on 2013-09-30.

    Could you please roll out a new version? Packaging PyPi libraries is much more convenient than depending on Github commit hashes (as there's no recent tag newer than 0.5.9.1).

    Best, xmj

    opened by xmj 1
  • Problems with test requirements

    Problems with test requirements

    Your tests requirements require ''django>=1.2.5,< 1.5'', but sentry, which uses this package requires Django>=1.5.5. Can you do something like 'django>=1.2.5,<=1.5.5', so we can run automated tests for both packages? Thanks!

    opened by offlinehacker 1
  • License question (name of product)

    License question (name of product)

    Hi, my name is lionel and I'm also a developer. I've noticed that you have the name "logan" for your project and I want to ask you if it's matter that one of my cli python tool project (https://github.com/first-developer/logan) is a also named "Logan" according to licensing. Thanks in advance for your answer.

    Bests Lionel

    opened by first-developer 1
  • Append or insert settings.

    Append or insert settings.

    Sometimes I need to add a middleware on the top or near the top. An example is the Debug Toolbar.

    The order of MIDDLEWARE_CLASSES is important. You should include the Debug Toolbar 
    middleware as early as possible in the list. However, it must come after any other middleware that 
    encodes the response’s content, such as GZipMiddleware.
    

    It's possible with logan?

    opened by teserak 0
  • Django 1.8 and py.test

    Django 1.8 and py.test

    Hi everybody,

    logan works fine with django 1.8 for our project but we have one problem: pytest.

    I'm not sure if this is a problem of pytest but I wanted to ask if anybody is using the combination of py.test and logan and django 1.8. Since the update we have an issue when we run the tests:

    ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
    

    We managed to integrate logan into pytest by defining a conftest.py with the following content:

    from logan.runner import configure_app
    from myproject.logan_runner import get_logan_kw
    configure_app(**get_logan_kw())
    

    But with the new version of either django or pytest or pytest-django something is wrong with the import ordering I guess.

    I'm just curious if anybody experienced the same things and has a solution. Again, logan might work fine here so feel free to resolve this issue :)

    opened by dmr 0
  • "myapp" could return "django-admin.py help" output

    When I run

    $ myapp
    

    I see

    usage: myapp [--config=/path/to/settings.py] [command] [options]
    

    But when I run

    $ django-admin.py
    

    I see

    Usage: django-admin subcommand [options] [args]
    
    Options:
      -v VERBOSITY, --verbosity=VERBOSITY
                            Verbosity level; 0=minimal output, 1=normal output,
                            2=verbose output, 3=very verbose output
      --settings=SETTINGS   The Python path to a settings module, e.g.
                            "myproject.settings.main". If this isn't provided, the
                            DJANGO_SETTINGS_MODULE environment variable will be
                            used.
      --pythonpath=PYTHONPATH
    ....
    

    --> How do you guys feel about putting a small logan-header on top of the help message and run the help command by default?

    opened by dmr 1
  • settings_envvar and OptionParser behave differently

    settings_envvar and OptionParser behave differently

    With

    def main(): run_app(settings_initializer='MY_CONF', ...)
    

    When I call

    MY_CONF="my.py" my test --stop
    

    everything works fine but with

    my --config=my.py test --stop
    

    I get a no option "--stop" error. (I'm using the nose test runner)

    Is that behavior expected?

    Can the --config option be removed? The settings_envvar could be assumed to be there on start and that would also provide another benefit: When I initialize a new project I had to look into the code until I realized that "my init" required another parameter: the default config path --> If the settings_envvar would be required the error would be more clear I think.

    opened by dmr 1
  • configure_app bug

    configure_app bug

    Project argument is optional for configure_app.

    And then project=None scripts crashed, after line 63.

    https://github.com/dcramer/logan/blob/master/logan/runner.py#L63

    opened by Lispython 0
  • --setting_module Option

    --setting_module Option

    I have a little library here at work (configtools) that helps me mange Django settings in config files and making a module kind of act like django.conf.settings by pulling config from some other preconfigured module (considering open-sourcing it, but that's beside the point). It makes use of something like sys.modules[name] to get access to the current module object at import time. Unfortunately, the way Logan handles the --config option and loading the file breaks that. This new option takes a dotted module name that gets passed almost directly to import fixing my problem.

    I'd almost recommend replacing --config with --settings_module as, with my experience in the python community, most always you refer to a module or function in it's dotted form (e.g. package.module or package.module:function) when passing them as arguments to command line tools (see DJANGO_SETTINGS_MODULE, how you launch an app with gunicorn, etc...). This keeps backwards compatibility with --config and prevents both from being passed at the same time.

    opened by 198d 4
Owner
David Cramer
founder/cto @getsentry
David Cramer
A Django app to initialize Sentry client for your Django applications

Dj_sentry This Django application intialize Sentry SDK to your Django application. How to install You can install this packaging by using: pip install

Gandi 1 Dec 9, 2021
A standalone package to scrape financial data from listed Vietnamese companies via Vietstock

Scrape Financial Data of Vietnamese Listed Companies - Version 2 A standalone package to scrape financial data from listed Vietnamese companies via Vi

Viet Anh (Vincent) Tran 45 Nov 16, 2022
Django app for building dashboards using raw SQL queries

django-sql-dashboard Django app for building dashboards using raw SQL queries Brings a useful subset of Datasette to Django. Currently only works with

Simon Willison 383 Jan 6, 2023
Learn Python and the Django Framework by building a e-commerce website

The Django-Ecommerce is an open-source project initiative and tutorial series built with Python and the Django Framework.

Very Academy 275 Jan 8, 2023
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

Fast to learn, fast to code, fast to run Django Ninja - Fast Django REST Framework Django Ninja is a web framework for building APIs with Django and P

Vitaliy Kucheryaviy 3.8k Jan 1, 2023
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Marco Bonetti 909 Dec 26, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 5, 2022
A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Yunbo Shi 8 Oct 28, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 8, 2021
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot ?? Features A Django stater project with fully basic requirements for a production-ready

null 8 Jun 27, 2022
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022