使用openshift部署本地django应用程序 [英] Deploying a local django app using openshift

查看:262
本文介绍了使用openshift部署本地django应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用django构建了webapp。为了托管它,我试图使用openshift,但是难以获得任何工作。似乎缺乏一步一步的做法。到目前为止,我有git工作正常,该应用程序在本地的开发环境工作,我已经成功地创建了一个开放的应用程序。



按照opens只需获得标准页面欢迎使用您的Openshift应用程序。



我遵循了这个https://developers.openshift.com/en/python-getting-started.html#step1 尝试更改wsgi.py文件。将它改为你好世界,推动它,但我仍然得到openshift默认页面。



有没有一个很好的综合资源,让本地的Django应用程序启动并运行在Openshift ?我可以在google上找到的大部分内容就是我已经建立的示例应用程序,这不是很有用。

解决方案

编辑记住这是一个依赖平台的答案,由于提供Django的OpenShift平台可能会改变,所以这个答案可能会变得无效。截至2016年4月1日,该答案在整个范围内仍然有效。



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


  1. 不要使用Django磁带,而是使用python 2.7磁带。使用Django购物车并尝试更新django版本带来许多头痛,如果从头开始,不包括在内。

  2. 通过git克隆您的存储库。您将获得您的项目和...

     #git clone yourrepo @ rhcloud.com:app.git yourproject<  - 将其替换为您实际的开箱回购地址

    yourproject /
    + --- wsgi.py
    + ---设置。 py
    * ---。openshift /(其内容 - 我现在省略)


  3. 为您的全新的存储库克隆到本地计算机中,创建一个virtualenv。激活它,并通过 pip 和您需要的所有依赖项(例如一个新的Pillow包,MySQL数据库包...)安装Django。在那里创建一个django项目说,你的项目。 编辑创建一个带有空的虚拟文件的 wsgi / static 目录(例如 .gitkeep - 名称只是惯例:您可以使用任何您想要的名称)。

      #assuming you have virtualenv-包装安装和设置
    mkvirtualenv myenvironment
    workon myenvironment
    pip安装Django [== xy [.z]] #select您的版本;可选的。
    #创建git仓库内的项目
    cd path / to / yourproject /
    django-admin.py startproject yourjdproject。
    #creating dummy wsgi / static directory for collectstatic
    mkdir -p wsgi / static
    touch wsgi / static / .gitkeep


  4. 在那里创建一个django应用程序。说,你的app


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

      yourproject / 
    + --- wsgi /
    | + --- static /
    | + ---。gitkeep
    + --- wsgi.py
    + --- setup.py
    + ---。openshift /(其内容 - 我现在省略)
    + --- yourdjproject /
    | + ----__ init__.py
    | + ---- urls.py
    | + ---- settings.py
    | + ---- wsgi.py
    + --- + yourapp /
    + ----__ init__.py
    + ---- models.py
    + --views.py
    + ---- tests.py
    + ----迁移
    + ---__ init__.py
    / pre>

  6. 像您一直做的一样设置您的django应用程序(我不会在此详细介绍)。记住要把你安装的所有依赖项包含在setup.py文件中(这个答案不是描述WHY的地方,而setup.py是包安装程序,而opensshift则使用它来在每个部署上重新安装你的应用程序,所以保持


  7. 为您的模型创建迁移。

  8. 编辑openshift-given WSGI脚本如下。您将包括django WSGI应用程序,包括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))
    除了IOError:
    pass

    from yourdjproject.wsgi import application


  9. 编辑.openshift / action_hooks中的钩子以自动执行db sincronization和媒体管理:



    构建钩子

     #! bin / bash 
    #this是.openshift / action / hooks / build
    #remember使它+ x所以openshift可以运行它。
    如果[! -d $ {OPENSHIFT_DATA_DIR} media];然后
    mkdir -p $ {OPENSHIFT_DATA_DIR} media
    fi
    ln -snf $ {OPENSHIFT_DATA_DIR} media $ OPENSHIFT_REPO_DIR / wsgi / static / media

    #### #####################文件结尾

    部署钩子

     #!/ bin / bash 
    #这是一个部署钩子.openshift / action_hooks / deploy
    source $ OPENSHIFT_HOMEDIR / python / virtenv / bin / activate
    cd $ OPENSHIFT_REPO_DIR
    echo执行'python manage.py migrate'
    python manage.py migrate
    echo执行'python manage.py collectstatic --noinput'
    python manage.py collectstatic --noinput

    ############# #############文件结尾


  10. 现在你有wsgi准备好,通过导入指向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'媒体')
    STATICFILES_DIRS =(os.path.join(BASE_DIR,'yourjdproject','static'))
    TEMPLATE_DIRS =(os.path.join(BASE_DIR,'yourjdproject','templates' )$)


  11. 创建示例视图,示例模型,示例迁移和PUSH


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

     
    您的djproject项目的Django设置

    有关此文件的更多信息,请参阅
    https:// docs。 djangoproject.com/en/1.7/topics/settings/

    有关设置及其值的完整列表,请参阅
    https://docs.djangoproject.com/en/1.7/ref / settings /


    #在项目中构建路径,如下所示:os.path.join(BASE_DIR,...)
    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__ file__))

    ON_OPENSHIFT = False
    如果os.environ中的OPENSHIFT_REPO_DIR:
    ON_OPENSHIFT = True


    #快速启动开发设置 - 不适合生产
    #请参阅https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

    #安全警告:保留生产秘密密钥!
    SECRET_KEY ='60e32dn-za#y = x!551tditnset(o9b @ 2bkh1)b $ hn& 0 $ ec5-j7'

    #应用程序定义

    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.applicatio n'

    #数据库
    #https://docs.djangoproject.com/en/1.7/ref/settings/#databases

    如果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',#如果要使用MySQL
    'NAME':'yourloca
    'USER':'yourlocalusername',
    'PASSWORD':'yourlocaluserpassword',
    'HOST':'yourlocaldbhost',
    'PORT':'3306' ,#这将是MySQL
    }


    #国际化
    #https://docs.djangoproject.com/en/1.7/topics/ i18n /

    LANGUAGE_CODE ='yr-LC'
    TIME_ZONE ='您/时区/这里'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True

    #静态文件(CSS,JavaScript,图像)
    #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 = path.join(BASE_DIR,'wsgi','static','media')
    STATICFILES_DIRS =(os.path.join(BASE_DIR,'yourdjproject','static'))
    TEMPLATE_DIRS = os.path.join(BASE_DIR,'yourdjproject', 'template'),)


  13. 添加,提交,推送,享受。 >

      cd路径/ to / yourproject / 
    git add。
    git commit -m你的消息
    git push origin master#这个命令会让LONG
    #git享受


  14. 您的示例Django应用程序几乎准备好了!但是,如果您的应用程序具有外部依赖关系,则不会有明显的原因。这就是我告诉你开发一个简单应用程序的原因。



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



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


    1. 打开该文件,读取所有行。 li>
    2. 对于每一行,如果它有一个#,请删除#和其后的所有内容。

    3. strip
    4. 丢弃空行,并将结果(即剩余行)作为数组。

    5. 必须分配结果到 install_requires = 关键字参数在安装调用setup.py文件。

    对不起,我以前没有在教程中包含这个!但是您需要在服务器中实际安装Django。也许是一个明显的建议,每个Python开发人员都可以事先知道。但是抓住这个机会我说:在包含任何其他依赖关系的条件下,在require.txt(或根据你是否使用require.txt文件)中添加适当的Django依赖项。


