使用openshift部署本地django应用程序

Oli*_*kin 21 python git django openshift

我用django构建了一个webapp.为了主持它,我正在尝试使用openshift,但是很难让任何工作.对此,似乎缺乏一步一步的措施.到目前为止,我有git工作正常,该应用程序适用于本地开发环境,我已成功在openshift上创建了一个应用程序.

在openshift创建URL后,我只需获得标准页面"欢迎使用您的Openshift应用程序".

我已经按照https://developers.openshift.com/en/python-getting-started.html#step1尝试更改wsgi.py文件.将其更改为hello world,推送它然后我仍然获得openshift默认页面.

是否有一个很好的综合资源可以让本地Django应用程序在Openshift上运行?我在谷歌上找到的大部分内容都只是示例应用程序,这些应用程序并不像我已经构建的那样有用.

Lui*_*lli 40

编辑:请记住这是一个依赖于平台的答案,因为服务Django的OpenShift平台可能会改变,这个答案可能会变得无效.截至2016年4月1日,此答案在整个范围内仍然有效.

很多时候,这发生在我身上,因为我必须安装至少5个应用程序,所以我必须创建自己的生命周期:

  1. 不要使用Django盒式磁带,而是使用python 2.7盒式磁带.使用Django购物车.并尝试更新django版本会带来许多令人头疼的问题,如果你从头开始做的话就不包括在内.
  2. 通过git克隆你的存储库.你会得到yourproject......

    # git clone yourrepo@rhcloud.com:app.git yourproject <- replace it with your actual openshift repo address
    
    yourproject/
    +---wsgi.py
    +---setup.py
    *---.openshift/ (with its contents - I omit them now)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 为您的全新存储库创建一个virtualenv克隆到您的本地计算机.激活它并通过pip你需要的所有依赖项安装Django (例如一个新的Pillow包,MySQL数据库包......).在那里创建一个django项目.说,你的项目.编辑创建一个wsgi/static带有空虚拟文件的目录(例如.gitkeep- 名称只是约定:您可以使用任何您想要的名称).

     #assuming you have virtualenv-wrapper installed and set-up
     mkvirtualenv myenvironment
     workon myenvironment
     pip install Django[==x.y[.z]] #select your version; optional.
     #creating the project inside the git repository
     cd path/to/yourproject/
     django-admin.py startproject yourjdproject .
     #creating dummy wsgi/static directory for collectstatic
     mkdir -p wsgi/static
     touch wsgi/static/.gitkeep
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在那里创建一个django应用程序.说,yourapp.将其包含在您的项目中.

  5. 你会有这样的东西(django 1.7):

    yourproject/
    +---wsgi/
    |   +---static/
    |       +---.gitkeep
    +---wsgi.py
    +---setup.py
    +---.openshift/ (with its contents - I omit them now)
    +---yourdjproject/
    |   +----__init__.py
    |   +----urls.py
    |   +----settings.py
    |   +----wsgi.py
    +---+yourapp/
        +----__init__.py
        +----models.py
        +----views.py
        +----tests.py
        +----migrations
             +---__init__.py
    
    Run Code Online (Sandbox Code Playgroud)
  6. 像往常一样设置你的django应用程序(我不会在这里详述).请记住在setup.py文件中相应地包含您安装的所有依赖项(此答案不是描述为什么的地方,但setup.py是软件包安装程序,openshift使用它在每次部署时重新安装您的应用程序,因此请保持它是最新的依赖项).

  7. 为模型创建迁移.
  8. 编辑openshift给定的WSGI脚本,如下所示.你将包括django WSGI应用程序AFTER,包括virtualenv(openshift创建一个用于python cartridge),因此pythonpath将被正确设置.

    #!/usr/bin/python
    import os
    virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
    virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
    try:
        execfile(virtualenv, dict(__file__=virtualenv))
    except IOError:
        pass
    
    from yourdjproject.wsgi import application
    
    Run Code Online (Sandbox Code Playgroud)
  9. 编辑.openshift/action_hooks中的钩子以自动执行db sincronization和媒体管理:

    建立钩子

    #!/bin/bash
    #this is .openshift/action/hooks/build
    #remember to make it +x so openshift can run it.
    if [ ! -d ${OPENSHIFT_DATA_DIR}media ]; then
        mkdir -p ${OPENSHIFT_DATA_DIR}media
    fi
    ln -snf ${OPENSHIFT_DATA_DIR}media $OPENSHIFT_REPO_DIR/wsgi/static/media
    
    ######################### end of file
    
    Run Code Online (Sandbox Code Playgroud)

    部署钩子

    #!/bin/bash
    #this one is the deploy hook .openshift/action_hooks/deploy
    source $OPENSHIFT_HOMEDIR/python/virtenv/bin/activate
    cd $OPENSHIFT_REPO_DIR
    echo "Executing 'python manage.py migrate'"
    python manage.py migrate
    echo "Executing 'python manage.py collectstatic --noinput'"
    python manage.py collectstatic --noinput
    
    ########################### end of file
    
    Run Code Online (Sandbox Code Playgroud)
  10. 现在你准备好了wsgi,通​​过import指向django wsgi,你运行了脚本.是时候考虑我们在这些脚本中使用的静态和媒体文件的位置了.编辑你的Django设置,告诉你想要这样的文件在哪里:

    STATIC_URL = '/static/'
    MEDIA_URL = '/media/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static')
    MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media')
    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'static'),)
    TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'templates'),)
    
    Run Code Online (Sandbox Code Playgroud)
  11. 创建示例视图,示例模型,示例迁移和推送所有内容.

  12. 编辑记住要设置正确的设置以考虑这两种环境,这样你就可以在本地环境和openshift中测试和运行(通常,local_settings.py如果文件存在,这将涉及一个,可选地导入,但我将省略该部分并将所有内容放入同一个文件).请仔细阅读此文件,因为像 yourlocaldbname 这样的值是您必须相应设置的值:

    """
    Django settings for yourdjproject project.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/1.7/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.7/ref/settings/
    """
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    
    ON_OPENSHIFT = False
    if 'OPENSHIFT_REPO_DIR' in os.environ:
        ON_OPENSHIFT = True
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '60e32dn-za#y=x!551tditnset(o9b@2bkh1)b$hn&0$ec5-j7'
    
    # Application definition
    
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'yourapp',
        #more apps here
    )
    
    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    )
    
    ROOT_URLCONF = 'yourdjproject.urls'
    
    WSGI_APPLICATION = 'yourdjproject.wsgi.application'
    
    # Database
    # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
    
    if ON_OPENSHIFT:
        DEBUG = True
        TEMPLATE_DEBUG = False
        ALLOWED_HOSTS = ['*']
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'youropenshiftgenerateddatabasename',
                'USER': os.getenv('OPENSHIFT_MYSQL_DB_USERNAME'),
                'PASSWORD': os.getenv('OPENSHIFT_MYSQL_DB_PASSWORD'),
                'HOST': os.getenv('OPENSHIFT_MYSQL_DB_HOST'),
                'PORT': os.getenv('OPENSHIFT_MYSQL_DB_PORT'),
                }
        }
    else:
        DEBUG = True
        TEMPLATE_DEBUG = True
        ALLOWED_HOSTS = []
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql', #If you want to use MySQL
                'NAME': 'yourlocaldbname',
                'USER': 'yourlocalusername',
                'PASSWORD': 'yourlocaluserpassword',
                'HOST': 'yourlocaldbhost',
                'PORT': '3306', #this will be the case for MySQL
            }
        }
    
    # Internationalization
    # https://docs.djangoproject.com/en/1.7/topics/i18n/
    
    LANGUAGE_CODE = 'yr-LC'
    TIME_ZONE = 'Your/Timezone/Here'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.7/howto/static-files/
    
    STATIC_URL = '/static/'
    MEDIA_URL = '/media/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static')
    MEDIA_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static', 'media')
    STATICFILES_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'static'),)
    TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourdjproject', 'templates'),)
    
    Run Code Online (Sandbox Code Playgroud)
  13. Git添加,提交,推送,享受.

    cd path/to/yourproject/
    git add .
    git commit -m "Your Message"
    git push origin master # THIS COMMAND WILL TAKE LONG
    # git enjoy
    
    Run Code Online (Sandbox Code Playgroud)
  14. 您的示例Django应用程序几乎准备好了!但是如果你的应用程序有外部依赖关系,它将没有明显的原因.这就是我告诉你开发一个简单应用程序的原因.现在是时候让你的依赖工作了.

    [ 未经测试!您可以编辑部署挂钩并在命令后添加命令cd $OPENSHIFT_REPO_DIR,如下所示:pip install -r requirements.txt,假设您的项目中存在requirements.txt文件.pip应该存在于你的virtualenv中,但如果没有,你可以看到下一个解决方案.

    或者,setup.py是OpenShift上已经提供的方法.我做了很多次 - 假设requirements.txt文件存在 - 是:

    1. 打开该文件,读取其所有行.
    2. 对于每一行,如果它有#,则删除#和之后的所有内容.
    3. strip 前导和尾随空格.
    4. 丢弃空行,并将结果(即剩余行)作为数组.
    5. 必须将该结果分配给setup.py文件中调用中的install_requires=关键字参数setup.

    对不起,我之前没有在教程中包含这个内容!但是你需要在服务器中实际安装Django.也许是一个明显的建议,每个Python开发人员都可以事先知道.但是抓住这个机会我说:在includes.txt(或者setup.py取决于你是否使用requirements.txt文件)中包含适当的Django依赖项,因为你包含任何其他依赖项.

这应该可以帮助您安装Django应用程序,并花了我很多时间来标准化这个过程.享受它,如果出现问题,请通过评论与我联系

编辑(对于那些有同样问题但不希望在本文评论中找到答案的人):请记住,如果您在Windows下编辑构建或部署挂钩文件并推送文件,它们将飞到服务器0644权限,因为Windows不支持Unix拥有的此权限方案,并且无法分配权限,因为这些文件没有任何扩展名.您会注意到这一点,因为部署时不会执行脚本.因此,尝试仅从基于Unix的系统部署这些文件.

编辑2:您可以使用git hooks(例如pre_commit)为某些文件设置权限,例如管道脚本(构建,部署,...).请参阅@StijndeWitt和@OliverBurdekin在此答案中的评论,以及此问题以获取更多详细信息.


Tan*_*lam 6

1)  Step 1 install  Rubygems
Ubuntu - https://rubygems.org/pages/download
Windows - https://forwardhq.com/support/installing-ruby-windows
$ gem
or
C:\Windows\System32>gem
RubyGems is a sophisticated package manager for Ruby.  This is a
basic help message containing pointers to more information……..

