소프트웨어 개발/Python

[목업 프로젝트] 프로젝트 설정 Django - React - Python

늘근이 2015. 12. 25. 11:13

Python - Django 설정

 

Django 설치 : 1.9

pip install django==1.9

 

파이썬 2.7이상 버전은 이미 깔려있어야 한다.

 

 

 

Anaconda 2버전 설치 (3버전은 파이썬 라이브러리 호환성때문에 포기한다.)

 

아나콘다 설치시 기본으로 깔리는 Spyder IDE에서 버전 확인.

 

 

 

이제 프롬프트에서 다음과 같은 명령어를 실행

 

python django-admin startproject imfactory

 

를 실행하면 되는데 아무 반응이 없을 경우는 다음과 같은 파이썬 설치 스크립트 폴더로 가서 직접 실행시킨다.

 

python django-admin.py startproject imfactory

 

다음은, 각 파일에 대한 설명

 

 

 

그리고 이제 기본 폴더로 가서 작동시킨다.

기본 소켓은 6770 으로 하겠다. 나중에 실제 웹서비스는

다음과 같이 하면 된다.

$ python manage.py runserver 0.0.0.0:8000

 

 

 

 

위 페이지를 손대기 전에 React.js를 가지고 놀아본다.

아래 react 블로그를 참조한다.

 

https://facebook.github.io/react/blog/2013/08/19/use-react-and-jsx-in-python-applications.html

http://www.shalomeir.com/2015/05/snippod-boilerplate-1-full-stack-react-flux-django/

http://gregblogs.com/how-django-reactjs-and-browserify/

 

이제 실제로 세번째 링크를 통해 react와 django 등 기타 셋팅을 하도록 한다. 이 다음 부분은 위의 링크중 GREGBLOS.COM에서 발췌했으며 버전에 따라 틀린 부분은 수정했다.


프로젝트 생성

$ python django-admin.py startproject mysite


프로젝트 안  디렉터리 생성

$ mkdir static/js static/templates


프로젝트 안 생성

$ touch templates/base.html templates/index.html


DRF / PIPELINE / BRWOSERIFY 설치


$ pip install djangorestframework django-pipeline django-pipeline-browserify



Browserify / ufligy-js / babelify 설치 (node.js필요)


$ npm install -g browserify

$ npm install -g uglify-js

$ npm install --save-dev babelify


Bower설치


$ npm install -g bower


bower를 이용해 프론트 웹 프레임워크들 다운로드


$ bower install --save react

$ bower install --save jquery

 

mysite/settings.py 수정


import os  

from os.path import abspath, basename, dirname, join, normpath


# Replace BASE_DIR with this

DJANGO_ROOT = dirname(dirname(abspath(__file__)))  

SITE_ROOT = dirname(DJANGO_ROOT)  

SITE_NAME = basename(DJANGO_ROOT)




INSTALLED_APPS = (  

    ...


    'django.contrib.staticfiles',

    'pipeline',

    'rest_framework',

)


# Configure templates

TEMPLATES = [  

    {

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

        'DIRS': ['templates'],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',

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

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

            ],

        },

    },

]


# Static files (CSS, JavaScript, Images)


STATIC_URL = '/static/'  

STATIC_ROOT = normpath(join(DJANGO_ROOT, 'static'))  

STATICFILES_DIRS = ()  


# Django Pipeline (and browserify)

STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'


STATICFILES_FINDERS = (  

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

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

    'pipeline.finders.PipelineFinder',

)


PIPELINE_COMPILERS = (  

    'pipeline_browserify.compiler.BrowserifyCompiler',

)


PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.NoopCompressor'  

PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.uglifyjs.UglifyJSCompressor'


if DEBUG:  

    PIPELINE_BROWSERIFY_ARGUMENTS = '-t babelify'



PIPELINE = {

    'STYLESHEETS': {

        'colors': {

            'source_filenames': (

              'css/core.css',

              'css/colors/*.css',

              'css/layers.css',

              'css/style.css',

            ),

            'output_filename': 'css/mysite_css.css',

            'extra_context': {

                'media': 'screen,projection',

            },

        },

    },

    'JAVASCRIPT': {

        'stats': {

            'source_filenames': (

            'js/bower_components/jquery/dist/jquery.min.js',

            'js/bower_components/react/JSXTransformer.js',

            'js/bower_components/react/react-with-addons.js',

            'js/app.browserify.js',

            ),

        'output_filename': 'js/mysite_js.js',

        }

    }

}



base.html


{% load pipeline %}

<!DOCTYPE html>  

<html lang="en">  

  <head>

    <meta charset="utf-8">

    <title>{% block title %}{% endblock %}</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="description" content="Oh shit! Word?! Shit you care about but probably shouldn't.">

    <meta name="author" content="Oh shit! Word?!">


    <!-- styles -->

    {% stylesheet 'mysite_css' %}


  </head>

  <body>


    {% block content %}{% endblock %}


    <!-- JavaScript scripts -->


    {% javascript 'mysite_js' %}

  </body>

</html>  




index.html


{% extends 'base.html' %}

{% block title %}MySite{% endblock %}


{% block content %}

<div id="content">  

</div>  

{% endblock %}


css/style.css


body {  

  background-color: #22A7F0;

}


app.browserify.js


'use strict';


var $ = require('jquery');  

var React = require('react');


var TestApp = React.createClass({  

  render: function() {

    return (

      <div className="page">

        <h1>Oh shit! React works!</h1>

      </div>

    );

  }

});


React.render(  

  React.createElement(TestApp, null),

  document.getElementById('content')

);


static파일 콜렉트



$ python manage.py collectstatic



mysite.urls.py


from django.views.generic import TemplateView


urlpatterns = [  

    ...


    # Root

    url(r'^$', TemplateView.as_view(template_name='index.html')),


]





* os가 가져오는 디렉토리 참고



참고


setting object has no attribute pipeline

에러가 나는 이유는 pipeline에서 설정하는 CSS와 JS경로를 예전에는 PIPELINE_CSS 이러한 식으로 생성했지만 이제는 PIPELINE하나로 통합했기 때문이다. 

아래 글 중 Specifying Files를 참조한다.

https://django-pipeline.readthedocs.org/en/latest/configuration.html#ref-configuration