레이블이 python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 python인 게시물을 표시합니다. 모든 게시물 표시

2020년 1월 7일 화요일

One Program Written in Python, Go, and Rust

https://www.nicolas-hahn.com/python/go/rust/programming/2019/07/01/program-in-python-go-rust/

Python, Go, Rust를 재밌는 글. Go와 Rust에 대한 특징을 잘 정리했다.

Static vs dynamic type system.
Somewhat like giving instructions to someone who always stops you to ask you to clarify what you mean, versus someone who always nods along and seems to understand you, though you’re not always sure they’re absorbing everything.

Rust

I also started with the book instead of just attempting to dive in headfirst. This was massively helpful, and probably the best introduction to any programming language I’ve ever experienced.

2019년 1월 30일 수요일

Multiple server instance 환경에서 form double submit을 server에서 검출하기

Client쪽에서 form의 submit이 중복되지 않도록 막는 방법은 여러가지가 알려져 있다. 모두 JavaScript에서 처리하는 방법들이고, 다양한 질문과 답변들을 찾아보면 개념적으로는 몇가지로 수렴한다.

다중 Server에서 form의 중복 submit을 검출하는 방법은 별로 쓸만한 것을 찾지 못했다.

Server instance가 여러 개이기 때문에 상태를 저장하기 위해 DB 등 외부의 node를 사용해야 한다. Form에 uuid 등 중복되지 않는 키를 할당하고 해당 키에 대해서 트랜잭션이 이미 발생했는지 여부를 DB에 query를 해서 확인하는 방식이다. 그런데, 이 방법은 불필요한 DB transaction이 발생하고, 일정 시간이 지난 후 불필요한 레코드들을 정리해야 해서 귀찮다.

Form이 submit되었을 때 uuid를 키로 사용해서 redis 또는 memcached에 item을 하나 생성해 놓는 것은 좀더 가벼운 해결책이 될 것 같다. 일정 시간이 지나면 cache item은 자동 정리가 되기 때문에 귀찮게 정리해줘야 할 일도 없다.

문제는, cache에 기록하는 작업이 끝나기 전에 cache를 읽으려고 할 때 발생. 두번의 form submit이 발생하는 사이 동일한 시간 간격으로 cache에 접근하려고 할텐데, overlap이 발생하면 중복된 submit을 알아챌 수 없다. django-lock-tokens같은 프로젝트는 resource에 대한 lock을 하는 방식. 그런데, 마찬가지의 문제가 있을 것 같다.

좋은 방법이 없을까?

How to manage concurrency in Django models를 보면 select_for_update를 사용해서 transaction이 끝날 때까지 lock을 하는 (pessimistic) 방법이 나온다.

우리가 사용하는 cache backend는 Redis이니 Distributed locks with Redis에서 제공하는 방법도 좋을 것 같다.

2016년 8월 24일 수요일

Django의 runserver_plus에 올린 Let's Encrypt의 SSL certificate

개발용이지만 https가 필요해서 RunServerPlus를 사용하고 있다. 문제가 생긴 것은 외부의 결제 시스템에서 개발 서버에 접속할 때 아래와 같은 에러가 난다는 것.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

결제 시스템쪽의 JVM을 업데이트하면 좋겠는데, 우리쪽에서 처리를 하라고 연락이 왔다.

https://www.geocerts.com/ssl_checker에 접속해서 certificate를 확인해보라며. certificate를 확인해보니, certificate chain을 확인할 수 없단다.


runserver_plus에는 Certificate chain file을 지정하는 옵션이 보이지 않는다. --cert만 지정할 수 있다. (그런데, 이 옵션이면 되는 것이었다)

Nginx + Gunicorn 또는 uWSGI로 가면서 chain file을 지정하는 방법이 있겠지 하고, uwsgi 설치하고, nginx 설정하고 nginx의 옵션을 알아보는데, crt 파일에 chain path 정보를 같이 넣은 것도 동작한다는 것을 알게 되었다-_-

Let's Encrypt에서 certificate 갱신하면 만드는 파일들이 있다.

  • cert.pem
  • chain.pem
  • fullchain.pem
  • privkey.pem

위의 파일들 중에서 cert.pem을 crt 파일로 symlink해서 사용하고 있었는데, chain 정보도 들어 있는 fullchain.pem을 crt 파일로 symlink한 후 Django를 올리니..


잘 된다.



2016년 2월 29일 월요일

How to add your library path so that find_library can find your dylibs

When you use find_library on OS X you can add your library path to the search path.

    import os
    from ctypes.macholib import dyld

    os.environ['RESOURCEPATH'] = '' # if not set before
    frameworks = os.path.join(os.environ['RESOURCEPATH'], '..', 'Frameworks')
    dyld.DEFAULT_FRAMEWORK_FALLBACK.insert(0, frameworks)
    dyld.DEFAULT_LIBRARY_FALLBACK.insert(0, frameworks)

    find_library("yourlib") # this will look for ../Frameworks/libyourlib.dylib


2015년 11월 7일 토요일

새벽의 취미 생활

토요일이다. 새벽에 일어나서, 어제 저녁에 트위터에 올라와 보던 글을 다시 한 번 읽어 본다.

