728x90
반응형

Error: Could not locate a Flask application. Use the 'flask --app' option, 'FLASK_APP' environment variable, or a 'wsgi.py' or 'app.py' file in the current directory.

flask 개발 초기에 종종 발생하는 에러


아마 사용하는 환경이 맥북이고, set FLASK_APP=testtest 명령어로 설정했을 가능성이 높다.

exprot FLASK_APP=testtest로 변경하고, flask run을 해보자

 

아래 그림처럼 flask 서버가 실행되는 것을 볼 수 있다.

 

-끝-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
728x90
반응형

requests 모듈 설치 하려는데 위 에러 가 뜸.

connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]

- 원인 : 패키지 다운로드 하는 사이트의 ssl 신뢰 X
- 해결: 아래와 같이 사용

pip install --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org {패키지이름}

 

 

1. 해결 케이스


pip install requests 에러남 (아래 처럼 에러메시지 뜸)

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SS                L: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))': /simple/requests/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SS                L: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))': /simple/requests/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SS                L: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))': /simple/requests/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SS                L: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))': /simple/requests/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))': /simple/requests/
Could not fetch URL https://pypi.org/simple/requests/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/requests/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
ERROR: Could not find a version that satisfies the requirement requests (from versions: none)
ERROR: No matching distribution found for requests
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1108)'))) - skipping
WARNING: There was an error checking the latest version of pip.

 

아래처럼 명령어 침

pip install {패키지명} --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org

 

[예시]

pip install --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org requests

 

설치 완료

 

-끝-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
728x90
반응형

조사하는김에 정리

sep='값' : print 출력값 사이 연결
end='값' : print 출력값 이후 출력
값.format() : 특정 값 삽입
escape : \n(개행), \t(탭) 등

 

sep, end, format


소스 복사해서 출력해보면 느낌이 올거다.

#sep
print('a', 'b', 'c', sep='$$$$$')

#출력값
#a$$$$$b$$$$$c


#end
print('a', 'b', 'c', end='\n$$$$$\n')

#출력값
#a b c
#$$$$$


#format
print('{} 앤드 {}'.format('coffee', 'donut'))
#출력값
#coffee 앤드 donut

 

escape 종류


print 구문에서 특수문자를 표현하려면 \(백슬래시)를 붙여줘야된다.


\n : 개행
\t : 탭(
\\ : '\' 
\' : 쿼터
\" : 더블쿼터

 

**Raw string과 F-string 활용


Raw String은 print('내용') 구문 내 특문을 전부 무시해준다.(매우 중요)


특문이 많은 문장을 복붙하거나, 데이터 분석 시 아래와 같은 상황에서는
각 \n 개행마다 텍스트 출력위해 \\n으로 바꿔주기 귀찮다.
ex1) print('1111\\n222\\n1111\\n222\\n1111\\n222\\n1111\\n222\\n1111\\n222\\n')

고로 r을 붙여서 raw string으로 쉽게쓰자
ex2) print(r'1111\n222\n1111\n222\n1111\n222\n1111\n222\n1111\n222\n1111\n222\n')

F-String은 format 기법을 효율적 사용 방안이다. (3.6버전 이상 지원한다.)

txt = 'aaa'
output = f'Its {txt}'
print(output)
# Its aaa

a = 1
b = 2
output = f'합 : {a+b}'
print(output)
# 합 : 3

#참고 https://brownbears.tistory.com/421

그렇다.

 

-끝-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
728x90
반응형

파이썬에서 subprocess 를 쓰다보면 종종 발생한다.

subprocess.call([path1, path2]) 형식의 명령어를 쓰다가 에러가 났고

subprocess.call([path1, path2], shell=True) 식으로 처리해서 해결했다.

에러 그림


다른 방법도 있다고 한다.(재부팅이라던지..)

원리는 아래와 같다.

shell = True로 실행 시 일반 shell에서 명령을 내리는 것과 동일하게
별도 유효성 검사 없이 실행이 된다.

그 뜻은 shell = True 설정을 안넣으면, 디폴트로 false로 잡히니까
유효성 검사가되고, 거기서 에러가 날 수 있다는 거같다.

기술문서 상으로는 추천하는 로직이 아니라고 한다(shell injection에 취약)

근데 에러나서 못하는 것보다 실행을 시켜야되지 않을까.(그냥 자동화 도구니..)

 

참조 문서 : https://docs.python.org/2/library/subprocess.html

 

17.1. subprocess — Subprocess management — Python 2.7.18 documentation

17.1. subprocess — Subprocess management The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions: os.system os.s

docs.python.org

 

-끝이다-

728x90
반응형
728x90
반응형

코드 짠김에 정리한다.


import time


time.sleep(60) # 1분간 sleep

time.sleep(10) # 10초간 sleep

time.sleep(1) # 1초간 sleep

sleep 이 초 단위라는 것만 기억하면된다.

 


javascript는 1000이 1초다.

setInterval(test, 3000);

 

-끝-

728x90
반응형
728x90
반응형

TypeError: string indices must be integers 에러 의미

직역 그대로다.

 

index_t에 'abcde'라는 str(문자열)을 담았다.

 

index_t[0]은 'a' 다.