2)  Step 2:
$ gem install rhc
Or
C:\Windows\System32> gem install rhc

3)  $ rhc
Or
C:\Windows\System32> rhc

Usage: rhc [--help] [--version] [--debug] <command> [<args>]
Command line interface for OpenShift.

4)  $ rhc app create -a mysite -t python-2.7
Or 
C:\Windows\System32>  rhc app create -a mysite -t python-2.7
# Here mysite would be the sitename of your choice
#It will ask you to enter your openshift account id and password

Login to openshift.redhat.com: Enter your openshift id here
Password : **********


Application Options
---------------------
Domain:    mytutorials
Cartridges: python-2.7
Gear Size:  Default
Scaling:    no

......
......

Your application 'mysite' is now available.

 URL : http://mysite.....................
 SSH to :  39394949......................
 Git remote: ssh://......................

Run 'rhc show-app mysite' for more details about your app.

5)  Clone your site
$ rhc git-clone mysite
Or
D:\> rhc git-clone mysite
.......................
Your application Git repository has been cloned to "D:\mysite"

6)  #”D:\mysite>” is the location we cloned.
D:\mysite> git remote add upstream -m master git://github.com/rancavil/django-openshift-quickstart.git

D:\mysite> git pull -s recursive -X theirs upstream master

7)  D:\mysite> git push
remote : ................
remote: Django application credentials
               user: admin
               xertefkefkt

