Djnago Logging



LOGGING = {

    'version': 1,

    'disable_existing_loggers': False,

    'formatters': {

        'standard': {

            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",

            'datefmt' : "%Y-%m-%d %H:%M:%S"

        },

    },

    'handlers': {

        'null': {

            'level': 'DEBUG',

            'class': 'logging.NullHandler',

        },

        'console': {

            'level': 'INFO',

            'class': 'logging.StreamHandler',

            'formatter': 'standard',

        },

        'file': {

            'level': 'INFO',

            'class': 'logging.handlers.RotatingFileHandler',

            'filename': 'access.log',

            'formatter': 'standard',

            'maxBytes': 1024*1024*100,

            'backupCount': 10,

        },

    },

    'loggers': {

        'django': {

            'handlers': ['console'],

            'level': 'DEBUG',

            'propagate': False,

        },

        'api': {

            'handlers': ['file'],

            'level': 'DEBUG',

            'propagate': False,

        },

    },

    'root': {

        'level': 'DEBUG',

        'handlers': ['console'],

    }

}

 propagate 

logging.getLogger() 인자값 없이 생성하면 root logger 가 생성됨

logging.getLogger("이름") 인자값을 넘겨주고 생성하면 "이름" 으로 logger 가 생성됨

두 logger는 부모와 자식 관계를 갖음 

이때 자식 logger 에서 부모 logger 에도 로그 메시지를 넘겨 줄수 잇는데 그 기능이 propagate 임.

사용하지 않으려면 False 로 성정하면 됨


만약 위 설정에서 api 로거의 propagate 를 True 로 하고 로그를 남기면

file, console 두곳에 같은 로그메시지가 전달됨


/path/to/projectname/projectname/settings.py 에 정의함






















- 피보나치 수는 0과 1로 시작하며, 다음 피보나치 수는 바로 앞의 두 피보나치 수의 합이 된다. n = 0, 1,...에 해당하는 피보나치 수는

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946... 이다.


제너레이터

참고: http://bluese05.tistory.com/56

참고: https://mingrammer.com/translation-iterators-vs-generators

참고: https://www.snip2code.com/Snippet/1571818/yield-send---generator------example


일단적인 함수는 사용이 종료되면 결과값을 호출부로 반환 후 함수 자체를 종료시킨 후 메모리 상에서 클리어된다 

하지만 yield 를 사용할 경우는 다르다.

generator 함수가 실행 중 yield 를 만날 경우, 해당 함수는 그 상태로 정지 되며 반화값을 next() 를 호출한 쪽으로 전달하게 된다.

이후 해당 함수는 일반적인 함수처럼 종료되고 메로리상에서 클리어되는게 아니라 그 yield 를 만나 시점의 상태로 유지되게 된다.

즉 함수에서 사용된 local 변수나 instrunction pointer 긍과 같은 함수 내부에서 사용된 데이터들이 메모리에 그대로 유지되는것이다.



def fib():

    past_num, curr_num = 0, 1

    while 1:

        yield curr_num

        past_num, curr_num = curr_num, past_num + curr_num


>> f = fib()

>> f.next()

1

>> f.next()

1

>> f.next()

2

>> f.next()

3

>> f.next()

5

>> f.next()

8


>>> from itertools import islice

>>> f = fib()      

>>> list(islice(f, 1, 10))

[1, 2, 3, 5, 8, 13, 21, 34, 55]

>>> f.next()

89



피보나치 수를 제너레이터로 구현한거


>>> def index_words_iter(text):

...     if text:

...         yield 0

...     for index, letter in enumerate(text):

...         if letter == ' ':

...             yield index + 1

... 

>>> 

>>> list(index_words_iter(address))

[0, 5, 11, 15, 21, 27, 31]

>>> 

>>> 

>>> f = index_words_iter(address)

>>> 

>>> f.next()

0

>>> f.next()

5

>>> f.next()

11

>>> f.next()

15

>>> f.next()

21

>>> f.next()

27

>>> f.next()

31

>>> f.next()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration


list 롤 감싸게 되면 StopIteration 발생하면 리턴해주는가부네 




'TF' 카테고리의 다른 글

[Research] Django  (0) 2017.06.29
[Research] API gateway  (0) 2017.06.29
[Research] microservice  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27

- http basic authentification

https://ponytech.net/blog/use-http-basic-authentification-login


- api 설계지 보안관련 부분참조 할 내용

https://www.slideshare.net/brotherjinho/restful-api-64494716

절대세션 사용하지 말것, request 마다 다 인증거치게 해야함

https 만 사용해야함


- nginx(ssl) + django

https://simpleisbetterthancomplex.com/tutorial/2016/05/11/how-to-setup-ssl-certificate-on-nginx-for-django-application.html


proxy_redirect 지시자는 http response 헤더중에  Location 과 Refresh 헤더를 조작한다.

