django采用cherrypy作为轻量级web服务器。

https://www.xuebuyuan.com/zh-hant/1547838.html

新建app,并添加到settings.py
在app下增加management包。

將以下代碼保存為文件runservercp.py,放到management/commands/runservercp.py

import os

import cherrypy
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "Starts a lightweight Web server for development."
    args = '[optional port number, or ipaddr:port]'

    # Validation is called explicitly each time the server is reloaded.  
    requires_model_validation = False

    def handle(self, addrport="", *args, **options):
        from django.core.handlers.wsgi import WSGIHandler
        if args:
            raise CommandError('Usage is runservercp %s' % self.args)

        def inner_run():
            from django.conf import settings
            from django.utils import translation

            translation.activate(settings.LANGUAGE_CODE)

            try:
                handler = StaticFilesHandler(WSGIHandler())

                print(os.path.abspath(os.getcwd()))
                print(os.path.abspath(os.getcwd()) + '/static')
                cherrypy.config.update({
                    'server.socket_host': "0.0.0.0",
                    'server.socket_port': 8080,
                    'server.thread_pool': 100,
                })
                cherrypy.tree.graft(handler, '/')
                cherrypy.engine.start()
                cherrypy.engine.block()
            finally:
                cherrypy.engine.exit()

        inner_run()

posted @ 2018-09-12 16:08  abcyrf  阅读(296)  评论(0)    收藏  举报