그리고 0,1,2,3,4 는 1~5번째의 값을 의미한다.

(왜냐. 컴터는 0부터 세니까, 다 아시겠지마는)


 

무튼 string indices must be integers 에러는

 

문자열의 인덱스 즉[값]에 정수만 넣으라는 의미다.

문자열의 값은 0(첫번째 데이터), 1(두번째 데이터) 가져오는데

1.1, 1.2 이러면 'a'도 아니고 'b'도 아니니 에러가 나는것이다.

 


 

string index out of range 에러는

아래 그림과 같이 'a', 'b', 'c', 'd', 'e' 5개의 데이터만 있는데 

범위를 넘어서는 요청을 하면 에러가 난다.

 


 

 

끝이다.

 

728x90
반응형
728x90
반응형

피들러랑 파이썬 requests 모듈 같이 사용하기

검색해보다가 검색 내용처럼 안되서 버프 방식으로 시도했더니 된다.


import os

proxy = '127.0.0.1:8888'
os.environ['HTTP_PROXY'] = proxy
os.environ['HTTPS_PROXY'] = proxy
os.environ['REQUESTS_CA_BUNDLE'] = r'.\FiddlerRoot.pem'

위와 같이 셋팅하고 테스트 하면 된다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
728x90
반응형

[상황]

파이썬에서 다수의 [특문+문자]를 str로 처리하고(1)

base64로 인코딩(2) 해야되는 케이스가 있었다.

 

근데.. 파이썬을 썼다가 안썼다가 하니.. 에러가 주구장창 나서 스트레스르 받았다.

이에 해당 이슈 정리


[발생한 에러 종류]

ValueError: string argument should contain only ASCII characters

TypeError: a bytes-like object is required, not 'str'

UnicodeEncodeError: 'ascii' codec can't encode characters in position 359-361: ordinal not in range(128)


[요약]

<방법1>

utf-8로 변환하고 bs64인코딩, utf-8 디코딩

bs64디코딩 후 utf-8 디코딩

 

text = '임의값 입력'
bs64_text=(base64.b64encode(text.encode('utf-8')))
enc_text=bs64_text.decode('utf-8')
print(enc_text)

print('개행 테스트\n\n\n')

data1 = base64.b64decode(enc_text)
data2 = data1.decode('utf-8')
print(data2)

 

<방법2>

str => encode() = bytes
bytes => decode() = str

mytext_bytes = mytext.encode()  #bytes
mytext_str = mytext_bytes.decode() #str 

encoded=(base64.b64encode(mytext.encode())) #bytes 된거 base64로

tmp = base64.b64decode(encoded) # base64 디코딩

print(tmp.decode()) #base64 디코딩된거 str로

[상세1]

encoded=base64.b64encode(mytext) 실행 시 에러1 발생
 
[에러1]
 TypeError: a bytes-like object is required, not 'str'

<원인> : base64 인코딩할 때 bytes type이 필요해서 에러 터짐

<해결>
str => encode() = bytes 되고
bytes => decode() = str 됨
또는 utf-8로 형변환 함

<예제>
mytext_bytes = mytext.encode()  #bytes
mytext_str = mytext_bytes.decode() #str

########################################################################################################
########################################################################################################


encoded=(base64.b64encode(mytext.encode('ascii'))) 실행 시 에러2 발생
에러3은 원인 까먹음

[에러2,3]
 UnicodeEncodeError: 'ascii' codec can't encode characters in position 359-361: ordinal not in range(128)
 ValueError: string argument should contain only ASCII characters

<원인/해결>
파이썬 디폴트는 unicode 사용 
한글 사용하려면 unicode를 utf-8로 변환해서 사용 가능  
unicode를 utf-8로 encoding ㄱㄱ

<예제>
encoded=(base64.b64encode(mytext.encode('utf-8'))) # utf-8 변환 또는
encoded=(base64.b64encode(mytext.encode())) # bytes 변환

 

-끝-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

p.s.

아래 사이트를 참고하여 해결하려 했으나. ascii 인코드 수행 시 에러나서 utf-8로 시도하니 됬다.

https://techexpert.tips/ko/python-ko/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%B2%A0%EC%9D%B4%EC%8A%A464-%EC%9D%B8%EC%BD%94%EB%94%A9/

 

728x90
반응형
728x90
반응형

개발하고, 까먹고

개발하고, Javascript 공부하다 까먹고..

그래서 정리합니다.

 

1. GET 방식 보내기

import requests

url = 'https://www.naver.com'

response = requests.get(url)

#상태코드
print(response.status_code)

#UTF-8 형식의 text
print(response.text)

#바이너리 원문 
#print(response.content)

#json
#print(response.json())

 

2. POST 방식 보내기

 

3. Header, Cookie, 

 

4. with

 

5. 세션 

 

 

 

 

기계 - 기계 - 기계 > {휴먼} > 아웃풋

728x90
반응형
728x90
반응형

한글이나 다른 인코딩 인식 안될경우 syntax error 발생함

 

그럴때 코드 상단에 아래 내용 입력

# -*- coding: utf-8 -*-

 

 

종종 이어서 작성 예정

728x90
반응형

+ Recent posts