4 Weeks of Golang: The Good, the Bad, and the Ugly

브라우저에는 Safari Books Online의 책이 열려 있다.

Clojure Reactive Programming

당면한 프로젝트에 사용할 웹 프레임 웍 중 하나로 보고 있는 Gin 홈페이지도 열려 있다.

https://gin-gonic.github.io/gin/

그리고는 Dave Cheney의 동영상과 David Nolen의 ClojureScript 동영상을 한 편씩 본다.

The Legacy of Go by Dave Cheney - GothamGo 2015 Closing Keynote
Alan Kay가 말했다는 "Programming is a pop culture". 공감. gofmt, Interfaces, Goroutines
ClojureScript: Lisp's Revenge by David Nolen
Revenge까지는.
그리고 Dave Cheney의 홈페이지에 가서 Go와 Rust에 대한 글들을 읽는다.

http://dave.cheney.net/2015/10/30/programming-language-markets
Programming Language Markets를 보면 Web/Mobile이 대세라는 것을 알 수 있다. Backend를 차지 하기 위한 경쟁. 그 외 모든 부분에서 C/C++를 대체하기는 요원해보인다.
http://dave.cheney.net/2015/07/02/why-go-and-rust-are-not-competitors
경쟁 상대는 아니지. Rust는 좀더 근본적인 것을 해결하려는 것이고, 잘 되어서 C/C++을 대신할 수 있길 기대.
http://dave.cheney.net/2015/08/08/performance-without-the-event-loop
Go의 최대 장점
http://dave.cheney.net/2015/11/05/lets-talk-about-logging
좀 억지스럽다고 할까. Feature를 최소화해야 한다는 생각에는 동의. 
http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
Optional parameter가 없으니 참 고생들 한다.

오늘의 프로그래밍언어 오덕질/프오덕질/포덕질?

어제 저녁부터 계속 비가 내리고, 화면 오른쪽 상단에 "Firefox 42.0 available" 알림이 뜬다.

2015년 9월 4일 금요일

How to check Windows System Service status with Python


You can check Windows system service status using Python.

Using psutil

>>> import win32serviceutil
>>> win32serviceutil.QueryServiceStatus("Service_Name")
(272, 4, 7, 0, 0, 0, 0) # 4 means it's running
>>> win32serviceutil.QueryServiceStatus("Service_Name")
(272, 1, 0, 0, 0, 0, 0) # 1 means it's stopped

Using wmi

You can lookup with conditions like StartMode and State. Following code enumerates services whose StartMode is "Disabled" and current State is "Stopped".

>>> import wmi
>>> c=wmi.WMI()
>>> c.Win32_Service(StartMode="Disabled", State="Stopped")
[<_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="aspnet_state">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="clr_optimization_v2.0.50727_32">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="clr_optimization_v2.0.50727_64">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="Mcx2Svc">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetMsmqActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetPipeActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetTcpActivator">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="NetTcpPortSharing">, <_wmi_object: \\YEONSH-PC\root\cimv2:Win32_Service.Name="RemoteAccess">]

Check if specific service is running or not. Empty array is returned if the service is not running.

>>> c.Win32_Service(Name="Netlogon", State="Running")
[]

2014년 5월 13일 화요일

파이썬 랜덤 스트링

문자와 숫자로 이루어진 랜덤 스트링을 만드는 간단한 작업에도 다양한 대답들이 달렸다.

python random string generation with upper case letters and digits


파이썬의 모토가 TOOWTD 아니던가? :)

2014년 5월 12일 월요일

Pythonic Clojure

내가 사용하고 싶은 언어는 Pythonic Clojure.

Python과 Clojure의 장점만 합해서 만든 언어라는 것이 가능할지 모르겠다.

사실 파이썬은 GIL 때문에 CPU 코어들을 최대한 활용할 수 없다는 것이 마음에 들지 않고, 그 문제를 해결하려는 의지를 보이지 않는 Guido, 또한 마음에 들지 않는다. (PyPy에 대한 Guido의 태도는 물론이고, 2.x과 3.x 사이의 호환성 문제도 해결 못하고 있는 상황도 그렇고.)

현실에서 텍스트 파일 처리, 빠른 프로토타이핑이나 작은 규모의 웹서비스를 만들 때는 파이썬이 워낙 손에 익어서 사용하지만, 이 범위를 넘어가는 경우에는 매번 다른 도구를 찾게 된다.

그럼에도 불구하고 파이썬을 사용하는 이유는?

  • 읽기 쉬운 깔끔한 코드 형식
  • 사용하기 편한 다양한 내장 자료구조들
  • 정말로 다양한 라이브러리 & 툴들
  • 다양한 오픈소스 프로젝트와 커뮤니티

2009년도 글. Python vs Clojure에서 인상적인 부분.
Well consider a C programmer who has spent 10 years manipulation pointers. What insights has he gained into architectural challenges, concurrency pitfalls, etc? Very little, he spends his days speaking baby-language (low-level) to the compiler in order to get the behavior he wants, at the cost of personal development.

All Your Ducks In A Row: Data Structures in the Std Lib and Beyond

Cache me if you can: memcached