2016-12-08 2 views
1

로깅 목적으로 URL의 암호를 모호하게하고 싶습니다. 나는, 구문 분석 더미 암호를 사용하여 암호를 대체하고 unparsing에 의해, urlparse을 사용하는 기대했다, 그러나 이것은 나에게주고있다 :URL에 난독 화 암호가 있습니다.

>>> from urllib.parse import urlparse 
>>> parts = urlparse('https://user:[email protected]/aaa/bbb') 
>>> parts.password = 'xxx' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: can't set attribute 

그래서 대안은 잔인한 것 같다 this을 것 같다.

표준 라이브러리를 사용하면 암호를 쉽게 교체 할 수 있습니까?

+0

'parts' 여기에 무엇입니까? – AKS

+0

@AKS : 죄송합니다. 분명하다고 생각했습니다. 더 많은 컨텍스트를 추가했습니다. – dangonfast

+0

@janbrohl : 그것이 바로 링크 된 스크립트가하는 일이며, urlparse가 별도의 구성 요소를 설정할 수 없기 때문에 과장된 것으로 보입니다. – dangonfast

답변

4

urlparse이라는 하위 클래스 ()를 반환합니다. 새 복사본을 생성하려면 namedtuple._replace() method을 사용하고 geturl()을 사용하여 '파싱을 취소합니다'.

암호는 더 구문 분석 할 수있는 netloc 속성의 일부입니다 :

from urllib.parse import urlparse 

def replace_password(url): 
    parts = urlparse(url) 
    if parts.password is not None: 
     # split out the host portion manually. We could use 
     # parts.hostname and parts.port, but then you'd have to check 
     # if either part is None. The hostname would also be lowercased. 
     host_info = parts.netloc.rpartition('@')[-1] 
     parts = parts._replace(netloc='{}:[email protected]{}'.format(
      parts.username, host_info)) 
     url = parts.geturl() 
    return url 

데모 :

>>> replace_password('https://user:[email protected]/aaa/bbb') 
'https://user:[email protected]/aaa/bbb' 
+0

그것은 유쾌하다! 그것을 시험하게하십시오. – dangonfast

+0

@delavnog : 약간의 문제 : 암호 필드가 없습니다. 오른쪽 필드로 업데이트하겠습니다. –

+0

'part.password가 None이 아닌지 확인하는 것이 왜 좋을까요? ' – warvariuc