當前位置:首頁 » 編程語言 » python接收get參數

python接收get參數

發布時間: 2023-09-20 19:24:08

1. python的BaseHTTPServer模塊怎樣接收post請求能給出,把接收到的POST數據輸...

#!/usr/bin/python
#encoding=utf-8
'''
基於BaseHTTPServer的http server實現,包括get,post方法,get參數接收,post參數接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib
import os, sys

class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
mpath,margs=urllib.splitquery(self.path) # ?分割
self.do_action(mpath, margs)

def do_POST(self):
mpath,margs=urllib.splitquery(self.path)
datas = self.rfile.read(int(self.headers['content-length']))
self.do_action(mpath, datas)

def do_action(self, path, args):
self.outputtxt(path + args )

def outputtxt(self, content):
#指定返回編碼
enc = "UTF-8"
content = content.encode(enc)
f = io.BytesIO()
f.write(content)
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html; charset=%s" % enc)
self.send_header("Content-Length", str(len(content)))
self.end_headers()
shutil.fileobj(f,self.wfile)

2. python通過get,post方式發送http請求和接收http響應


本文實例講述了python通過get,post方式發送http請求和接收http響應的方法。姿敏分享給輪敏大家供大家參考。
具體如下:
測試用CGI,名字為test.py,放在apache的cgi-bin目錄下:
#!/usr/bin/python
import cgi
def main():
print Content-type: text/htmln
form = cgi.FieldStorage()
if form.has_key(ServiceCode) and form[ServiceCode].value != :
print h1 Hello,form[ServiceCode].value,/h1
else:
print h1 Error! Please enter first name./h1
main()
python發送post和get請求
get請求:
使用get方式時,請求數據直接放在url中。
方法一、
?
7
8
import urllib
import urllib2
url =
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
?
7
import httplib
url =
conn = httplib.HTTPConnection(192.168.81.16)
conn.request(method=GET,url=url)
response = conn.getresponse()
res= response.read()
print res
post請求:臘冊枝
使用post方式時,數據放在data或者body中,不能放在url中,放在url中將被忽略。
方法一、
import urllib
import urllib2
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
11
import urllib
import httplib
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
headerdata = {Host:192.168.81.16}
conn = httplib.HTTPConnection(192.168.81.16)
conn.request(method=POST,url=requrl,body=test_data_urlencode,headers = headerdata)
response = conn.getresponse()
res= response.read()
print res
對python中json的使用不清楚,所以臨時使用了urllib.urlencode(test_data)方法;
模塊urllib,urllib2,httplib的區別
httplib實現了http和https的客戶端協議,但是在python中,模塊urllib和urllib2對httplib進行了更上層的封裝。
介紹下例子中用到的函數:
1、HTTPConnection函數
httplib.HTTPConnection(host[,port[,stict[,timeout]]])
這個是構造函數,表示一次與伺服器之間的交互,即請求/響應
host 標識伺服器主機(伺服器IP或域名)
port 默認值是80
strict 模式是False,表示無法解析伺服器返回的狀態行時,是否拋出BadStatusLine異常
例如:
conn = httplib.HTTPConnection(192.168.81.16,80) 與伺服器建立鏈接。
2、HTTPConnection.request(method,url[,body[,header]])函數
這個是向伺服器發送請求
method 請求的方式,一般是post或者get,
例如:
method=POST或method=Get
url 請求的資源,請求的資源(頁面或者CGI,我們這里是CGI)
例如:
url=
或者
url=
body 需要提交到伺服器的數據,可以用json,也可以用上面的格式,json需要調用json模塊
headers 請求的http頭headerdata = {Host:192.168.81.16}
例如:
?
test_data = {ServiceCode:aaaa,b:bbbbb}
test_data_urlencode = urllib.urlencode(test_data)
requrl =
headerdata = {Host:192.168.81.16}
conn = httplib.HTTPConnection(192.168.81.16,80)
conn.request(method=POST,url=requrl,body=test_data_urlencode,headers = headerdata)
conn在使用完畢後,應該關閉,conn.close()
3、HTTPConnection.getresponse()函數
這個是獲取http響應,返回的對象是HTTPResponse的實例。
4、HTTPResponse介紹:
HTTPResponse的屬性如下:
read([amt]) 獲取響應消息體,amt表示從響應流中讀取指定位元組的數據,沒有指定時,將全部數據讀出;
getheader(name[,default]) 獲得響應的header,name是表示頭域名,在沒有頭域名的時候,default用來指定返回值
getheaders() 以列表的形式獲得header
例如:
?
1
2
3
4
5
date=response.getheader(date);
print date
resheader=
resheader=response.getheaders();
print resheader
列形式的響應頭部信息:
?
1
2
3
[(content-length, 295), (accept-ranges, bytes), (server, Apache), (last-modified, Sat, 31 Mar 2012 10:07:02 GMT), (connection, close), (etag, e8744-127-4bc871e4fdd80), (date, Mon, 03 Sep 2012 10:01:47 GMT), (content-type, text/html)]
date=response.getheader(date);
print date
取出響應頭部的date的值。
希望本文所述對大家的Python程序設計有所幫助。

3. Python爬蟲筆記(二)requests模塊get,post,代理

  import requests

  base_url = 'https://www..com'

  response = requests.get(base_url)

        url=請求url,

        headers =請求頭字典,

        params = 請求參數字典。

        timeout = 超時時長,

    )---->response對象

  伺服器響應包含:狀態行(協議,狀態碼)、響應頭,空行,響應正文

    字元串格式:response.text

    bytes類型:response.content

        response.headers['cookie']

    response.text獲取到的字元串類型的響應正文,

    其實是通過下面的步驟獲取的:

        response.text = response.content.decode(response.encoding)

    產生的原因:編碼和解碼的編碼格式不一致造成的。

        str.encode('編碼')---將字元串按指定編碼解碼成bytes類型

        bytes.decode('編碼')---將bytes類型按指定編碼編碼成字元串。

    a、response.content.decode('頁面正確的編碼格式')

        <meta http-equiv="content-type" content="text/html;charset=utf-8">

    b、找到正確的編碼,設置到response.encoding中

        response.encoding = 正確的編碼

        response.text--->正確的頁面內容。

  a、沒有請求參數的情況下,只需要確定url和headers字典。

  b、get請求是有請求參數。

    在chrome瀏覽器中,下面找query_string_params,

    將裡面的參數封裝到params字典中。

  c、分頁主要是查看每頁中,請求參數頁碼欄位的變化,

  找到變化規律,用for循環就可以做到分頁。

  requests.post(

    url=請求url,

    headers = 請求頭字典,

    data=請求數據字典

    timeout=超時時長

  )---response對象

  post請求一般返回數據都是json數據。

(1)response.json()--->json字元串所對應的python的list或者dict

(2)用 json 模塊。

    json.loads(json_str)---->json_data(python的list或者dict)

    json.mps(json_data)--->json_str

  post請求能否成功,關鍵看**請求參數**。

  如何查找是哪個請求參數在影響數據獲取?

  --->通過對比,找到變化的參數。

  變化參數如何找到參數的生成方式,就是解決這個ajax請求數據獲取的途徑。

**尋找的辦法**有以下幾種:

    (1)寫死在頁面。

    (2)寫在js中。

    (3)請求參數是在之前的一條ajax請求的數據裡面提前獲取好的。

  代理形象的說,他是網路信息中轉站。

  實際上就是在本機和伺服器之間架了一座橋。

  a、突破自身ip訪問現實,可以訪問一些平時訪問不到網站。

  b、訪問一些單位或者團體的資源。

  c、提高訪問速度。代理的伺服器主要作用就是中轉,

  所以一般代理服務裡面都是用內存來進行數據存儲的。

  d、隱藏ip。

    ftp代理伺服器---21,2121

    HTTP代理伺服器---80,8080

    SSL/TLS代理:主要用訪問加密網站。埠:443

    telnet代理 :主要用telnet遠程式控制制,埠一般為23

    高度匿名代理:數據包會原封不動轉化,在服務段看來,就好像一個普通用戶在訪問,做到完全隱藏ip。

    普通匿名代理:數據包會做一些改動,伺服器有可能找到原ip。

    透明代理:不但改動數據,還會告訴服務,是誰訪問的。

    間諜代理:指組織或者個人用於記錄用戶傳輸數據,然後進行研究,監控等目的的代理。   

  proxies = {

    '代理伺服器的類型':'代理ip'

  }

  response = requests.get(proxies = proxies)

  代理伺服器的類型:http,https,ftp

  代理ip:http://ip:port

4. python flask 怎麼接受參數

GET方式

fromflaskimportFlask,render_template,request
#InitializetheFlaskapplication
app=Flask(__name__)
#Thisisacatchallroute,tocatchanyrequesttheuserdoes
@app.route('/')
defindex():
qs=request.query_string
returnrender_template('index.html',query_string=qs)
if__name__=='__main__':
app.run(
host="0.0.0.0",
port=int("80"),
)

POST方式

fromflaskimportrequest
@app.route('/login',methods=['POST','GET'])
deflogin():
error=None
ifrequest.method=='POST':
ifvalid_login(request.form['username'],
request.form['password']):
returnlog_the_user_in(request.form['username'])
else:
error='Invalisername/password'
#
#
returnrender_template('login.html',error=error)


當然這些官方的開發文檔都有的

熱點內容
python賦值運算符 發布:2025-02-02 03:00:51 瀏覽:903
怎麼查詢電腦ip地址和dns伺服器 發布:2025-02-02 02:57:50 瀏覽:238
資料庫應用系統的概念 發布:2025-02-02 02:44:46 瀏覽:547
存儲甘油違法 發布:2025-02-02 02:35:36 瀏覽:991
壓縮譜寫法 發布:2025-02-02 02:26:33 瀏覽:936
ipad電子書上傳 發布:2025-02-02 02:22:14 瀏覽:403
堅果郵件怎麼配置 發布:2025-02-02 02:15:14 瀏覽:333
安卓跟h5哪個好 發布:2025-02-02 02:07:56 瀏覽:853
vcjava 發布:2025-02-02 02:06:27 瀏覽:339
航海世紀55區是什麼伺服器 發布:2025-02-02 02:01:22 瀏覽:836