서버가 Location 헤더에 url 를 지정해서 response 를 해주면 브라우저는 자동으로 Location 에 지정된 url 로 이동하고  response 를 받아온다.

참조: http://storyj.net/http-%EA%B8%B0%EC%B4%88-%EB%8C%80%ED%91%9C%EC%A0%81%EC%9D%B8-http%ED%95%B4%EB%8D%94/


reverse proxy

clinet request 를 받아서 실제 서비스 하는 서버로 전달하는 일을 한다. 

참고: https://www.joinc.co.kr/w/man/12/proxy

'TF' 카테고리의 다른 글

[Research] fibonacci number  (0) 2017.06.30
[Research] API gateway  (0) 2017.06.29
[Research] microservice  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27

참조:

- https://github.com/ecidi/djangoapigateway

'TF' 카테고리의 다른 글

[Research] fibonacci number  (0) 2017.06.30
[Research] Django  (0) 2017.06.29
[Research] microservice  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27

참조:

- https://www.slideshare.net/saltynut/building-micro-service-architecture


단점:

- 복잡한구조

- 복잡함테스트

- 멀티디비 transaction 관리

- 배포/운영 자동화가 필요

- 여러서비스들과 합치기 어려운 개발 특징

'TF' 카테고리의 다른 글

[Research] Django  (0) 2017.06.29
[Research] API gateway  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27
[Research] Quota/Spike difference  (0) 2017.06.27

- high availability

https://n3tc4t.github.io/blog/simple-dbha-for-django-app

https://www.slideshare.net/fdintino/high-availability-django-djangocon-2016


profiling(성능분석):

• Hosted services: New Relic, Opbeat 

• django-debug-toolbar, django-silk 

• cProfile / pyprof2calltree / KCacheGrind for masochists 

• WSGI middleware


monitoring(모니터링)

• Downtime notifications: Alertra, New Relic, Opbeat, Chartbeat 

• Nagios and its many forks, Zabbix


Caching 

• Use a CDN 

• Proxy cache (Nginx, Squid, Varnish) 

• {% cache %}, @cached_property, CachedStaticFilesStorage, cached template loader 

• Page caching frameworks 

• ORM caching: a mixed bag


Query optimization 

• .prefetch_related(), .select_related() 

• prefetch_related_objects() for generic foreign keys

• .values() and .values_list() where it counts, if possible 

• Database parameter tuning, judicious indexing


uWSGI 

• Broad and active community  (넓고 활성화된 커뮤니티)

• Very thorough documentation (overwhelming, in fact) (친절한문서)

• Highly configurable (설정이다양함)


'TF' 카테고리의 다른 글

[Research] API gateway  (0) 2017.06.29
[Research] microservice  (0) 2017.06.29
[Research] openstack  (0) 2017.06.27
[Research] Quota/Spike difference  (0) 2017.06.27
[Research] 스파이크( spike)  (0) 2017.06.27

- https://www.suse.com/documentation/suse-openstack-cloud-7/singlehtml/book_cloud_admin/book_cloud_admin.html#get-started-conceptual-architecture

- https://indigo-dc.gitbooks.io/synergy-doc/content/doc/admin.html

- http://inter6.tistory.com/category/OpenStack



'TF' 카테고리의 다른 글

[Research] microservice  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] Quota/Spike difference  (0) 2017.06.27
[Research] 스파이크( spike)  (0) 2017.06.27
[Research] API (Application Programming Interface)  (0) 2017.06.27

참조: https://community.apigee.com/questions/35903/what-is-main-difference-between-quota-policy-and-s.html

1. Quota Policy: This policy is used to meet up the business requirements where business decides the no. of calls allowed for a product/developer/developer app etc and also they can decide pricing for different products based on no. of calls allowed. This ensures business that no developer/app can make calls more than the allowed limit.

2. Spike Arrest: This policy is used to avoid spikes in traffic and protect your backend systems against spikes so I will take it as a measure to protect/secure your API.


01. Quota Policy : It defines a time window ( for example 1 hour or 1 minute ) and within that time a fixed number of request are honored. For example, in 1 hour 10 requested are allowed and the user is free to make all the 10 request in 1 second or 1 hour. The basic idea is that only 10 request are allowed in an hour and make sure a user can make a fixed number of request

02. Spike Arrest. This policy specifies the total number of request and divides between the time interval that is defined. If the number of request is more then that calculated amount that the policy will block access. The idea behind is to make sure the traffic that is coming to the server or handled by target system is smooth and sudden burst of request does not impact.performance.


Quota Policy helps you limit the number of requests per time interval. For instance, setting quota policy rate to 10 per minute, it is possible to hit all 10 requests in the first few seconds of a minute.

Spike Arrest Policy, on the other hand helps you limit the sudden increase in the number of requests at any point in time. For instance, setting spike arrest policy rate to 10 per minute, it does the following calculations to limit the sudden spike/increase in the number of requests -

