`
sillycat
  • 浏览: 2541880 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

将django发布为桌面应用

阅读更多
将django发布为桌面应用

了解到的一些资源如下:
http://misunderstandings.wordpress.com/2008/06/26/django-desktop-app/
http://www.pyinstaller.org/wiki/DjangoApplication
http://www.pyinstaller.org/
http://www.pyinstaller.org/wiki/Python26Win
http://blog.robotercoding.com/?p=124
http://www.danomagnum.com/wiki/py2exe%20and%20django

综合以上资料,我的操作步骤如下:
第一步
新建项目exedjango
将原有的easydjango项目拷贝到根目录下,并将easydjango加为src目录(只是为了平时在 eclipse直接运行方便)

第二步
在根目录上新建文件,PyConvert.py如下:
from distutils.core import setup 
import py2exe 
 
setup(console=[{'script':'bootstrap.py','icon_resources':[(0x0001,'kath.ico')]}], 
         options={'py2exe':{'packages':['django','email','easydjango',]} }) 

在根目录上新建文件,bootstrap.py如下:
import django 
import easydjango.settings 
import webbrowser,time, sys, os 
from   django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException 
from   django.core.handlers.wsgi import WSGIHandler 
 
class DummyFile(object): 
    def write(*a, **kw): pass 
 
if __name__ == "__main__": 
    os.environ['DJANGO_SETTINGS_MODULE'] = 'easydjango.settings' 
    port = 8000 
    out = sys.stdout 
 
    from django.conf import settings 
    try: 
        path = 'media/' 
        handler = AdminMediaHandler(WSGIHandler(), path) 
 
        #sys.stderr = sys.stdout = DummyFile() 
        #webbrowser.open('http://localhost:%s/wiki' % port) #mmm 
        run('0.0.0.0', port, handler) 
    except WSGIServerException, e: 
        # Use helpful error messages instead of ugly tracebacks. 
        ERRORS = {
            13: "You don't have permission to access that port.", 
            98: "That port is already in use.", 
            99: "That IP address can't be assigned-to.", 
        }
        try: 
            error_text = ERRORS[e.args[0].args[0]] 
            sys.stderr.write("Error: %s \n" % error_text) 
        except (AttributeError, KeyError): 
            error_text = str(e)
平时运行django程序,其实直接在eclipse里面启动这个bootstrap.py就行了,调试其实还比较方便,不用再另外启动一个命令行了。

第三步
修改项目中的urls.py和settings.py等配置。
urls.py如下:
from django.conf.urls.defaults import *
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

admin.autodiscover()

import os 
CURRENT_DIR = os.path.dirname(__file__) 
OUTSIDE_DIR = CURRENT_DIR.split('library.zip')[0] 
print CURRENT_DIR 
print OUTSIDE_DIR

urlpatterns = patterns('',
    # Example:
    # (r'^easydjango/', include('easydjango.foo.urls')),
    (r'^hello/$', 'easydjango.hello.HelloWorld.index'),
    (r'^add/$', 'easydjango.hello.Add.index'),
    (r'^list/$', 'easydjango.hello.List.index'),
    (r'^wiki/$', 'easydjango.wiki.views.index'),
    (r'^wiki/(?P<pagename>\w+)/$', 'easydjango.wiki.views.index'),
    (r'^wiki/(?P<pagename>\w+)/edit/$', 'easydjango.wiki.views.edit'),
    (r'^wiki/(?P<pagename>\w+)/save/$', 'easydjango.wiki.views.save'),
    (r'^address/', include('easydjango.address.urls')),
    (r'^ajax/$', 'django.views.generic.simple.direct_to_template',{'template': 'ajax/ajax.html'}),
    (r'^ajax/input/$', 'easydjango.ajax.views.input'),
    (r'^ajax/json/$', 'easydjango.ajax.views.json'),
    (r'^calendar/$', 'django.views.generic.simple.direct_to_template',{'template': 'my_calendar/calendar.html'}),
   
    (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_PATH}),
   

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
)

settings.py如下:
# Django settings for easydjango project.
from django.conf import settings
import os

#DEFAULT_CHARSET = 'utf-8'
#DATABASE_OPTIONS = { 'charset': 'utf8', }
#FILE_CHARSET= 'utf-8'

DEBUG = True
TEMPLATE_DEBUG = DEBUG

CURRENT_DIR = os.path.dirname(__file__) 
OUTSIDE_DIR = CURRENT_DIR.split('library.zip')[0]

print CURRENT_DIR
print OUTSIDE_DIR

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = OUTSIDE_DIR + '/data.db'             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
#TIME_ZONE = 'America/Chicago'
TIME_ZONE = 'Asia/Shanghai'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-cn'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
ADMIN_MEDIA_ROOT = OUTSIDE_DIR + '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'i_9wlov#n93b(%13vzytj=nd)nvy)kkth8t-he*8k#o-3*t4-e'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
    #'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.doc.XViewMiddleware',
)

ROOT_URLCONF = 'easydjango.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    #'./template',
    os.path.join(OUTSIDE_DIR,'template'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'easydjango.wiki',
    'easydjango.address',
    'easydjango.ajax',
    'easydjango.my_calendar',
)

STATIC_PATH = OUTSIDE_DIR + '/media'
UPLOAD_USER = 'kiko'

其实变化不大,只是为了让py2exe了以后,还能找到这些对应的目录啊这些。
一起准备就绪后,使用命令
D:\work\exedjango>python PyConvert.py py2exe
就可以生成dist目录,这个目录里面的bootstrap.exe就是WINDOWS上可以直接运行的绿色软件了:)

第四步
要将一些需要的文件,拷贝到这个路径上才行。比如:
media/
template/
data.db
等,另外我们的easydjango其实已经打在了压缩包library.zip里面了,可以将对应的media,template这些删除,以减少打给别人的zip包的大小。整个过程就胜利结束了:)

问题一
过程中有遇到报错情况。

报错如下:
Traceback (most recent call last):
  File "django\core\servers\basehttp.pyc", line 279, in run
  File "django\core\servers\basehttp.pyc", line 651, in __call__
  File "django\core\handlers\wsgi.pyc", line 230, in __call__
  File "django\core\handlers\base.pyc", line 42, in load_middleware
ImproperlyConfigured: Error importing middleware django.middleware.common: "No module named text"

问题解决,修改为:
setup(console=[{'script':'bootstrap.py','icon_resources':[(0x0001,'kath.ico')]}], 
         options={'py2exe':{'packages':['django','email','easydjango',]} })
分享到:
评论
1 楼 outofthink 2011-09-02  
那个no text module 错误始终解决不了,有人解决了么

相关推荐

Global site tag (gtag.js) - Google Analytics