这应该可以帮助你安装一个Django应用程序,并花了我很多时间来标准化这个过程。如果出现问题,请尽快与我联系。



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



编辑2 :您可以使用git hook (例如pre_commit)为某些文件设置权限,如管道脚本(构建,部署,...)。在这个答案中,请参阅@StijndeWitt和@OliverBurdekin的评论,以及这个问题了解更多详情。


I've built a webapp using django. In order to host it I'm trying to use openshift but am having difficulty in getting anything working. There seems to be a lack of step by steps for this. So far I have git working fine, the app works on the local dev environment and I've successfully created an app on openshift.

Following the URL on openshift once created I just get the standard page of "Welcome to your Openshift App".

I've followed this https://developers.openshift.com/en/python-getting-started.html#step1 to try changing the wsgi.py file. Changed it to hello world, pushed it and yet I still get the openshift default page.

Is there a good comprehensive resource anywhere for getting local Django apps up and running on Openshift? Most of what I can find on google are just example apps which aren't that useful as I already have mine built.

解决方案

Edit: Remember this is a platform-dependent answer and since the OpenShift platform serving Django may change, this answer could become invalid. As of Apr 1 2016, this answer remains valid at its whole extent.

Many times this happened to me and, since I had to mount at least 5 applications, I had to create my own lifecycle:

  1. Don't use the Django cartridge, but the python 2.7 cartridge. Using the Django cart. and trying to update the django version brings many headaches, not included if you do it from scratch.
  2. Clone your repository via git. You will get yourproject and...

    # 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)
    

  3. Make a virtualenv for your brand-new repository cloned into your local machine. Activate it and install Django via pip and all the dependencies you would need (e.g. a new Pillow package, MySQL database package, ...). Create a django project there. Say, yourdjproject. Edit Create, alongside, a wsgi/static directory with an empty, dummy, file (e.g. .gitkeep - the name is just convention: you can use any name you want).

     #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
    

  4. Create a django app there. Say, yourapp. Include it in your project.

  5. You will have something like this (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
    

  6. Set up your django application as you'd always do (I will not detail it here). Remember to include all the dependencies you installed, in the setup.py file accordingly (This answer is not the place to describe WHY, but the setup.py is the package installer and openshift uses it to reinstall your app on each deploy, so keep it up to date with the dependencies).

  7. Create your migrations for your models.
  8. Edit the openshift-given WSGI script as follows. You will be including the django WSGI application AFTER including the virtualenv (openshift creates one for python cartridges), so the pythonpath will be properly set up.

    #!/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
    

  9. Edit the hooks in .openshift/action_hooks to automatically perform db sincronization and media management:

    build hook

    #!/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
    

    deploy hook

    #!/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
    

  10. Now you have the wsgi ready, pointing to the django wsgi by import, and you have your scripts running. It is time to consider the locations for static and media files we used in such scripts. Edit your Django settings to tell where did you want such 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, 'yourjdproject', 'static'),)
    TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'yourjdproject', 'templates'),)
    

  11. Create a sample view, a sample model, a sample migration, and PUSH everything.

  12. Edit Remember to put the right settings to consider both environments so you can test and run in a local environment AND in openshift (usually, this would involve having a local_settings.py, optionally imported if the file exists, but I will omit that part and put everything in the same file). Please read this file conciously since things like yourlocaldbname are values you MUST set accordingly:

    """
    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'),)
    

  13. Git add, commit, push, enjoy.

    cd path/to/yourproject/
    git add .
    git commit -m "Your Message"
    git push origin master # THIS COMMAND WILL TAKE LONG
    # git enjoy
    

  14. Your sample Django app is almost ready to go! But if your application has external dependencies it will blow with no apparent reason. This is the reason I told you to develop a simple application. Now it is time to make your dependencies work.

    [untested!] You can edit the deploy hook and add a command after the command cd $OPENSHIFT_REPO_DIR, like this: pip install -r requirements.txt, assuming the requirements.txt file exists in your project. pip should exist in your virtualenv, but if it does not, you can see the next solution.

    Alternatively, the setup.py is an already-provided approach on OpenShift. What I did many times is -assuming the requirements.txt file exists- is:

    1. Open that file, read all its lines.
    2. For each line, if it has a #, remove the # and everything after.
    3. strip leading and trailing whitespaces.
    4. Discard empty lines, and have the result (i.e. remaining lines) as an array.
    5. That result must be assigned to the install_requires= keyword argument in the setup call in the setup.py file.

    I'm sorry I did not include this in the tutorial before! But you need to actually install Django in the server. Perhaps an obvious suggestion, and every Python developer could know that beforehand. But seizing this opportunity I remark: Include the appropriate Django dependency in the requirements.txt (or setup.py depending on whetheryou use or not a requirements.txt file), as you include any other dependency.

This should help you to mount a Django application, and took me a lot of time to standarize the process. Enjoy it and don't hesitate on contacting me via comment if something goes wrong

Edit (for those with the same problem who don't expect to find the answer in this post's comments): Remember that if you edit the build or deploy hook files under Windows and you push the files, they will fly to the server with 0644 permissions, since Windows does not support this permission scheme Unix has, and has no way to assign permissions since these files do not have any extension. You will notice this because your scripts will not be executed when deploying. So try to deploy those files only from Unix-based systems.

Edit 2: You can use git hooks (e.g. pre_commit) to set permissions for certain files, like pipeline scripts (build, deploy, ...). See the comments by @StijndeWitt and @OliverBurdekin in this answer, and also this question for more details.

这篇关于使用openshift部署本地django应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