remote: Git Post-Receive Result: success
.............

8)  D:\mysite>virtualenv venv --no-site-packages
D:\mysite>venv\Scripts\activate.bat
<venv> D:\mysite> python setup.py install
creating .....
Searching for Django<=1.6
.............
Finished processing dependencies for mysite==1.0

9)  Change admin password
<venv> D:\mysite\wsgi\openshift> python manage.py changepassword admin
password:
...
Password changed successfully for user 'admin'
<venv> D:\mysite\wsgi\openshift> python manage.py runserver
Validating models….

10) Git add
<venv> D:\mysite> git add.
<venv> D:\mysite> git commit -am"activating the app on Django / Openshift"
   .......
<venv> D:\mysite> git push



#----------------------------------------------------------------------------------
#-----------Edit your setup.py in mysite with packages you want to install----------

from setuptools import setup

import os

# Put here required packages
packages = ['Django<=1.6',  'lxml', 'beautifulsoup4', 'openpyxl']

if 'REDISCLOUD_URL' in os.environ and 'REDISCLOUD_PORT' in os.environ and 'REDISCLOUD_PASSWORD' in os.environ:
     packages.append('django-redis-cache')
     packages.append('hiredis')

setup(name='mysite',
      version='1.0',
      description='OpenShift App',
      author='Tanveer Alam',
      author_email='xyz@gmail.com',
      url='https://pypi.python.org/pypi',
      install_requires=packages,
)
Run Code Online (Sandbox Code Playgroud)