programing

플라스크에 http 헤더를 넣는 방법

randomtip 2022. 10. 23. 11:56
반응형

플라스크에 http 헤더를 넣는 방법

저는 Python을 처음 접해 Python Flask를 사용하고 REST API 서비스를 생성합니다.

클라이언트에 보낸 승인 헤더를 확인하고 싶습니다.

하지만 플라스크에 HTTP 헤더를 넣는 방법을 찾을 수 없습니다.

HTTP 헤더 인가를 받기 위한 도움말이 있으면 감사하겠습니다.

from flask import request
request.headers.get('your-header-name')

request.headers는 딕셔너리처럼 동작하기 때문에, 임의의 딕셔너리에서와 같이 헤더를 취득할 수도 있습니다.

request.headers['your-header-name']

단지 주의해 주세요.헤더가 존재하지 않는 경우 메서드의 차이는

request.headers.get('your-header-name')

돌아온다None예외 없이 사용할 수 있습니다.

if request.headers.get('your-header-name'):
    ....

그러나 다음 항목은 오류를 발생시킵니다.

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

다음 방법으로 처리할 수 있습니다.

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

전달된 헤더를 모두 가져오려는 경우 다음 명령을 사용하십시오.

dict(request.headers)

모든 헤더를 딕트 형식으로 제공하므로 실제로 원하는 작업을 수행할 수 있습니다.내 사용 사례에서는 python API가 프록시였기 때문에 모든 헤더를 다른 API로 전송해야 했다.

플라스크에서 어떻게 파라암, 머리글, 본체를 얻을 수 있는지 봅시다.우체부의 도움을 받아 설명할게요.

여기에 이미지 설명 입력

파라미터 키와 값은 API 엔드포인트에 반영됩니다.예를 들어 엔드 포인트의 key1key2 입니다.https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

    key_1 = request.args.get('key1')
    key_2 = request.args.get('key2')
    print(key_1)
    #--> value1
    print(key_2)
    #--> value2

파라미터 후에 헤더를 취득하는 방법에 대해 설명하겠습니다.

여기에 이미지 설명 입력

header_1 = request.headers.get('header1')
header_2 = request.headers.get('header2')
print(header_1)
#--> header_value1
print(header_2)
#--> header_value2

이제 시체를 어떻게 구하는지 봅시다

여기에 이미지 설명 입력

file_name = request.files['file'].filename
ref_id = request.form['referenceId']
print(ref_id)
#--> WWB9838yb3r47484

업로드한 파일을 요청으로 가져옵니다.파일 및 텍스트(요청 포함)를 지정합니다.형태

언급URL : https://stackoverflow.com/questions/29386995/how-to-get-http-headers-in-flask

반응형