Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách đọc tất cả HTTP headers trong Python CGI script?

Có thể lấy giá trị custom request header trong Apache CGI script với Python. Giải pháp tương tự như sau.

Module mod_cgi của Apache sẽ thiết lập biến môi trường cho mỗi HTTP request header nhận được, các biến này đều có tiền tố HTTP_. Ví dụ x-client-version: 1.2.3 sẽ có sẵn sebagai biến HTTP_X_CLIENT_VERSION.

Để đọc custom header trên, chỉ cần gọi os.environ["HTTP_X_CLIENT_VERSION"].

Script dưới in ra tất cả header HTTP_* và giá trị:

#!/usr/bin/env python
import os
print "Content-Type: text/html"
print "Cache-Control: no-cache"
print
print "<html><body>"
for headername, headervalue in os.environ.items():
    if headername.startswith("HTTP_"):
        print "<p>{0} = {1}</p>".format(headername, headervalue)
print "</html></body>"