본문 바로가기
my_lesson/_NodeJSmongoDB

Django

by boolean 2017. 12. 3.
728x90

Django

DJango의 장점

It is free & opensource. 무료이며 오픈 소스이다.

It is speedable.   빠르다.

It have rich taskes. 추가기능이 풍부하다.

It takes security seriously. 보안을 중요하게 여긴다.

It is flexibly & scalable. 유연하고 방대하다.

It is Incredibly versatilel   용도가 매우 다양하다.


Warnnig : 여기에 계시된 내용이외에 추가사항은 꼭 공식 홈페이지를 이용하기 바랍니다. 최신으로 업데이트 되지 않은 내용들은 혼란을 줄것 입니다.

Django's Server


1. The Django Development Server  (Usages: Test.)
The Django development server comes packaged with Django and can be run with the following command:
$ django-admin.py runserver  // running localhost:8000,  It is a lightweight web server.
$ djando-admin.py runserver 10.0.0.150:8001  //specify host

For Apache and is a highly recommended method if you are using Apache as your web server.

3. uWSGI  (Usage: uch as NGINX, Apache, Cherokee, etc.)
uWSGI is a server that implements the WSGI protocol in order to communicate with other web servers such as NGINX, Apache, Cherokee, etc.

4. Gunicorn
Gunicorn is a Python WSGI HTTP server much like uWSGI.

Django's Database
If you plan to use Django’s database API functionality, you’ll need to make sure a database server is running.
Officially supported with PostgreSQL,MariaDB, MySQL, Oracle and SQLite.
If you’re using Django’s testing framework to test database queries, Django will need permission to create a test database.

How to install Django

진행과정은 제일 하단에 프로젝트 트리구조 그림을 참조 하길 바란다.

Django on Jython

Python on Windows


If you are upgrading your installation of Django from a previous version, you will need to uninstall the old Django version before installing the new version.

If you installed Django using pip or easy_install previously, installing with pip or easy_install again will automatically take care of the old version, so you don’t need to do it yourself.


Installing an official release with pip (권장)

This is the recommended way to install Django.

각 project별로 필요로 하는 개발 환경이 다르므로 virtualenv를 사용하여 프로젝트 별로 가성설정환경을 만들어준다.

$ sudo apt-get update

$ sudo apt-get install python3-pip    // python -> pip   python3 ->pip3

$ sudo pip3 install virtualenv           

$ virtualenv uwsgi-tutorial   // uwsgi-tutorial 라는 이름으로 virtualenv 생성

$ cd uwsgi-tutorial

$ source bin/activate   // vitualenv 활성화 

활성화 성공 :  hostname@server.~/uwsgi-tutorial ->(uwsgi-tutorial)hostname@server.~/uwsgi-tutorial 

virtualenv가 활성화 된 상태에서 Django를 설치

$ pip3 install django

$ django-admin.py startproject testproject



$ pip3 install uwsgi

$ sudo vi test.py     // ~/uwsgi-tutorial 폴더 안에 작성

   def application(env, start_response):

start_response('200 OK', [('Content', 'text/html')])

return [b"Hello World"] # python3

$ uwsgi -http :8000 -wsgi-file test.py  // 127.0.0.1:8000 접속 Hello World 확인

$ cd testproject

$ python3 manage.py runserver 0.0.0.0:8000  //127.0.0.1:8000 접속 It Works 확인

$ uwsgi --http :8000 --module testproject.wsgi  //127.0.0.1:8000 접속 It Works 확인


NginX setting

NginX 설치후 virtualenv 폴더로 이동해 testproject-nginx.conf를 작성한다.
$cd ~/uwsgi-tutorial
$ sudo vi testproject_nginx.conf  //아래 내용 작성  빨간색 본인에 맞게 수정

# testproject_nginx.conf

# the upstream component nginx needs to connect to upstream django {     # server unix:///path/to/your/mysite/mysite.sock; # for a file socket     server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server {     # the port your site will be served on     listen 8000;

    # the domain name it will serve for     server_name yourhost; # substitute your machine's IP address or FQDN     charset utf-8;

    # max upload size     client_max_body_size 75M; # adjust to taste     # Django media     location /media {     alias /home/username/uwsgi-tutorial/testproject/media; # your Django project's media files -amend as required     }     location /static {     alias /home/username/uwsgi-tutorial/testproject/static; # your Django project's static files - amend as required     }     # Finally, send all non-media requests to the Django server.     location / {     uwsgi_pass django;     include /home/username/uwsgi-tutorial/testproject/static/uwsgi_params; # the uwsgi_params file you installed     } }


$ cd /etc/nginx/sites-enabled
$ sudo ln -s /home/username/uwsgi-tutorial/testproject_nginx.conf /etc/nginx/sites-enabled/
$ cd ~/uwsgi-tutorial/testproject/testproject/
$ vi settings.py   //아래 내용 추가
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
$cd ../
$ ln -s ./testproject/settings 
$ python3 manage.py collectstatic // yes를 입력하면 static폴더 생성
$ cd static
$ vi uwsgi_params  //아래 내용 작성 
uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

TCP Port socket을 사용한 uWSGI 구조 web client <-> web server <-> socket <-> uWSGI <-> Python

구현이 간단함 : 오버헤드가 큼

$ service nginx status   // nginx server 상태 확인

$ service nginx restart  //nginx server 다시 시작

$ cd ../../     // ~/uwsgi-tutorial 폴더로 이동

$ uwsgi --socket : 8001 --wsgi-file test.py   //이전에 만들어놓은 test.py로 nginx와 uWSGI 연동확인

127.0.0.1:8000(8000으로 접속하면 testproject_nginx.conf에서 8001 호출함)


