Python獲取請求頭Header的常用方法
1. 使用 Flask 獲取請求頭
Flask 是一個輕量級的 Python Web 框架,可以通過 request.headers 獲取請求頭。
from flask import Flask, request
app = Flask(__name__)
@app.route('/get_headers', methods=['GET', 'POST'])
def get_headers():
# 獲取所有請求頭
headers = request.headers
print(headers)
# 獲取某個特定的請求頭(例如:Authorization)
auth_header = request.headers.get('Authorization')
print(f"Authorization Header: {auth_header}")
return "Request headers processed."
if __name__ == '__main__':
app.run(debug=True)
2. 使用 Django 獲取請求頭
Django 是一個更全面的 Python Web 框架,可以通過 request.META 獲取請求頭信息。
from django.http import HttpResponse
from django.views import View
class GetHeadersView(View):
def get(self, request):
# 獲取所有請求頭
headers = request.META
print(headers)
# 獲取某個特定的請求頭(例如:Authorization)
auth_header = request.META.get('HTTP_AUTHORIZATION')
print(f"Authorization Header: {auth_header}")
return HttpResponse("Request headers processed.")
# 在 urls.py 中添加路由
# from django.urls import path
# from .views import GetHeadersView
#
# urlpatterns = [
# path('get_headers/', GetHeadersView.as_view(), name='get_headers'),
# ]
3. 通用方法(使用 http.server)
如果你沒有使用任何框架,而是直接使用 Python 的內(nèi)置 http.server 模塊來處理 HTTP 請求,可以通過 BaseHTTPRequestHandler 的 headers 屬性來獲取請求頭。
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 獲取請求頭
headers = self.headers
print(headers)
# 獲取某個特定的請求頭(例如:Authorization)
auth_header = self.headers.get('Authorization')
print(f"Authorization Header: {auth_header}")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"Request headers processed.")
def run(server_class=HTTPServer, handler_class=SimpleRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print("Server running on port 8000...")
httpd.serve_forever()
if __name__ == '__main__':
run()
總結(jié)
- 如果你使用 Flask,可以通過 request.headers 獲取請求頭。
- 如果你使用 Django,可以通過 request.META 獲取請求頭。
- 如果你沒有使用任何框架,可以通過 http.server 的 self.headers 獲取請求頭。
根據(jù)你使用的框架或工具,選擇合適的方法即可。
到此這篇關(guān)于Python獲取請求頭Header的常用方法的文章就介紹到這了,更多相關(guān)Python獲取請求頭Header內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Python中封裝GObject模塊進行圖形化程序編程的教程
這篇文章主要介紹了在Python中封裝GObject模塊進行圖形化程序編程的教程,本文來自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下2015-04-04
Python列表轉(zhuǎn)一維DataFrame的完整指南
在數(shù)據(jù)處理領(lǐng)域,Pandas的DataFrame是當(dāng)之無愧的王者,本文將用5個核心方法,教你優(yōu)雅地將一維列表轉(zhuǎn)換為Pandas DataFrame,感興趣的可以了解下2025-04-04

