Use only some parts of Django?
Asked Answered
I

7

42

I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.

Specifically, I want to use:

  • The models and database abstraction
  • The caching API, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.

I would not use:

  • Templating
  • urlconfigs

Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.

Can this work?

My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.

Introduce answered 19/11, 2008 at 17:14 Comment(2)
You might check out peewee: github.com/coleifer/peewee -- its just an ORM, lightweight, and should be familiar to Django usersReprography
Not to insult coleifer here, but beware that the documentation for peewee is significantly less detailed than for Django, which may present a challenge if you're unfamiliar with some concepts.Tarp
N
48

I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called djangosettings.py and insert the necessary configuration, for example:

DATABASE_ENGINE   = 'oracle'
DATABASE_HOST     = 'localhost'
DATABASE_NAME     = 'ORCL'
DATABASE_USER     = 'scott' 
DATABASE_PASSWORD = 'tiger'

Then in your regular Python code, do

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings"

before you import any Django modules. This will let you use Django's object/db mappings without actually having a Django project, so you can use it for standalone scripts or other web applications or whatever you want.

As for caching, if you don't want to use Django then you should probably decide what you are using and go from there. I recommend using CherryPy, which doesn't use Django-style regular expression URL mapping, but instead automatically maps URLs to functions based on the function names. There's an example right at the top of the CherryPy home page: http://cherrypy.org/

CherryPy has its own caching system, so you can accomplish exactly the same thing as what Django does but without needing to use Django's urlconfig system.

Nussbaum answered 19/11, 2008 at 18:17 Comment(5)
Also see docs.djangoproject.com/en/dev/topics/settings/… for working without a settings file in the first place.Kenyon
That's definitely a useful link, although I still prefer keeping my settings separate since I tend to use a bunch of them, and so I find it cleaner to put them all in a separate file.Nussbaum
This will raise error No module named py. You have to put there the name of the module not the name of the file. So os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings" will do it.Nne
@LazyDave: Good catch! I've editing my answer to fix the code.Nussbaum
@EliCourtwright What about using django-admin and specifically makemigrations with a standalone app?Afroasian
C
13

Django, being a web framework, is extremely efficient at creating websites. However, it's also equally well-suited to tackling problems off the web. This is the loose coupling that the project prides itself on. Nothing stops you from installing a complete version of Django, and just using what you need. As a rule, very few components of Django make broad assumptions about their usage.

Specifically:

  • Django models don't know anything about HTML or HTTP.
  • Templates don't know anything about HTML or HTTP.
  • The cache system can be used to store anything that can be pickled.

One of the main things you'll face when trying to use Django without a web server is setting up the environment properly. The ORM and cache system still need to be configured in settings.py. There are docs on using django without a settings module that you may find useful.

Comedic answered 20/11, 2008 at 4:46 Comment(1)
Saying "This is the loose coupling that the project prides itself on" and "One of the main things you'll face when trying to use Django without a web server is setting up the environment properly" in the same answer seems like a bit of a contradiction.Afroasian
L
13

Django ORM Standalone

I've created a template Django project that allows you to do just that.

https://github.com/dancaron/Django-ORM

Just follow the instructions and you can write standalone python files that utilize Django's database functionality, without having to use urlconf, views, etc.

Lucrece answered 28/5, 2012 at 20:4 Comment(3)
This was very useful, thanks for creating it. Needed a little hacking of sys.path, and the exception handling hid some module loading errors, but made it really easy.Selfsown
Any chance you can add a license to that?Stratocracy
@Stratocracy MIT license added.Lucrece
D
2

There are of course other projects out there that specifically implement single parts of django. TurboGears for example is a collection of several projects that can work by themselves and together form a complete web development framework.

For the db abstraction SQLAlchemy comes to mind.

Regarding the caching part: I'm not aware of any standalone project that implements a generic caching facility.

On the other hand, it should be fairly easy to implement your own caching, for example by using pickles. Have a look at this recipe for a decorator for ideas and google for "memoize".

Also keep in mind that your database has its own caching mechanism, so maybe you don't even need to concern yourself with the details.

Displace answered 19/11, 2008 at 17:23 Comment(0)
G
2

I tend to prefer a mix-and-match approach to using Python for web programming. :-)

I don't have a lot of experience with Django, but I'd recommend giving sqlalchemy a look for the database stuff. It works well with others and gives you several potential layers of abstraction (so you can go with something basic or tweak the hell out of it if you want). Plus, you'll already be somewhat familiar with it if you've ever used hibernate/nhibernate.

My favorite part is that it has a lot of options for databases to connect to (most notably SQL Server, which django doesn't have built in last time I checked).

With that said, I'm told that with Django, it's pretty easy to decouple functionality (but never done so myself).

Gibbsite answered 19/11, 2008 at 17:24 Comment(0)
G
1

I've shared an example of solution, which prevents Python Path manipulation inside code:

https://github.com/askalyuk/django-orm-standalone

It contains a standalone data access package, a separated simple Django site and a unit test.

Goatsbeard answered 21/1, 2013 at 1:42 Comment(0)
S
1

I found KeyboardInterrupt's answer but it was answered in 2009 and I failed to run it in Django 1.8.For recent Django 1.8, You can have a look at this, in which some parts come from KeyboardInterrupt's answer.

The folder structure is:

.
├── myApp
│   ├── __init__.py
│   └── models.py
└── my_manage.py

myApp is a module, contains an empty __init__.py and models.py.

There is an example model class in models.py: from django.db import models

class MyModel(models.Model):
     field = models.CharField(max_length=255)

my_manage.py contains django database, installed_app settings and acts as django offical manage.py, so you can:

python my_manage.py sql myApp
python my_manage.py migrate
......

The codes in my_manage.py are: from django.conf import settings

db_conf = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_database_name',
        'USER': 'your_user_name',
        'PASSWORD': 'your_password',
        'HOST': 'your_mysql_server_host',
        'PORT': 'your_mysql_server_port',
    }
}

settings.configure(
    DATABASES = db_conf,
    INSTALLED_APPS     = ( "myApp", )
)

# Calling django.setup() is required for “standalone” Django u usage
# https://docs.djangoproject.com/en/1.8/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
import django
django.setup()

if __name__ == '__main__':
    import sys
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
Safko answered 9/9, 2015 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.