PythonDjango-Oscar

oscar的电商平台

2018-04-16  本文已影响652人  ab64fd4eaee3

说明:Oscar是在Github上得星最多,基于Django的电商框架,可以帮助企业快速企业建立支持多渠道(网站、微信等),集成多后台系统的品牌电商平台。而基于金山云提供的公有云服务,在低投资的情况下获得高可用、高安全而且访问速度快的电商服务。本文介绍如何利用Django-oscar,基于金山云提供的云服务器和关系数据库RDS快速搭建电商平台的过程。

一、环境需求

1、创建云服务器,并关联一个弹性IP。

2、安装python3.6.1(通过下载最新的安装包,重新编译进行安装)

[myang@vm10-0-0-21 ~]$ python3 --version

Python 3.6.1

3、创建一个RDS实例

二、建立Oscar开放环境

1、创建Python虚拟环境

[myang@vm10-0-0-21 ~]$ mkdir oscar_prj
[myang@vm10-0-0-21 ~]$ cd oscar_prj/
[myang@vm10-0-0-21 oscar_prj]$ ls
[myang@vm10-0-0-21 oscar_prj]$ python3 -m venv venv
[myang@vm10-0-0-21 oscar_prj]$ ls
venv
[myang@vm10-0-0-21 oscar_prj]$ source venv/bin/activate

(venv) [myang@vm10-0-0-21 oscar_prj]$ python --version
Python 3.6.1

2、安装django-oscar包

(venv) [myang@vm10-0-0-21 oscar_prj]$ pip install django-oscar
    Collecting django-oscar
      Downloading django_oscar-1.4-py2.py3-none-any.whl (5.6MB)
        100% |████████████████████████████████| 5.6MB 122kB/s

3、创建Django项目,保证该Django项目能正常启动

    (venv) [myang@vm10-0-0-21 oscar_prj]$ django-admin startproject frobshop
    (venv) [myang@vm10-0-0-21 oscar_prj]$ cd frobshop/
    (venv) [myang@vm10-0-0-21 frobshop]$ python manage.py runserver
    Performing system checks...

    System check identified no issues (0 silenced).

    You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
    Run 'python manage.py migrate' to apply them.

    April 20, 2017 - 10:26:41
    Django version 1.10.7, using settings 'frobshop.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    [20/Apr/2017 10:27:46] "GET / HTTP/1.1" 200 1767

4、修改frobshop/settings.py配置文件

    """
    Django settings for frobshop project.

    Generated by 'django-admin startproject' using Django 1.10.7.

    For more information on this file, see
    https://docs.djangoproject.com/en/1.10/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.10/ref/settings/
    """

    import os

    #import oscar缺省配置
    from oscar.defaults import *
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '=1pberh++qpw!-nzcky*8fvn6!lcn_i30$4g#)i$ot^9bfv72='

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    #让所有客户端IP都能访问
    ALLOWED_HOSTS = ['*',]

    location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), x)

    # Application definition

    #导入oscar get_core_apps函数

    from oscar import get_core_apps

    #加载oscar相关应用模块

    INSTALLED_APPS = [

        'django.contrib.admin',

        'django.contrib.auth',

        'django.contrib.contenttypes',

        'django.contrib.sessions',

        'django.contrib.sites',

        'django.contrib.messages',

        'django.contrib.staticfiles',

        'django.contrib.flatpages',

        'widget_tweaks',

        'mod_wsgi.server',

    ] + get_core_apps()

    #定义SITE_ID

    SITE_ID = 1

    配置MIDDLEWARE

    MIDDLEWARE = [

        'django.middleware.security.SecurityMiddleware',

        'django.contrib.sessions.middleware.SessionMiddleware',

        'django.middleware.common.CommonMiddleware',

        'django.middleware.csrf.CsrfViewMiddleware',

        'django.contrib.auth.middleware.AuthenticationMiddleware',

        'django.contrib.messages.middleware.MessageMiddleware',

        'django.middleware.clickjacking.XFrameOptionsMiddleware',

        'oscar.apps.basket.middleware.BasketMiddleware',

        'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',

    ]

    #配置允许通过email进行登录

    AUTHENTICATION_BACKENDS = (

        'oscar.apps.customer.auth_backends.EmailBackend',

        'django.contrib.auth.backends.ModelBackend',

    )

    ROOT_URLCONF = 'frobshop.urls'

    #配置模板路径信息

    from oscar import OSCAR_MAIN_TEMPLATE_DIR

    TEMPLATES = [

        {

            'BACKEND': 'django.template.backends.django.DjangoTemplates',

            'DIRS': [

                os.path.join(BASE_DIR, 'templates'),

                OSCAR_MAIN_TEMPLATE_DIR

            ],

            'APP_DIRS': True,

            'OPTIONS': {

                'context_processors': [

                    'django.template.context_processors.debug',

                    'django.template.context_processors.request',

                    'django.contrib.auth.context_processors.auth',

                    'django.template.context_processors.i18n',

                    'django.contrib.messages.context_processors.messages',

                    'oscar.apps.search.context_processors.search_form',

                    'oscar.apps.promotions.context_processors.promotions',

                    'oscar.apps.checkout.context_processors.checkout',

                    'oscar.apps.customer.notifications.context_processors.notifications',

                    'oscar.core.context_processors.metadata',

                ],

            },

        },

    ]

    WSGI_APPLICATION = 'frobshop.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/1.10/ref/settings/#databases

    #配置数据库信息,此处需要配置为RDS信息
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

    # Password validation
    # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]

    # Internationalization
    # https://docs.djangoproject.com/en/1.10/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.10/howto/static-files/

    #配置静态文件属性

    MEDIA_ROOT = location("public/media")

    MEDIA_URL = '/media/'

    STATIC_URL = '/static/'

    STATIC_ROOT = location('public/static')

    STATICFILES_DIRS = (

        location('static/'),

    )

    STATICFILES_FINDERS = (

        'django.contrib.staticfiles.finders.FileSystemFinder',

        'django.contrib.staticfiles.finders.AppDirectoriesFinder',

        'compressor.finders.CompressorFinder',

    )

    #配置内置搜索引擎

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        },
    }