Unix socket을 사용한 uWSGI 구조 web client <-> web server <-> socket <-> uWSGI <-> Python

다소 복잡하지만 오버헤드가 적음

$vi testproject_nginx.conf    // 아래 내용 수정

server unix: ///tmp/testproject.sock; # for a file socket

# server 127.0.0.1:8001; # a web port socket (we'll use this first)

$ service nginx restart

$ uwsgi --socket /tmp/testproject.sock --wsgi-file test.py --chmod-socket=666  //모든 사용자 읽기쓰기 권한 부여


Unix Socket 을 이용한 Django 실행하기 

$ cd testproject/testproject

$ vi settings.py   // 아래부분 찾아서 호스트 추가

ALLOWED_HOSTS = [  //djongo 2.0 부터 보안강화로 인하여 ALLOW_HOSTS 등록 필수 

    'yourhost.com',

    'loclahost',

    '127.0.0.1',           

]

$ cd ..

$ uwsgi --socket /tmp/testproject.sock --module testproject.wsgi --chmod-socket=666  //It Works


.ini file을 이용한 uWSGI 실행하기


실행문구 간단히 하기 위함


$vi testproject_uwsgi.ini

# mysite_uwsgi.ini file

[uwsgi]


# Django-related settings


# the base directory (full path)

chdir           = /home/username/uwsgi-tutorial/testproject/


# Django's wsgi file

module          = testproject.wsgi


# the virtualenv (full path)

home            = /home/username/uwsgi-tutorial


# process-related settings


# master

master          = true


# maximum number of worker processes

processes       = 1


# the socket (use the full path to be safe

socket          = /tmp/testproject.sock


# ... with appropriate permissions - may be needed

chmod-socket    = 666


# clear environment on exit

vacuum          = true


$ uwsgi --ini testproject_uwsgi.ini


virtualenv 나가기

$ deactivate



Simple sequence

필요한 프로그램이 모두 설치 되어 있다는 전제를 두고 차례로 진행해보자

Let's move on to the assumption that all necessary programs are installed.

이해가 안가는 부분은 링크를 따라가보자.

Let's follow the link where we do not understand.



from django.http import HttpResponse


def index(request):

    return HttpResponse("Hello, world. You're at the polls index.")

from django.urls import path


from . import views


urlpatterns = [

    path('', views.index, name='index'),

]

from django.urls import include, path

from django.contrib import admin


urlpatterns = [

    path('polls/', include('polls.urls')),

    path('admin/', admin.site.urls),

]

~/uwsgi-tutorial/testproject$ python3 manage.py migrate

~/uwsgi-tutorial/testproject$ vi polls/models.py

from django.db import models


class Question(models.Model):

    question_text = models.CharField(max_length=200)

    pub_date = models.DateTimeField('date published')


class Choice(models.Model):

    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    choice_text = models.CharField(max_length=200)

    votes = models.IntegerField(default=0)

~/uwsgi-tutorial/testproject$ vi testproject/setting.py    //Activating models

INSTALLED_APPS = [

    'polls.apps.PollsConfig',   

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

~/uwsgi-tutorial/testproject$ python3 manage.py makemigrations polls

You should see flowing message

Migrations for 'polls':

  polls/migrations/0001_initial.py:

    - Create model Choice

    - Create model Question

    - Add field question to choice

~/uwsgi-tutorial/testproject$ python3 manage.py sqlmigrate polls 0001   //manage your database schema automatically

You should see flowing message

BEGIN;

--

-- Create model Choice

--

CREATE TABLE "polls_choice" (

    "id" serial NOT NULL PRIMARY KEY,

    "choice_text" varchar(200) NOT NULL,

    "votes" integer NOT NULL

);

--

-- Create model Question

--

CREATE TABLE "polls_question" (

    "id" serial NOT NULL PRIMARY KEY,

    "question_text" varchar(200) NOT NULL,

    "pub_date" timestamp with time zone NOT NULL

);

--

-- Add field question to choice

--

ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;

ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;

CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");

ALTER TABLE "polls_choice"

  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"

    FOREIGN KEY ("question_id")

    REFERENCES "polls_question" ("id")

    DEFERRABLE INITIALLY DEFERRED;


COMMIT;

Now, run migrate again to create those model tables in your database:

~/uwsgi-tutorial/testproject$ python3 manage.py migrate

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, polls, sessions

Running migrations:

  Rendering model states... DONE

  Applying polls.0001_initial... OK

Remember the three-step guide to making model changes:

  • Change your models (in models.py).
  • Run python manage.py makemigrations to create migrations for those changes
  • Run python manage.py migrate to apply those changes to the database.

~/uwsgi-tutorial/testproject$ python3 manage.py shell    //Creating & Playing with the API

import datetime


from django.db import models

from django.utils import timezone


class Question(models.Model):

question_text = models.CharField(max_length=200)

pub_date = models.DateTimeField('date published')

def __str__(self):

return self.question_text

def was_published_recently(self):

return self.pub_date >= timezone.now() - datetime.timedelta(days=1)



class Choice(models.Model):

question = models.ForeignKey(Question, on_delete=models.CASCADE)

choice_text = models.CharField(max_length=200)

votes = models.IntegerField(default=0)

def __str__(self):

return self.choice_text

~/uwsgi-tutorial/testproject$ python3 manage.py createsuperuser   //Creating an admin user

Username (leave blank to use 'khjoony'): 

Email address: khjoony4u@gmail.com

Password: 

Password (again): 

Superuser created successfully.


~/uwsgi-tutorial/testproject$ uwsgi --ini testproject_uwsgi.ini 

localhost:8000/polls

localhost:8000/admin

requested page

~/uwsgi-tutorial/testproject$

~/uwsgi-tutorial/testproject$

~/uwsgi-tutorial/testproject$




댓글