2011-07-07 4 views
0

私はHTTP転送で遊んでいます。私はGAEサーバを持っていると私は私が私のブラウザでそれに行くとき、それはレンダリングので、それが正常に働いているかなり確信しているが、ここではPythonのコードは、とにかくです:私はちょうど全体のHTTP POST対を勉強HTTP telnet POST/GAEサーバーの質問(簡単なスタッフ)

import sys 
print 'Content-Type: text/html' 
print '' 
print '<pre>' 
number = -1 
data = sys.stdin.read() 
try: 
    number = int(data[data.find('=')+1:]) 
except: 
    number = -1 
print 'If your number was', number, ', then you are awesome!!!' 
print '</pre>' 

応答処理対GETが、これは、私は端末からやっているものです:

$ telnet localhost 8080 
Trying 127.0.0.1... 
Connected to localhost. 
Escape character is '^]'. 
GET http://localhost:8080/?number=28 HTTP/1.0 

HTTP/1.0 200 Good to go 
Server: Development/1.0 
Date: Thu, 07 Jul 2011 21:29:28 GMT 
Content-Type: text/html 
Cache-Control: no-cache 
Expires: Fri, 01 Jan 1990 00:00:00 GMT 
Content-Length: 61 

<pre> 
If your number was -1 , then you are awesome!!! 
</pre> 
Connection closed by foreign host. 

私がTelnet POSTの仕事をしようとして約40分間の周りにつまずいたので、私はここでGETを使用しています - いいえ成功を収めて: (

私はこのGETおよび/またはtを取得する方法についての助けに感謝します彼は働くPOST。前もって感謝します!!!!

+1

あなたは可能な限り最も痛みを伴う方法についてでこれをやっています。 WSGIとフレームワークをサーバー上で使用し、クライアント上のカール、wget、またはWebブラウザを使用しないでください。 –

答えて

2

GETを使用すると、要求本体にデータが存在しないため、sys.stdin.read()は失敗します。代わりに、具体的には環境を見てみたいかもしれません。os.environ['QUERY_STRING']

もう1つのことは、正しいリクエストフォーマットを使用していないことです。要求の第2の部分はURLスキーム、ホストまたはポートを含むべきではない、それは次のようになります。別々Host:ヘッダ内のホストを指定

GET /?number=28 HTTP/1.0 

。サーバーは独自のスキームを決定します。

POSTを使用している場合、ほとんどのサーバーはContent-Lengthヘッダーのデータ量を超えて読み取ることはありません。これを指定しないと、ゼロバイトとみなされる可能性があります。サーバーは、永続的な接続の次の要求であるcontent-lengthで指定されたポイントの後にバイトを読み取ろうとします。有効な要求で始まらない場合は、接続を閉じます。基本的に:

POST/HTTP/1.0 
Host: localhost: 8080 
Content-Length: 2 
Content-Type: text/plain 

28 

しかし、なぜこれをtelnetでテストしていますか?カールはいかがですか? Pythonで

$ curl -vs -d'28' -H'Content-Type: text/plain' http://localhost:8004/ 
* About to connect() to localhost port 8004 (#0) 
* Trying ::1... Connection refused 
* Trying 127.0.0.1... connected 
* Connected to localhost (127.0.0.1) port 8004 (#0) 
> POST/HTTP/1.1 
> User-Agent: curl/7.20.1 (x86_64-redhat-linux-gnu) libcurl/7.20.1 NSS/3.12.6.2 zlib/1.2.3 libidn/1.16 libssh2/1.2.4 
> Host: localhost:8004 
> Accept: */* 
> Content-Type: text/plain 
> Content-Length: 2 
> 
* HTTP 1.0, assume close after body 
< HTTP/1.0 200 OK 
< Date: Thu, 07 Jul 2011 22:09:17 GMT 
< Server: WSGIServer/0.1 Python/2.6.4 
< Content-Type: text/html; charset=UTF-8 
< Content-Length: 45 
< 
* Closing connection #0 
{'body': '28', 'method': 'POST', 'query': []} 

またはより良いまだ、:

>>> import httplib 
>>> headers = {"Content-type": "text/plain", 
...   "Accept": "text/plain"} 
>>> 
>>> conn = httplib.HTTPConnection("localhost:8004") 
>>> conn.request("POST", "/", "28", headers) 
>>> response = conn.getresponse() 
>>> print response.read() 
{'body': '28', 'method': 'POST', 'query': []} 
>>> 
+0

はい、それは働きました - ありがとうトン。 (それはsys.environの代わりにos.environでした) – startuprob