5、修改forbshop/urls.py文件

from django.conf.urls import include, url

from django.contrib import admin

from oscar.app import application

urlpatterns = [

    url(r'^i18n/', include('django.conf.urls.i18n')),

    # The Django admin is not officially supported; expect breakage.

    # Nonetheless, it's often useful for debugging.

    url(r'^admin/', include(admin.site.urls)),

    url(r'', include(application.urls)),

] 

6、创建数据库

 (venv) [myang@vm10-0-0-21 frobshop]$ ./manage.py migrate
Operations to perform:
  Apply all migrations: address, admin, analytics, auth, basket, catalogue, contenttypes, customer, flatpages, offer, order, partner, payment, promotions, reviews, sessions, shipping, sites, thumbnail, voucher, wishlists
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying address.0001_initial... OK
  Applying admin.0001_initial... OK

7、初始化国家信息

(venv) [myang@vm10-0-0-21 frobshop]$ pip install pycountry
Collecting pycountry
  Using cached pycountry-17.1.8.tar.gz
Installing collected packages: pycountry
  Running setup.py install for pycountry ... done
Successfully installed pycountry-17.1.8
(venv) [myang@vm10-0-0-21 frobshop]$ ./manage.py oscar_populate_countries
Successfully added 249 countries.

三、部署生产环境

1、安装mod_wsgi

在安装 mod_wsgi前,确保已经安装了httpd和httpd-devel包

[myang@vm10-0-0-21 frobshop]$ rpm -qa |grep httpd

httpd-tools-2.4.6-45.el7.centos.4.x86_64

httpd-2.4.6-45.el7.centos.4.x86_64

httpd-devel-2.4.6-45.el7.centos.4.x86_64

 (venv) [myang@vm10-0-0-21 frobshop]$ pip install mod_wsgi
Collecting mod_wsgi
  Using cached mod_wsgi-4.5.15.tar.gz
Installing collected packages: mod-wsgi
  Running setup.py install for mod-wsgi ... done

2、安装压缩工具包

(venv) [myang@vm10-0-0-21 frobshop]>nbsp; pip install django_compressor
Collecting django_compressor
  Downloading django_compressor-2.1.1-py2.py3-none-any.whl (130kB)
    100% |████████████████████████████████| 133kB 1.1MB/s
Collecting django-appconf>=1.0 (from django_compressor)
  Downloading django_appconf-1.0.2-py2.py3-none-any.whl
Collecting rjsmin==1.0.12 (from django_compressor)
  Downloading rjsmin-1.0.12.tar.gz (446kB)
    100% |████████████████████████████████| 450kB 1.3MB/s
Collecting rcssmin==1.0.6 (from django_compressor)
  Downloading rcssmin-1.0.6.tar.gz (582kB)
    100% |████████████████████████████████| 583kB 1.2MB/s