10 per minute = 10 per 60 seconds = 1 per 6 seconds 

It will not allow more than 1 request every 6 seconds. In this way, we can ensure that all 10 requests are not made within the initial seconds of a minute.

Spike Arrest Policy helps in reducing the risk of automated request generation through malicious code.

The examples are well explain in the Apigee Documentation -

Quota Policy

Spike Arrest Policy

'TF' 카테고리의 다른 글

[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27
[Research] 스파이크( spike)  (0) 2017.06.27
[Research] API (Application Programming Interface)  (0) 2017.06.27
[Define] TF 란?  (0) 2017.06.27

최근 보안 연구원들이 컴퓨터와 라우터, 사물인터넷 기기에 침투해 대규모의 동시 다발적인 디도스 공격을 감행할 수 있는 새로운 툴킷을 찾았다고 밝혔다.


6개월 전, 디도스 대응 전략을 연구하던 아카마이는 ‘스파이크(Spike)’라는 이름의 툴킷을 발견하고 이툴깃이 자사의 아시아와 미국 기업 고객에게 디도스 공격을 감행하는 것을 저지했다.


아카마이의 PLX서트(PLXsert) 연구소장 데이비드 페르단데즈는 “스파이크로 인한 디도스 공격 가운데 하나는 초당 215 기가바이트의 공격, 그리고 초당 1억 5,000만 패킷을 보내는 등 상당한 수준이었다”고 설명했다.


스파이크는 리눅스와 윈도우, 그리고 ARM 기반의 시스템에 침투할 수 있다는 것이 특징인데, 이로 인해 PC, 라우터, 그리고 스마트 온도기와 같은 다양한 사물인터넷 기기가 스파이크의 공격에 노출돼 있다.


아카마이는 현재까지 감염된 기기 가운데 아직 사물인터넷 기기는 없었다고 밝혔다. 하지만 스파이크의 개발자들이 ARM과 리눅스를 대상으로 한 바이너리 페이로드까지 포함시킨 것을 감안했을 때, 앞으로 사물인터넷 기기가 공격받을 가능성은 존재한다. 페르난데즈는 이에 대해 “사물인터넷 기기는 앞으로 스파이크와 같은 디도스 공격의 대상이 될 수 있다”고 경고했다.


이 외에도 스파이크는 동시에 다양한 형식의 디도스 공격을 할 수 있다는 점에서 차이가 난다. 예를 들어, 공격자는 스파이크를 통해 4개의 서로 다른 커맨드-컨트롤 서버를 사용해 하나의 SYN이나 UDP, GET, 그리고 DNS 쿼리를 공격할 수 있다.


아카마이는 스파이크가 중국어로 쓰였다는 것을 감안해 진원지를 아시아로 보고 있다.


스파이크를 차단하기 위해 기업은 접근 제한 목록을 열어보고자 공격 당한 인프라를 추가할 수 있다. 애플리케이션 단에서 공격을 차단하기 위해 아카마이는 SNORT를 배포했다. SNORT는 오픈소스 네트워크 침입 탐지 및 방지 시스템으로 쓰이고 있다.


아카마이는 이 외에도 각종 보안 패치를 최신 버전으로 업데이트할 것과 SANS, 마이크로소프트, NIST(National Institute of Standards and Technology), OWASP(Open Web Application Security Project) 등에서 배포한 가이드를 따를 것을 권고하고 있다.


또한, 아카마이는 아직 스파이크 봇넷이 초기 단계에 있는 만큼, 감염 시스템 청소를 위해 보안 업체 및 관련 정부 기관 등 많은 보안 연구 커뮤니티에게 적극적으로 협조를 요청하고 있다. 아카마이는 “만약 보안 커뮤니티들이 적극적으로 대처하지 않는다면 스파이크 봇으로 인한 감염은 더욱 확산될 것”이라고 경고했다


원문보기: 

http://www.ciokorea.com/tags/13301/%EC%8A%A4%ED%8C%8C%EC%9D%B4%ED%81%AC/22439#csidx3a83816c27b2e169580a2541f1580b6 

'TF' 카테고리의 다른 글

[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27
[Research] Quota/Spike difference  (0) 2017.06.27
[Research] API (Application Programming Interface)  (0) 2017.06.27
[Define] TF 란?  (0) 2017.06.27

- API 란? API-Best-Practices-ebook-2016-12.pdf

- 네이버 API 신입사원 교육: https://github.com/quki/web-api-practice

- django 예제: https://github.com/jihyungSong/pyengine

- API 설계시 참조할 구조: http://catmaid.readthedocs.io/en/stable/contributing.html


'TF' 카테고리의 다른 글

[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27
[Research] Quota/Spike difference  (0) 2017.06.27
[Research] 스파이크( spike)  (0) 2017.06.27
[Define] TF 란?  (0) 2017.06.27

+ Recent posts