Installing collected packages: django-appconf, rjsmin, rcssmin, django-compressor
  Running setup.py install for rjsmin ... done
  Running setup.py install for rcssmin ... done
Successfully installed django-appconf-1.0.2 django-compressor-2.1.1 rcssmin-1.0.6 rjsmin-1.0.12

3、整理静态文件

创建静态文件目录,并把所有静态文件集中到特定目录下。该目录下的文件可通过CDN加速。

(venv) [myang@vm10-0-0-21 frobshop]$ mkdir /home/myang/oscar_prj/frobshop/frobshop/static
(venv) [myang@vm10-0-0-21 frobshop]$ ./manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:

    /home/myang/oscar_prj/frobshop/frobshop/public/static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes
Copying '/home/myang/oscar_prj/venv/lib/python3.6/site-packages/django/contrib/admin/static/admin/css/login.css'
Copying '/home/myang/oscar_prj/venv/lib/python3.6/site-packages/django/contrib/admin/static/admin/css/changelists.css'
Copying '/home/myang/oscar_prj/venv/lib/python3.6/site-packages/django/contrib/admin/static/admin/css/base.css'

4、创建超级用户,在通过http://hostname:8000/admin时需要用该用户登录

(venv) [myang@vm10-0-0-21 frobshop]$ ./manage.py createsuperuser
Username (leave blank to use 'myang'): admin
Email address: admin@hotmail.com
Password:
Password (again):
Superuser created successfully.

5、通过wsgi运行应用,该命令会自动启动apache server

(venv) [myang@vm10-0-0-21 frobshop]$ ./manage.py runmodwsgi
Successfully ran command.
Server URL         : http://localhost:8000/
Server Root        : /tmp/mod_wsgi-localhost:8000:1000
Server Conf        : /tmp/mod_wsgi-localhost:8000:1000/httpd.conf
Error Log File     : /tmp/mod_wsgi-localhost:8000:1000/error_log (warn)
Request Capacity   : 5 (1 process * 5 threads)
Request Timeout    : 60 (seconds)
Startup Timeout    : 15 (seconds)
Queue Backlog      : 100 (connections)
Queue Timeout      : 45 (seconds)
Server Capacity    : 20 (event/worker), 20 (prefork)
Server Backlog     : 500 (connections)
Locale Setting     : en_US.UTF-8 

(venv) [myang@vm10-0-0-21 frobshop]$ ps -ef|grep httd

myang    10867 30170  0 10:26 pts/1    00:00:00 grep --color=auto htt

myang    13919   513  0 Apr20 ?        00:00:03 httpd (mod_wsgi-express)   -f /tmp/mod_wsgi-localhost:8000:1000/httpd.conf -DMOD_WSGI_MPM_ENABLE_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_WORKER_MODULE -DMOD_WSGI_MPM_EXISTS_PREFORK_MODULE -k start -DFOREGROUND

myang    22857 13919  0 Apr20 ?        00:00:08 (wsgi:localhost:8000:1000) -f /tmp/mod_wsgi-localhost:8000:1000/httpd.conf -DMOD_WSGI_MPM_ENABLE_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_WORKER_MODULE -DMOD_WSGI_MPM_EXISTS_PREFORK_MODULE -k start -DFOREGROUND

myang    22858 13919  0 Apr20 ?        00:00:17 httpd (mod_wsgi-express)   -f /tmp/mod_wsgi-localhost:8000:1000/httpd.conf -DMOD_WSGI_MPM_ENABLE_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_WORKER_MODULE -DMOD_WSGI_MPM_EXISTS_PREFORK_MODULE -k start -DFOREGROUND

myang    27429 13919  0 Apr20 ?        00:00:17 httpd (mod_wsgi-express)   -f /tmp/mod_wsgi-localhost:8000:1000/httpd.conf -DMOD_WSGI_MPM_ENABLE_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_EVENT_MODULE -DMOD_WSGI_MPM_EXISTS_WORKER_MODULE -DMOD_WSGI_MPM_EXISTS_PREFORK_MODULE -k start -DFOREGROUND

通过浏览器访问,可获得如下界面

[KSC Solution > 基于Django-oscar的电商框架 > Screen Shot 2017-04-21 at 10.31.52 AM.png]

6、停止服务器

(venv) [myang@vm10-0-0-21 ~]$ /tmp/mod_wsgi-localhost:8000:1000/apachectl stop

(venv) [myang@vm10-0-0-21 ~]$ ps -ef|grep httpd

myang    11120 30170  0 10:27 pts/1    00:00:00 grep --color=auto httpd
上一篇下一篇

猜你喜欢

热点阅读